@vcp-dev/site-edit-engine 0.11.33 → 0.11.35
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.d.ts +76 -68
- package/dist/index.js +21 -17
- package/package.json +7 -3
package/dist/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import*as U_ from"@babel/parser";import*as jt from"@babel/types";import*as _r from"node:path";var vu=[".tsx",".ts",".jsx",".js"],V_=vu.map(e=>`/index${e}`),K_=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 $g(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&K_.has(n[1].toLowerCase())}function Ug(e){let t=[];for(let n of e.program.body)jt.isImportDeclaration(n)&&typeof n.source.value=="string"&&mt(n.source.value)&&t.push(n.source.value),jt.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&mt(n.source.value)&&t.push(n.source.value),jt.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&mt(n.source.value)&&t.push(n.source.value);return jt.traverseFast(e.program,n=>{let r=jt.isImportExpression(n)?n.source:jt.isCallExpression(n)&&jt.isImport(n.callee)?n.arguments[0]:null;jt.isStringLiteral(r)&&mt(r.value)&&t.push(r.value)}),t}function mt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Kn(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 J_(e,t){for(let n of Vg(e))if(await t(n))return n;return null}function Vg(e){return[...vu.some(t=>e.endsWith(t))?[e]:[],...vu.map(t=>`${e}${t}`),...V_.map(t=>`${e}${t}`)]}function Rr(e,t,n){let r=Kn(e,t);if(!mt(t)||!Kg(e,t,r))return null;for(let o of Vg(r))if(n.has(o))return o;return null}async function oo(e,t,n){let r=await ua(e,t,n);return r.ok?r.path:null}async function ua(e,t,n){let r=Kn(e,t);try{if(!Kg(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 J_(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 Kg(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 z_}from"node:crypto";import*as Jg from"@babel/parser";function io(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:io(t,n,r,o)}}function Iu(e,t,n,r,o){return{ok:!1,source:e,diagnostic:io(t,n,r,o)}}var X_={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Jn(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Jg.parse(t,{sourceType:"module",plugins:X_[n]})}}catch(r){return{ok:!1,source:t,diagnostic:io("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function ku(e,t){return Jn({source:e,profile:Xg(t.kind)})}function Oi(e,t){return Jn({source:e,profile:Xg(t)})}function Xg(e){return"next-app-entry"}function so(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 Ee=(e,t)=>{let n=Jn({source:t,profile:so({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${z_("sha256").update(t).digest("hex")}`,ast:n.ast,imports:Ug(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function H_(e,t){return Ee(e,t)}function W_(e,t){return Kn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as G_,parseComponentI18nResourcesJson as Y_,resolveSiteTextDirection as Z_,SiteLocaleSchema as q_}from"@vcp-dev/contracts";var Q_=["i18next","react-i18next"],eR="components/ui/site-locale-provider.tsx",tR="components/ui/component-i18n-provider.tsx",zg="app/layout.tsx";async function Fi(e){let t=e.files.filter(f=>f.path.endsWith(G_));if(t.length===0)return{ok:!0};for(let f of["package.json",zg,eR,tR])if(!await e.exists(f))return Pr(`Target snapshot is missing required i18n host file: ${f}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return Pr("Target snapshot package.json is invalid.")}let r=Hg(n)&&Hg(n.dependencies)?n.dependencies:{},o=Q_.filter(f=>typeof r[f]!="string"||r[f].trim().length===0);if(o.length>0)return Pr(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(zg),s=_u(i,"html","lang"),a=_u(i,"html","dir"),l=_u(i,"SiteLocaleProvider","locale"),c=q_.safeParse(s);if(!c.success||!a||!l||s!==l||a!==Z_(c.data))return Pr("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 Pr("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=c.data;if(e.targetLocale&&e.targetLocale!==u)return Pr("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let f of t){let g=Y_(f.content);if(!g.success)return Pr(`Component i18n resource is invalid: ${f.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(g.data,u)&&!Object.hasOwn(g.data,d))return Pr(`Component i18n resource ${f.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function _u(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 Hg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pr(e){return{ok:!1,message:e}}import Pu from"@babel/generator";import*as Qg from"@babel/parser";import Cu from"@babel/traverse";import*as nt from"@babel/types";import{computeSiteEditSourceIdentityKey as rR}from"@vcp-dev/contracts";var Wg="data-vcp-ui-component",da="components/ui";function lr(e){if(!e)return!1;let t=Ru(e);return t===da||t.startsWith(`${da}/`)||t.includes(`/${da}/`)||t.endsWith(`/${da}`)}function ao(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?lr(e.slice(2)):e.startsWith("./")||e.startsWith("../")?lr(Ru(`${nR(t)}/${e}`)):lr(e):!1}function Ru(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 nR(e){let t=Ru(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as fV}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as mV,isSiteEditRuntimeTextTag as gV}from"@vcp-dev/contracts/site-edit-runtime-capability";var Gg={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 oR=typeof Pu=="function"?Pu:Pu.default,iR=typeof Cu=="function"?Cu:Cu.default,sR=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),aR="suppressHydrationWarning",cR=new Set(["SiteEditBootstrap"]);function lR(e){let t=fR(e.file,e.projectRoot);if(!dR(e.source)||lr(t))return{code:e.source,elements:[]};let n=e.attributes??Gg,r=Qg.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=mR(r,t);return iR(r,{JSXElement(s){let a=s.node.openingElement,l=a.name;if(!hR(l)||eh(a,n.key))return;let c=xR(s)??"default",u=ER(s),d=rR(t,c,u),f=pa(l)??"unknown",g=pR(l)?"jsx":"component-call";if(g==="component-call"&&!bR(s.node.children)&&cR.has(f))return;let m=g==="component-call"&&gR(f,i);yR(a,n.key,d),m&&Yg(a,Wg),uR(s)&&Yg(a,aR),o.push({key:d,tag:f,componentName:c,sourceFile:t,sourceKind:g})}}),o.length===0?{code:e.source,elements:o}:{code:oR(r,{jsescOption:{minimal:!0}}).code,elements:o}}function uR(e){return!e.findParent(t=>t.isJSXElement())}function dR(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function fR(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 pR(e){return nt.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function pa(e){return nt.isJSXIdentifier(e)?e.name:nt.isJSXMemberExpression(e)?nh(e):null}function mR(e,t){let n=new Set;for(let r of e.program.body)if(!(!nt.isImportDeclaration(r)||!ao(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function gR(e,t){let n=e.split(".")[0]??e;return t.has(n)}function hR(e){let t=pa(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!sR.has(t)}function eh(e,t){return e.attributes.some(n=>nt.isJSXAttribute(n)&&nt.isJSXIdentifier(n.name,{name:t}))}function yR(e,t,n){th(e,nt.jsxAttribute(nt.jsxIdentifier(t),nt.stringLiteral(n)))}function Yg(e,t){eh(e,t)||th(e,nt.jsxAttribute(nt.jsxIdentifier(t),null))}function th(e,t){let n=e.attributes.findIndex(r=>nt.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function nh(e){return`${nt.isJSXIdentifier(e.object)?e.object.name:nh(e.object)}.${e.property.name}`}function xR(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&nt.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 bR(e){return e.some(t=>nt.isJSXElement(t)||nt.isJSXFragment(t))}var Zg=new WeakMap,fa=new WeakMap,Nu=new WeakMap;function ER(e){let t=Zg.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=SR(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Zg.set(e.node,o),o}function SR(e){let t=pa(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${qg(e,t)}`:`${t}#${qg(e,t)}`}function qg(e,t){let n=rh(e)??e.getFunctionParent();if(!n)return 0;let r=Nu.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Nu.get(n.node);o||(o=new Map,Nu.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()?ma(n):vR(n);for(let l of a)if(pa(l.node.openingElement.name)===t){if(i.set(l.node,s),l.node===e.node)return s;s+=1}return i.get(e.node)??0}function vR(e){let t=fa.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!rh(r)&&n.push(r)}}),fa.set(e.node,n),n}function rh(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 ma(e){let t=fa.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(...ma(o));continue}o.isJSXExpressionContainer()&&n.push(...co(o.get("expression")))}return fa.set(e.node,n),n}function co(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return ma(e);if(e.isParenthesizedExpression())return co(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return co(e.get("right"));if(e.isConditionalExpression())return[...co(e.get("consequent")),...co(e.get("alternate"))];if(e.isCallExpression()&&kR(e.node)){let t=e.get("arguments")[0];return IR(t)}return[]}function IR(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return ma(t);if(t.isParenthesizedExpression())return co(t.get("expression"));if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?co(r):[]}return[]}function kR(e){return nt.isMemberExpression(e.callee)&&nt.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as UB,SiteEditPatchPlanSchema as VB}from"@vcp-dev/contracts";function lo(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 ga(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 ha(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 ya(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:_R(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 xa(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:lo(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 _R(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 qM,computeSiteEditCompositionKey as QM,getSiteEditSourceDeleteProtectionReason as eB,isSiteEditTextSourcePath as tB,parseSiteEditRepeatInstanceKey as nB,SITE_EDIT_SOURCE_DELETE_CAPABILITY as rB,stripSiteEditRepeatInstanceKeys as en}from"@vcp-dev/contracts";import Al from"node:path";import{parse as oB}from"yaml";import Fu from"node:path";import{TextDecoder as PR}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as ih,SITE_EDIT_SOURCE_ALLOWED_DIRS as sh,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as ah,SiteEditCompositionContextSchema as CR,SiteEditSourceFileResponseSchema as Au,SiteEditSourceLocationSchema as NR,SiteEditSourcePathSchema as ba,SiteEditSourceTreeResponseSchema as AR,isSiteEditTextSourcePath as TR}from"@vcp-dev/contracts";import{createHash as RR}from"node:crypto";var Li=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(l=>a===l||a.startsWith(`${l}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let l=Buffer.byteLength(this.files.get(a)??"","utf8"),c=a.split("/").length;if(t.maxDepth!==void 0&&c>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+l>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:l}),s+=l}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 Te(e){return`sha256:${RR("sha256").update(e).digest("hex")}`}var wR=[...ah,...ih,...sh];function Lu(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return CR.parse(e.composition)}var Tu=2e3,wu=12,Ou=24*1024*1024,oh=512*1024,OR=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),FR={".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"},LR={".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"},DR=new PR("utf-8",{fatal:!0});async function Ea(e,t={}){let n=Lu(t),{files:r,truncated:o}=await KR(e,t),i=zR(r.map(s=>s.metadata));return AR.parse({composition:n,nodes:i,defaultPath:HR(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Sa(e,t,n={}){let r=Lu(n),o=ba.parse(t.path),i=await BR(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Mu(o)){let a=uh(o),l=await $R(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Au.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...l})}let s=await Du(e,o);return s.ok?Au.parse({composition:r,path:o,kind:"text",language:dh(o),sizeBytes:s.sizeBytes,contentHash:Te(s.content),readonly:!1,content:s.content}):Au.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function Du(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=MR(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 MR(e){if(e.includes(0))return null;try{return DR.decode(e)}catch{return null}}async function BR(e,t,n){if(!UR(t,n))return null;let r=await jR(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function jR(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=ch(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(Mu(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function $R(e,t){if(!OR.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>oh)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>oh?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function UR(e,t){return ah.some(n=>n===e)||ih.some(n=>n===e)||sh.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 va(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return NR.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 ch(e){return Array.isArray(e)?{files:e}:e}function VR(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function KR(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=ch(await e.listFiles({roots:JR(t),maxFiles:Tu+1,maxDepth:wu,maxTotalBytes:Ou+1})),r=new Map,o=new Set(n.truncated?.reasons),i=0;for(let a of[...n.files].sort((l,c)=>l.path.localeCompare(c.path))){let l=ba.safeParse(a.path);if(!l.success)continue;let c=l.data;if(c.split("/").length>wu){o.add("max-depth");continue}if(r.size>=Tu){o.add("max-files");break}if(i+a.sizeBytes>Ou){o.add("max-total-bytes");break}r.set(c,{path:c,sizeBytes:a.sizeBytes,metadata:XR(c,a.sizeBytes,Lu(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,l)=>a.path.localeCompare(l.path)),...o.size>0?{truncated:{reasons:VR([...o]),maxFiles:Tu,maxDepth:wu,maxTotalBytes:Ou}}:{}}}function JR(e){let t=new Set(wR);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 XR(e,t,n){return Mu(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:uh(e),readonly:!0}:{composition:n,path:e,kind:"text",language:dh(e),sizeBytes:t,readonly:!1}}function zR(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 l=s===r.length-1,c=o.find(u=>u.name===a);if(c||(c=l?{kind:"file",name:a,path:i,file:n}:{kind:"directory",name:a,path:i,children:[]},o.push(c)),l){if(c.kind!=="file")throw new Error(`Source tree path collision: ${n.path}`);c.file=n}else{if(c.kind!=="directory")throw new Error(`Source tree path collision: ${n.path}`);o=c.children}}}return lh(t)}function lh(e){return e.map(t=>t.kind==="directory"?{...t,children:lh(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function HR(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 Mu(e){return!TR(e)}function uh(e){let t=Fu.posix.extname(e).toLowerCase();return!t&&Fu.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":FR[t]??"application/octet-stream"}function dh(e){let t=Fu.posix.extname(e).toLowerCase();return LR[t]??"plaintext"}import*as fo from"@babel/types";import Bu from"@babel/traverse";import*as Xn from"@babel/types";function it(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(Xn.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(Xn.isIdentifier(s)&&s.name==="Fragment"||Xn.isStringLiteral(s)&&s.value==="Fragment")&&fh(i.parentPath)}if(!Xn.isJSXMemberExpression(t)||!Xn.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!Xn.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())&&fh(r.parentPath)}function fh(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var Cr=typeof Bu=="function"?Bu:Bu.default,Ia=new WeakMap,ka=new WeakMap;function zn(e,t){let n=ku(e,t);if(!n.ok)return Iu(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=Ne(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}}:Iu(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function Ne(e,t){return t.kind==="jsx-node"?hh(e,t):t.kind==="jsx-attribute"?QR(e,t):t.kind==="value"?eP(e,t):t.kind==="expression"?tP(e,t):t.kind==="directive"?nP(e,t):t.kind==="export"?rP(e,t):{ok:!1,diagnostic:io("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function hh(e,t){return t.strategy==="source-range"?WR(e,t):GR(e,t)}function WR(e,t){let n=null;if(Cr(e,{JSXElement(o){if(!uo(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(!uo(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(!uo(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(!uo(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 _t("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!gP(r.path,t.expectedIdentity)?_t("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function GR(e,t){if(t.structuralPath===""){let r=ZR(e,t.component);if(r){let o=qR(r);if(o)return o}}let n=null;return Cr(e,{JSXElement(r){if(Mi(r)!==t.component||$u(r)!==t.structuralPath)return;let i=bt("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Mi(r)!==t.component||$u(r)!==t.structuralPath)return;let i=bt("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=YR(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:_t("jsx-node","locator-miss","JSX node not found for structural-path locator")}function YR(e,t,n){let r=null;return Cr(e,{JSXElement(o){if(Mi(o)!==t||!uo(o.node,n))return;let i=bt("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Mi(o)!==t||!uo(o.node,n))return;let i=bt("jsx-node",o);i&&(r=i,o.stop())}}),r}function ZR(e,t){let n=null;return Cr(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 qR(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 _t("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?_t("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 _t("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function QR(e,t){let n=hh(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(l=>hP(l,t.name));if(!s||!s.isJSXAttribute())return _t("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=bt("jsx-attribute",s);return a?{ok:!0,match:a}:_t("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function eP(e,t){let n=oP(e,t);if(!n.ok)return n;let r=iP(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!dr(r.match.path.node.loc,t.expectedRange)?_t("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function tP(e,t){let n=null;return Cr(e,{Identifier(r){if(!dP(r))return;let o=mh(r);if(!o||!gh(o,t))return;let i=bt("expression",r);i&&(t.expectedRange&&!dr(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=mh(r);if(!o||!gh(o,t))return;let i=bt("expression",r);i&&(t.expectedRange&&!dr(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:_t("expression","locator-miss","Expression not found")}function nP(e,t){let n=null;return Cr(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!dr(i.node.loc,t.expectedRange))return;let s=bt("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:_t("directive","locator-miss",`Directive '${t.value}' not found`)}function rP(e,t){let n=null;return Cr(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let l=r.get("declaration");if(l.isFunctionDeclaration()&&l.node.id?.name==="generateMetadata"){let f=bt("export",l);if(!f||t.expectedRange&&!dr(l.node.loc,t.expectedRange))return;n=f,r.stop();return}if(!l.isVariableDeclaration())return;let c=Uu(l,"generateMetadata");if(!c||!c.isVariableDeclarator())return;let u=c.get("init");if(!u.node)return;let d=bt("export",u);if(!d||t.expectedRange&&!dr(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Uu(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!dr(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&&!dr(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:_t("export","export-not-found",`Export '${mP(t)}' not found`)}function oP(e,t){let n=null;return Cr(e,{Expression(r){if(n||t.root.kind!=="expression"||!uo(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 l=s.node.callee;if((l.type==="Identifier"?l.name:l.type==="MemberExpression"&&l.property.type==="Identifier"?l.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=Uu(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}:_t("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 iP(e,t){let n=ju(e);for(let o of t){if(n=ju(n),o.kind==="property"){if(!n.isObjectExpression())return _t("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(c=>!c.isObjectProperty()))return _t("value","unsupported-syntax","Spread properties are not supported");let l=a.find(c=>yP(c,o.name));if(!l||!l.isObjectProperty())return _t("value","property-not-found",`Property '${o.name}' not found`);n=l.get("value");continue}if(!n.isArrayExpression())return _t("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return _t("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return _t("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=ju(n);let r=bt("value",n);return r?{ok:!0,match:r}:_t("value","locator-miss","Resolved value has no source range")}function ju(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 uo(e,t){return dr(e.loc,t)}function dr(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 $u(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!it(n)){let o=xh(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${ph(n,o)}`):t.unshift(`${o}#${ph(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||lP(n.parentPath)&&!uP(n.parentPath))break;n=n.parentPath}return t.join("/")}function ph(e,t){let n=yh(e)??e.getFunctionParent();if(!n)return 0;let r=Ia.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Ia.get(n.node)?.get(t);if(!i){let a=Ia.get(n.node);a||(a=new Map,Ia.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?Di(n):sP(n);for(let a of s)if(xh(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function sP(e){let t=ka.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!yh(r)&&n.push(r)}}),ka.set(e.node,n),n}function yh(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(it(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Di(e){let t=ka.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(...Di(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Di(o));continue}o.isJSXExpressionContainer()&&n.push(...ur(o.get("expression")))}return ka.set(e.node,n),n}function ur(e){if(e.isJSXElement())return it(e)?Di(e):[e];if(e.isJSXFragment())return Di(e);if(e.isParenthesizedExpression())return ur(e.get("expression"));if(e.isLogicalExpression()&&aP(e.node.operator))return ur(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 l=a.get("init");(l.isJSXElement()||l.isJSXFragment())&&i.push(...ur(l))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...ur(a));break}}return i}else if(o.node&&o.isExpression())return ur(o)}}}}return e.isConditionalExpression()?[...ur(e.get("consequent")),...ur(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:ur(t)):[]}function aP(e){return e==="&&"||e==="||"||e==="??"}function xh(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?cP(e.name):null}function cP(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 Mi(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 lP(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function uP(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 dP(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function mh(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 gh(e,t){return e.base===t.base&&fP(e.path,t.path??[])}function fP(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 pP(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function mP(e){return e.exportKind==="named"?e.name:e.exportKind}function _t(e,t,n,r){return{ok:!1,diagnostic:io(t,n,e,r)}}function gP(e,t){return Mi(e)!==t.component?!1:$u(e)===t.structuralPath}function hP(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Uu(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function yP(e,t){return e.isObjectProperty()?pP(e.node)===t:!1}import*as Eh from"@babel/parser";import{arrayExpression as vP,booleanLiteral as IP,identifier as kP,jsxAttribute as _P,jsxExpressionContainer as RP,jsxIdentifier as PP,nullLiteral as CP,numericLiteral as NP,objectExpression as AP,objectProperty as TP,stringLiteral as Ku}from"@babel/types";import Vu from"@babel/generator";var xP=typeof Vu=="function"?Vu:Vu.default;function bP(e){let t=e.split(`
|
|
2
|
-
`),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let l=a[1];l.includes(" ")?r=!0:l.length>0&&n.push(l.length)}}if(r&&t.every(a=>{let l=a.match(/^(\s+)/);return!l||l[1].includes(" ")}))return"tab";if(n.length===0)return"2";function o(s,a){return a===0?s:o(a,s%a)}let i=n[0];for(let s=1;s<n.length;s++)i=o(i,n[s]);return i>=4?"4":"2"}function
|
|
3
|
-
`).map(r=>
|
|
4
|
-
`)}function _a(e){let{ast:t,source:n}=e;try{let r=bP(n),i=xP(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=SP(i,r)),{ok:!0,source:i}}catch(r){return ne(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 Bi(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 Xe(e,t,n){let r=_a({ast:e,source:t});return r.ok?Bi(t,r.source,n):r}function rt(e,t){let n=Oi(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Ra(e,t){return _a({ast:e,source:t})}function wP(e,t,n){let r=Ne(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function jo(e,t,n){let r=wP(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 Nr(e){return typeof e=="string"?Ku(e):typeof e=="number"?NP(e):typeof e=="boolean"?IP(e):e===null?CP():Array.isArray(e)?vP(e.map(t=>Nr(t))):AP(Object.entries(e).map(([t,n])=>{let r=TP(Ju(t),Nr(n));return t==="__proto__"&&(r.computed=!0),r}))}function OP(e){return typeof e=="string"?Ku(e):RP(Nr(e))}function ji(e,t){return _P(PP(e),OP(t))}function Pa(e,t){try{let r=Eh.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 Ju(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?kP(e):Ku(e)}function Ca(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=rt(t,"jsx-node");if(!i.ok)return i.result;let s=Ne(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let l=FP(s.match.path)[r];if(!l)return ne(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(l.kind){case"jsx-text":{let c=l.path.node.value;if(o.trim().length===0){let d=c.match(/^\s*/)?.[0]??"",f=c.match(/\s*$/)?.[0]??"";l.path.replaceWithMultiple([...d?[fo.jsxText(d)]:[],fo.jsxExpressionContainer(fo.stringLiteral("")),...f?[fo.jsxText(f)]:[]]);break}let u=LP(c,o);l.path.node.value=u,l.path.node.extra={rawValue:u,raw:u.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/{/g,"{").replace(/}/g,"}")};break}case"string-literal":l.path.node.value=o;break;case"template-literal":{let c=l.quasiIndex;l.path.node.quasis[c].value.raw=o.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${").replace(/\r/g,"\\r"),l.path.node.quasis[c].value.cooked=o;break}}return Xe(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function FP(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=DP(r.get("expression"));o.length>0&&t.push(...o)}}return t}function LP(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function DP(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 Xu}from"@babel/types";function po(e){let{source:t,locator:n}=e,r=rt(t,"jsx-node");if(!r.ok)return r.result;let o=Ne(r.ast,n);return o.ok?(MP(o.match.path),Xe(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function MP(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Xu());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Xu());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Xu());return}e.remove()}import{cloneNode as BP}from"@babel/types";function $o(e){let t=rt(e.source,"jsx-node");if(!t.ok)return t.result;let n=Ne(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=Pa(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(BP(r.node,!0)),Xe(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as GP}from"@babel/types";import zu from"@babel/traverse";import*as be from"@babel/types";function $i(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 jP=typeof zu=="function"?zu:zu.default;function En(e,t,n,r){if(!e.ok)return e;let o=bn(n,t);if(!o)return e;let i=$P(t,o,r);return i?{...e,selectionRef:i}:e}function $P(e,t,n){let r=UP(e,t);if(!r)return;let o=n.sourceLocator?Sh(n.sourceLocator):void 0,i=n.targetParentLocator?Sh(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??KP(r)??i?.component??o?.component;if(!(!s||!a))return{key:$i(s,a,JP(r))}}function Sh(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function UP(e,t){let n=Ph(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Ph(e,t){let n=null;return jP(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function bn(e,t){if(!e)return null;if(be.isJSXElement(e))return WP(t,e)?vh(e.children,t):e;if(be.isJSXFragment(e))return vh(e.children,t);if(be.isJSXExpressionContainer(e)||be.isParenthesizedExpression(e)||be.isTSAsExpression(e)||be.isTSSatisfiesExpression(e)||be.isTSTypeAssertion(e)||be.isTSNonNullExpression(e))return bn(e.expression,t);if(be.isLogicalExpression(e))return bn(e.right,t);if(be.isConditionalExpression(e))return bn(e.consequent,t)??bn(e.alternate,t);if(be.isCallExpression(e)||be.isOptionalCallExpression(e))return Ch(e)?VP(e.arguments[0],t):null;if(be.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=bn(n,t);if(r)return r}return null}function vh(e,t){for(let n of e){let r=bn(n,t);if(r)return r}return null}function VP(e,t){return!e||!be.isArrowFunctionExpression(e)&&!be.isFunctionExpression(e)?null:be.isBlockStatement(e.body)?Ui(e.body.body,t):bn(e.body,t)}function Ui(e,t){for(let n of e){if(be.isReturnStatement(n)){let r=bn(n.argument,t);if(r)return r;continue}if(be.isBlockStatement(n)){let r=Ui(n.body,t);if(r)return r;continue}if(be.isIfStatement(n)){let r=Ih(n.consequent,t);if(r)return r;let o=n.alternate?Ih(n.alternate,t):null;if(o)return o;continue}if(be.isSwitchStatement(n))for(let r of n.cases){let o=Ui(r.consequent,t);if(o)return o}}return null}function Ih(e,t){return be.isBlockStatement(e)?Ui(e.body,t):Ui([e],t)}function KP(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(be.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&be.isIdentifier(t.node.id)){let n=t.get("init");if(!Array.isArray(n)&&(n.isArrowFunctionExpression()||n.isFunctionExpression()))return t.node.id.name}t=t.parentPath}return null}var kh=new WeakMap,_h=new WeakMap,Hu=new WeakMap;function JP(e){let t=kh.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=XP(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return kh.set(e.node,o),o}function XP(e){let t=Nh(e.node.openingElement.name);return!t||it(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Rh(e,t)}`:`${t}#${Rh(e,t)}`}function Rh(e,t){let n=zP(e);if(!n)return 0;let r=Hu.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Hu.get(n.node);o||(o=new Map,Hu.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of mo(n))if(Nh(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 zP(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 mo(e){let t=_h.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(...mo(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...mo(o));continue}o.isJSXExpressionContainer()&&n.push(...Hn(o.get("expression")))}return _h.set(e.node,n),n}function Hn(e){if(e.isJSXElement())return it(e)?mo(e):[e];if(e.isJSXFragment())return mo(e);if(e.isParenthesizedExpression())return Hn(e.get("expression"));if(e.isLogicalExpression())return Hn(e.get("right"));if(e.isConditionalExpression())return[...Hn(e.get("consequent")),...Hn(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Hn(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Ch(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?HP(n):[]}return[]}function HP(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return it(t)?mo(t):[t];if(t.isJSXFragment())return mo(t);if(t.isParenthesizedExpression())return Hn(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Hn(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(...Hn(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...Hn(o)),n}return n}function Ch(e){let t=e.callee;return(be.isMemberExpression(t)||be.isOptionalMemberExpression(t))&&be.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function WP(e,t){let n=Ph(e,t);return n?it(n):!1}function Nh(e){return be.isJSXIdentifier(e)?e.name:be.isJSXMemberExpression(e)?Ah(e):be.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Ah(e){return`${be.isJSXIdentifier(e.object)?e.object.name:Ah(e.object)}.${e.property.name}`}function Ar(e,t){if(t.parentPath===e&&t.listKey==="children"&&Wu(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!Wu(n))return null;let r=n;for(;r&&r!==e;){if(!Wu(r)||!it(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function Wu(e){return e.isJSXElement()||e.isJSXFragment()}function Sn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=rt(t,"jsx-node");if(!a.ok)return a.result;let l=Ne(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-child target must be a JSXElement or JSXFragment","jsx-node");let c=l.match.path;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=Pa(t,r.jsx);if(!u.ok)return u.result;let d=GP(u.node,!0),f=c.node.children,g={...s,targetParentLocator:n},m=b=>s?En(b,a.ast,d,g):b;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=Ne(a.ast,i);if(!p.ok)return{ok:!1,source:t,diagnostic:p.diagnostic};let h=Ar(l.match.path,p.match.path);if(!h)return ne(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");c=h;let x=c.node.children,E=x.findIndex(b=>b===p.match.path.node);return E===-1?ne(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,d),m(Xe(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Th from"@babel/parser";import{cloneNode as YP}from"@babel/types";function Na(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=rt(t,"jsx-node");if(!a.ok)return a.result;let l=ZP(t,r);if(!l.ok)return l.result;let c=Ne(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-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");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=c.match.path,d=null;if(i){let x=Ne(a.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let E=Ar(c.match.path,x.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=x.match.path.node}else if(o==="before"||o==="after")return ne(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=YP(l.node,!0),g=u.node.children,m={...s,targetParentLocator:n},p=x=>s?En(x,a.ast,f,m):x;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 h=g.findIndex(x=>x===d);return h===-1?ne(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(g.splice(o==="before"?h:h+1,0,f),p(Xe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function ZP(e,t){try{let r=Th.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 qP,nullLiteral as Gu}from"@babel/types";import*as Tr from"@babel/types";import*as wh from"@babel/types";function Vi(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!wh.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function go(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=rt(t,"jsx-node");if(!a.ok)return a.result;let l=Ne(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};let c=Ne(a.ast,r);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","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let u=c.match.path;if(c.match.path.isJSXElement()){let b=c.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return ne(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let b=Ne(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let S=b.match.path.isJSXElement()?Vi(b.match.path,c.match.path):b.match.path,v=Ar(c.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=l.match.path.isJSXElement()?Vi(l.match.path,c.match.path):l.match.path,m=qP(g.node,!0);if(!Tr.isJSXElement(m)&&!Tr.isJSXExpressionContainer(m)&&!Tr.isJSXFragment(m)&&!Tr.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");QP(g);let h=u.node.children,x={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return h.push(m),En(Ra(a.ast,t),a.ast,m,x);if(o==="prepend")return h.unshift(m),En(Ra(a.ast,t),a.ast,m,x);let E=f-(p!==-1&&p<f?1:0);return h.splice(o==="before"?E:E+1,0,m),En(Ra(a.ast,t),a.ast,m,x)}function QP(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Gu());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Gu());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Gu());return}e.remove()}import*as Oh from"@babel/parser";import{cloneNode as eC,nullLiteral as Yu}from"@babel/types";function Aa(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,l=rt(t,"jsx-node");if(!l.ok)return l.result;let c=tC(t,s);if(!c.ok)return c.result;let u=Ne(l.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=Ne(l.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 b=d.match.path.node;if(!b.closingElement||b.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 b=Ne(l.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let S=Ar(d.match.path,b.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=b.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=eC(c.node,!0);nC(u.match.path);let h={...a,sourceLocator:n,targetParentLocator:r},x=m.children;if(o==="append")return x.push(p),En(Xe(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,p,h);if(o==="prepend")return x.unshift(p),En(Xe(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,p,h);let E=x.findIndex(b=>b===g);return E===-1?ne(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,p),En(Xe(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,p,h))}function tC(e,t){try{let r=Oh.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 nC(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Yu());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Yu());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Yu());return}e.remove()}import{SiteEditSetPropsParamsSchema as rC,classifySiteEditPropertyName as oC}from"@vcp-dev/contracts";import*as Uo from"@babel/types";function Ta(e){let t=rC.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=rt(e.source,"jsx-node");if(!n.ok)return n.result;let r=jo(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let l=oC(a.name);if(l.owner!=="generic")return ne(e.source,"unsupported-syntax",l.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(Uo.isJSXAttribute),s=new Map;for(let a of i){let l=iC(a);if(!l)continue;let c=s.get(l)??[];c.push(a),s.set(l,c)}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 l=s.get(a.name)?.[0];if(a.operation==="remove"){l&&(o.attributes=o.attributes.filter(u=>u!==l));continue}let c=ji(a.name,a.value).value;l?l.value=c:o.attributes.push(ji(a.name,a.value))}return Xe(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function iC(e){return Uo.isJSXIdentifier(e.name)?e.name.name:Uo.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as sC}from"@vcp-dev/contracts";import*as se from"@babel/types";var Fh=["prefetch","replace","scroll","locale","onNavigate"],aC=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function cC(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>se.isJSXAttribute(n)&&se.isJSXIdentifier(n.name)&&aC.test(n.name.name)))return!0;t=t.parentPath}return!1}function wa(e){let t=rt(e.source,"jsx-node");if(!t.ok)return t.result;let n=jo(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=sC.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return fr(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=gC(s.name);if(!a)return fr(e.source,"Unsupported JSX link tag");if(s.attributes.some(se.isJSXSpreadAttribute))return fr(e.source,"Link elements with spread props cannot be transformed safely");let l=new Map;for(let m of s.attributes){if(!se.isJSXAttribute(m))continue;let p=qu(m);if(!p)return fr(e.source,"Unsupported JSX attribute name");let h=l.get(p)??[];h.push(m),l.set(p,h)}if([...l.values()].some(m=>m.length>1))return fr(e.source,"Duplicate JSX attributes cannot be transformed safely");let c=l.get("href")?.[0];if(c&&!mC(c))return fr(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:dC(o,s.name);if(!u&&!d)return fr(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&cC(o))return fr(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=fC(t.ast,o);if(!m.ok)return fr(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")),pC(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"),Fh.forEach(m=>g.add(m))):(g.add("href"),e.link.kind==="native-link"&&Fh.forEach(m=>g.add(m))),s.attributes=s.attributes.filter(m=>{if(!se.isJSXAttribute(m))return!0;let p=qu(m);return!p||!g.has(p)}),e.link.kind!=="none"&&s.attributes.push(se.jsxAttribute(se.jsxIdentifier("href"),se.stringLiteral(e.link.href))),lC(s,e.changes),Xe(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function lC(e,t){for(let n of t){let r=e.attributes.find(s=>se.isJSXAttribute(s)&&qu(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(Zu(n.value)),i=se.jsxAttribute(se.jsxIdentifier(n.name),o);r&&se.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function Zu(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=>Zu(t))):typeof e=="object"?se.objectExpression(Object.entries(e).map(([t,n])=>se.objectProperty(se.isValidIdentifier(t)?se.identifier(t):se.stringLiteral(t),Zu(n)))):se.nullLiteral()}function uC(e){return se.isImportDefaultSpecifier(e)||se.isImportSpecifier(e)&&e.importKind!=="type"&&(se.isIdentifier(e.imported,{name:"default"})||se.isStringLiteral(e.imported,{value:"default"}))}function Lh(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 dC(e,t){if(!se.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!Lh(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function fC(e,t){let n=e.program.body.filter(l=>se.isImportDeclaration(l)&&l.source.value==="next/link"&&l.importKind!=="type"),r=n[0],o=n.flatMap(l=>l.specifiers).find(uC);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},(l,c)=>`NextLink${c+2}`)].find(l=>!i.hasBinding(l)&&!t.scope.hasBinding(l));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 l=se.importDeclaration([a],se.stringLiteral("next/link")),c=0;for(;c<e.program.body.length&&se.isImportDeclaration(e.program.body[c]);)c+=1;e.program.body.splice(c,0,l)}return{ok:!0,localName:s}}function pC(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!Lh(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 mC(e){return!e.value||se.isStringLiteral(e.value)}function gC(e){return se.isJSXIdentifier(e)?e.name:null}function qu(e){return se.isJSXIdentifier(e.name)?e.name.name:null}function fr(e,t){return ne(e,"unsupported-syntax",t,"jsx-node")}import*as wt from"@babel/types";import{classifySiteEditPropertyName as Dh}from"@vcp-dev/contracts";function Oa(e){let t=Dh(e.name),n=Dh(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(!Mh(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=rt(e.source,"jsx-node");if(!r.ok)return r.result;let o=jo(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(c=>wt.isJSXAttribute(c)&&yC(c)===e.name);if(s.length>1)return ne(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=hC(e.object,e.property),l=s[0];if(l)l.value=wt.jsxExpressionContainer(a);else{let c=ji(e.name,"");c.value=wt.jsxExpressionContainer(a),i.attributes.push(c)}return Xe(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function hC(e,t){return Mh(t)?wt.memberExpression(wt.identifier(e),wt.identifier(t)):wt.memberExpression(wt.identifier(e),wt.stringLiteral(t),!0)}function Mh(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function yC(e){return wt.isJSXIdentifier(e.name)?e.name.name:wt.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as bC,identifier as Ki,importDeclaration as EC,importDefaultSpecifier as SC,importNamespaceSpecifier as vC,importSpecifier as IC,isImportDefaultSpecifier as Bh,isImportNamespaceSpecifier as jh,isImportSpecifier as $h,stringLiteral as kC}from"@babel/types";function vn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(h=>!OC(h));if(o!==-1){let h=r[o],x=h&&typeof h=="object"&&"kind"in h?h.kind:void 0;return ne(t,"unsupported-syntax",`Unsupported import spec kind: ${String(x)}`)}let i=AC(r);if(!i.ok)return ne(t,"unsupported-syntax",i.message);let s=rt(t);if(!s.ok)return s.result;let{ast:a}=s,l=a.program,c=l.body.filter(h=>h.type==="ImportDeclaration"&&h.source.value===n),u=new Set(c.flatMap(h=>h.specifiers.flatMap(x=>{let E=FC(h,x);return E?[E]:[]}))),d=i.imports.filter(h=>!u.has(zh(h)));if(d.length===0)return Bi(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let f=TC(l.body),g=d.find(h=>f.has(Qu(h)));if(g)return ne(t,"unsupported-syntax",`Import local binding already exists: ${Qu(g)}`);let m=NC(d);if(m.reduce((h,x)=>h+x.length,0)!==d.length)return ne(t,"unsupported-syntax","Unsupported import specifier grouping");for(let h of m){if(!Jh(Vh(h)))return ne(t,"unsupported-syntax","Unsupported import specifier combination");let x=c.find(E=>_C(E,h));if(x)RC(x,h);else{let E=EC(Uh(h),kC(n));wC(l.body,E),c.push(E)}}return Xe(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function _C(e,t){return e.importKind==="type"?!1:Jh(CC(PC(e),Vh(t)))}function RC(e,t){let n=!1,r=new Set(e.specifiers.map(o=>ed(o)));for(let o of Uh(t)){let i=ed(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return Xh(e.specifiers),{changed:n}}function Uh(e){let t=e.map(n=>{switch(n.kind){case"named":return IC(n.local?Ki(n.local):Ki(n.imported),Ki(n.imported));case"default":return SC(Ki(n.local));case"namespace":return vC(Ki(n.local));default:return n}});return Xh(t),t}function Vh(e){let t=Kh();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 PC(e){let t=Kh();for(let n of e.specifiers)Bh(n)?t.defaultLocals.add(n.local.name):jh(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Kh(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function CC(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Jh(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function Xh(e){let t=[...e.filter(n=>Bh(n)),...e.filter(n=>jh(n)),...e.filter(n=>$h(n))];e.splice(0,e.length,...t)}function NC(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=[],l=t[s],c=n[s];l&&a.push(l),c&&a.push(c),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 AC(e){let t=new Map,n=new Map;for(let r of e){let o=zh(r);if(t.has(o))continue;let i=Qu(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 TC(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(bC(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 wC(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 OC(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 zh(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 Qu(e){return e.kind==="named"?e.local??e.imported:e.local}function FC(e,t){return e.importKind==="type"||$h(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 Vo(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!DC(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=rt(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,l=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(l===-1)return Bi(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let c=a.body[l];return r.length===0?(a.body.splice(l,1),Xe(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(c.specifiers=c.specifiers.filter(u=>!r.some(d=>LC(u,d))),c.specifiers.length===0&&a.body.splice(l,1),Xe(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function LC(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 DC(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 Ji(e){let{source:t,locator:n,next:r}=e,o=Ma(t,n);return o.ok?(o.path.replaceWith(Nr(r)),Xe(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Fa(e){let{source:t,locator:n,index:r,value:o}=e,i=Ma(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,Nr(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 La(e){let{source:t,locator:n,index:r}=e,o=Ma(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 Da(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=Ma(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(l=>l?.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 Ma(e,t){let n=rt(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=Ne(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 Lt from"@babel/types";function Ba(e){let t=rt(e.source,"value");if(!t.ok)return t.result;let n=Ne(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=>Lt.isSpreadElement(a)||Lt.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=>Lt.isObjectProperty(a)&&MC(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"?Lt.unaryExpression("void",Lt.numericLiteral(0)):Nr(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Lt.objectProperty(Ju(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 MC(e){return Lt.isIdentifier(e)?e.name:Lt.isStringLiteral(e)?e.value:Lt.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as BC,isSiteEditRuntimeVoidElementTag as jC}from"@vcp-dev/contracts/site-edit-runtime-capability";function Ko(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function $C(e,t,n){let r=Ko(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,c=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,f=!d&&jC(u),g=d||BC(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 h=p&&(!a||i.importedFrom==="next/link"),x=!i.isPublicUiComponent&&!f&&g&&(!a||m);return{composition:r,key:e,canUpdateText:h,canInsertChild:x,canMove:!c,canRemove:!c,constraints:s}}function ja(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,$C(r,e,t));return n}function td(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:Te(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=UC(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:Te(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:Wh(r),version:{documentVersion:e.route.graph.version,contentHash:Te(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",l=n.get("openingElement").get("attributes").find(d=>d.node===o),c=l?.isJSXAttribute()?l.get("value"):null,u=c?.isJSXExpressionContainer()?VC(c.get("expression")):void 0;return{...i,sourceKind:a,attrRaw:Hh(e.route.source,o),valueRaw:s?Hh(e.route.source,s):null,...u===void 0?{}:{resolvedClassName:u},attrRange:Wh(o),diagnostics:[]}}function Gh(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,l=o?`${a<n.start?" ":""}${o}`:"";return t.slice(0,a)+l+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 UC(e,t){let n=Jn({source:e,profile:so({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=Ne(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:KC(t.sourceRange)});return!r.ok||!r.match.path.isJSXElement()?null:r.match.path}function VC(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 Yh(e){let t=Jn({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 Hh(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Wh(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 KC(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Zh(){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 JC}from"node:crypto";import $a from"node:fs/promises";import nd from"node:path";import{setTimeout as XC}from"node:timers/promises";var zC={async mkdir(e,t){await $a.mkdir(e,t)},async writeFile(e,t,n){await $a.writeFile(e,t,n)},async rename(e,t){await $a.rename(e,t)},async rm(e,t){await $a.rm(e,t)}},HC=new Set(["EACCES","EBUSY","EPERM"]),WC=[10,20,40,80,160];async function GC(e,t,n){for(let r of WC)try{await e.rename(t,n);return}catch(o){if(!YC(o))throw o;await XC(r)}await e.rename(t,n)}function YC(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&HC.has(e.code)}async function Ua(e,t,n=zC){let r=nd.dirname(e),o=nd.basename(e),i=nd.join(r,`.${o}.${process.pid}.${JC()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await GC(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import rd from"@babel/traverse";import*as A from"@babel/types";import*as $e from"@babel/types";function Wn(e,t={}){if($e.isTSAsExpression(e)||$e.isTSSatisfiesExpression(e)||$e.isTSNonNullExpression(e)||$e.isTypeCastExpression(e)||$e.isParenthesizedExpression(e))return Wn(e.expression,t);if($e.isStringLiteral(e))return{status:"resolved",value:e.value};if($e.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if($e.isBooleanLiteral(e))return{status:"resolved",value:e.value};if($e.isNullLiteral(e))return{status:"resolved",value:null};if($e.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($e.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if($e.isUnaryExpression(e)&&e.operator==="void"&&$e.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if($e.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||$e.isSpreadElement(r))return{status:"unresolved"};let o=Wn(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if($e.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!$e.isObjectProperty(r)||r.computed||!$e.isExpression(r.value))return{status:"unresolved"};let o=ZC(r.key);if(o===null)return{status:"unresolved"};let i=Wn(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 $e.isMemberExpression(e)||$e.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function ZC(e){return $e.isIdentifier(e)?e.name:$e.isStringLiteral(e)?e.value:$e.isNumericLiteral(e)?String(e.value):null}var qC=typeof rd=="function"?rd:rd.default;function $t(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 QC(e){return/^[A-Z]/.test(e)}function cd(e){let t=e.openingElement;return A.isJSXIdentifier(t.name)?t.name.name==="Fragment":A.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function Xo(e){return A.isJSXFragment(e)}function Qh(e){return A.isJSXIdentifier(e.name)?e.name.name:A.isJSXMemberExpression(e.name)?ey(e.name):A.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function ey(e){return A.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:A.isJSXMemberExpression(e.object)?`${ey(e.object)}.${e.property.name}`:e.property.name}function eN(e){return e.split(".")[0]??e}function tN(e){let t=e;for(;t;){let n=t.node;if(A.isFunctionDeclaration(n)&&n.id||A.isVariableDeclarator(n)&&A.isIdentifier(n.id))return n.id.name;if(A.isExportDefaultDeclaration(n)){let r=n.declaration;if(A.isFunctionDeclaration(r)&&r.id)return r.id.name;if(A.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function nN(){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 rN(e){let t=new Map;for(let n of e.program.body){if(!A.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(A.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(A.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(A.isImportSpecifier(o)){let i=A.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function pr(e,t=[]){if(A.isIdentifier(e))return t.push(e.name),t;if(A.isObjectPattern(e)){for(let n of e.properties)A.isObjectProperty(n)?pr(n.value,t):A.isRestElement(n)&&pr(n.argument,t);return t}if(A.isArrayPattern(e)){for(let n of e.elements)n&&(A.isRestElement(n)?pr(n.argument,t):pr(n,t));return t}return A.isAssignmentPattern(e)?(pr(e.left,t),t):(A.isRestElement(e)&&pr(e.argument,t),t)}function Tn(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Xi(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 oN(e,t,n){e.set(t,{resolved:!0,value:n})}function ld(e,t){e.set(t,{resolved:!1})}function ty(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 Ct(e,t,n){if(A.isTSAsExpression(e)||A.isTSSatisfiesExpression(e)||A.isTSNonNullExpression(e)||A.isTypeCastExpression(e)||A.isParenthesizedExpression(e))return Ct(e.expression,t,n);if(A.isLogicalExpression(e))return Va([Ct(e.left,t,n),Ct(e.right,t,n)]);if(A.isBinaryExpression(e))return Va([A.isExpression(e.left)?Ct(e.left,t,n):null,A.isExpression(e.right)?Ct(e.right,t,n):null]);if(A.isConditionalExpression(e))return Va([Ct(e.consequent,t,n),Ct(e.alternate,t,n)]);if(A.isTemplateLiteral(e))return Va(e.expressions.filter(A.isExpression).map(i=>Ct(i,t,n)));if(A.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!A.isMemberExpression(e)&&!A.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;A.isMemberExpression(o)||A.isOptionalMemberExpression(o);){if(o.computed)if(A.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(A.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&A.isExpression(o.property)){let i=wr(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(!A.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return A.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:Tn(e,t),base:o.name,path:r}:null}function Va(e){let t=e.filter(r=>r!==null);if(t.length===0)return null;let n=t[0];return t.some(r=>r.base!==n.base||JSON.stringify(r.path)!==JSON.stringify(n.path))?null:{...n}}function ud(e,t,n){if(A.isArrayExpression(e)){let r=e.elements[0];return e.elements.length===1&&A.isExpression(r)?Ct(r,t,n):null}return A.isCallExpression(e)&&A.isMemberExpression(e.callee)&&!e.callee.computed&&A.isIdentifier(e.callee.property)&&["filter","slice","sort","toSorted","reverse","toReversed"].includes(e.callee.property.name)&&A.isExpression(e.callee.object)?ud(e.callee.object,t,n):Ct(e,t,n)}function wr(e,t){if(A.isStringLiteral(e)||A.isNumericLiteral(e)||A.isBooleanLiteral(e))return e.value;if(A.isNullLiteral(e))return null;if(A.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(A.isIdentifier(e)){let n=Xi(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(A.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||A.isSpreadElement(r))return;let o=wr(r,t);if(o===void 0)return;n.push(o)}return n}if(A.isObjectExpression(e)){let n={};for(let r of e.properties){if(!A.isObjectProperty(r)||r.computed||!A.isExpression(r.value))return;let o=null;if(A.isIdentifier(r.key)?o=r.key.name:A.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!A.isIdentifier(r.value))return;let s=Xi(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=wr(r.value,t);if(i===void 0)return;n[o]=i}return n}if(A.isMemberExpression(e)){let n=Ct(e,"",t);if(!n)return;let r=Xi(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=ty(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(A.isCallExpression(e))return ry(e,t)??void 0}function ny(e,t,n){let r=Ct(e,n,t);if(!r)return A.isMemberExpression(e)||A.isBinaryExpression(e)||A.isLogicalExpression(e)||A.isConditionalExpression(e)||A.isCallExpression(e)?{value:Tn(e,n),source:null}:null;let o=Xi(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?ty(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 od(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:nN(),parentStack:[],valueScopes:i,importMap:o}}function sd(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of pr(o.id))ld(n,s);if(!A.isIdentifier(o.id)||!o.init||!A.isExpression(o.init))continue;let i=wr(o.init,t);i!==void 0&&oN(n,o.id.name,i)}}function iN(e){let t=[];for(let n of e){if(A.isVariableDeclaration(n)){t.push(n);continue}A.isExportNamedDeclaration(n)&&n.declaration&&A.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function sN(e,t,n){let r=[],o=0;for(let i of e)if(A.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:$t(i),editable:!0,source:null})}else if(A.isJSXExpressionContainer(i)&&A.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:$t(i),editable:!0,source:null});else if(A.isJSXExpressionContainer(i)&&A.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:$t(i),editable:!0,source:null}):r.push({index:o++,value:Tn(s,n),sourceRange:$t(i),editable:!0,source:Ct(s,n,t)})}else if(A.isJSXExpressionContainer(i)&&A.isExpression(i.expression)){let s=ny(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:$t(i),editable:!0,source:s.source})}return r}function aN(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!A.isJSXAttribute(i))continue;let s=lN(i.name);if(!s)continue;let a=Tn(i,n);if(A.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:$t(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:$t(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(A.isJSXExpressionContainer(i.value)&&A.isExpression(i.value.expression)){let l=wr(i.value.expression,t);if(s==="className"){let g=typeof l=="string"?l:l===void 0?ry(i.value.expression,t):null;if(g){r.push({name:s,value:g,sourceRange:$t(i),source:null,resolvedValue:g,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:g}});continue}}let c=ny(i.value.expression,t,n);if(l!==void 0){r.push({name:s,value:hN(l),sourceRange:$t(i),source:Ct(i.value.expression,n,t),resolvedValue:l,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:l}});continue}let u=uN(i.value.expression,t),d=Ct(i.value.expression,n,t),f=c?.value??Tn(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":f,sourceRange:$t(i),source:c?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function cN(e,t,n){return e.attributes.flatMap((r,o)=>!A.isJSXSpreadAttribute(r)||!A.isExpression(r.argument)?[]:[{raw:Tn(r.argument,n),sourceRange:$t(r),order:o,source:Ct(r.argument,n,t)}])}function lN(e){return A.isJSXIdentifier(e)?e.name:A.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function uN(e,t){return Wn(e,{resolveIdentifier(n){let r=Xi(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=wr(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function ry(e,t){let n=Jo(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function Jo(e,t){if(A.isStringLiteral(e))return[e.value];if(A.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(A.isNullLiteral(e))return[];if(A.isBooleanLiteral(e))return e.value?null:[];if(A.isIdentifier(e)||A.isMemberExpression(e)){if(A.isIdentifier(e)&&e.name==="undefined")return[];let n=wr(e,t);return typeof n=="string"?[n]:null}if(A.isConditionalExpression(e)){let n=Jo(e.consequent,t),r=Jo(e.alternate,t);return!n||!r?null:[...n,...r]}if(A.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=wr(e.left,t);return n===!1||n===null?[]:Jo(e.right,t)}if(A.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||A.isSpreadElement(r))return null;let o=Jo(r,t);if(!o)return null;n.push(...o)}return n}if(A.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!A.isObjectProperty(r))return null;let o=fN(r.key);if(!o)return null;n.push(o)}return n}if(A.isCallExpression(e)){let n=dN(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!A.isExpression(o))return null;let i=Jo(o,t);if(!i)return null;r.push(...i)}return r}return null}function dN(e){return A.isIdentifier(e)?e.name:A.isMemberExpression(e)&&A.isIdentifier(e.property)?e.property.name:null}function fN(e){return A.isIdentifier(e)?e.name:A.isStringLiteral(e)?e.value:null}function pN(e,t){let n=e.attributes.find(r=>A.isJSXAttribute(r)&&A.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!A.isJSXAttribute(n)||!A.isJSXExpressionContainer(n.value)?null:n.value.expression}function mN(e,t){for(let n of t){let r=pN(e,n);if(r)return r}return null}function gN(e){return A.isJSXIdentifier(e.name)?e.name.name:null}function hN(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function yN(e){if(!A.isCallExpression(e)&&!A.isOptionalCallExpression(e))return null;let t=e.callee;return!A.isMemberExpression(t)&&!A.isOptionalMemberExpression(t)||!A.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!A.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function id(e){return A.isArrowFunctionExpression(e)||A.isFunctionExpression(e)}function xN(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function bN(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function qh(e,t,n,r){if(!e||!A.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:Tn(e,n),collectionSource:ud(e,n,r)};if(t){let i=t.params[0],s=t.params[1];A.isIdentifier(i)&&(o.itemParamName=i.name),A.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function mr(e,t,n){if(!e)return[];if(A.isJSXElement(e)){if(cd(e))return Ha(e.children,t,n);let r=Xa(e,t,n);return r?[r]:[]}return Xo(e)?za(e,t,n):A.isParenthesizedExpression(e)?mr(e.expression,t,n):A.isExpression(e)?Wa(e,t,n):[]}function Ka(e,t,n){let r=new Map;for(let o of e.params)for(let i of pr(o))ld(r,i);t.valueScopes.push(r);try{if(!A.isBlockStatement(e.body))return mr(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return oy(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function oy(e,t,n){let r=[];for(let o of e){if(A.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){sd([o],t,i);for(let s of o.declarations)A.isIdentifier(s.id)&&(A.isJSXElement(s.init)||A.isJSXFragment(s.init))&&r.push(...mr(s.init,t,n))}continue}r.push(...ad(o,t,n))}return r}function ad(e,t,n){if(A.isReturnStatement(e))return e.argument?mr(e.argument,t,n):[];if(A.isBlockStatement(e))return ho(e.body,t,n);if(A.isIfStatement(e)){let r=A.isBlockStatement(e.consequent)?ho(e.consequent.body,t,n):ad(e.consequent,t,n),o=e.alternate?A.isBlockStatement(e.alternate)?ho(e.alternate.body,t,n):ad(e.alternate,t,n):[];return[...r,...o]}if(A.isSwitchStatement(e))return ho(e.cases.flatMap(r=>r.consequent),t,n);if(A.isTryStatement(e)){let r=ho(e.block.body,t,n);return e.handler&&r.push(...ho(e.handler.body.body,t,n)),e.finalizer&&r.push(...ho(e.finalizer.body,t,n)),r}return[]}function ho(e,t,n){let r=new Map;t.valueScopes.push(r);try{return oy(e,t,n)}finally{t.valueScopes.pop()}}function Ja(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:$t(r),sourceCandidates:i&&i.length>0?i:void 0})}function EN(e,t,n,r){let o=mN(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Qh(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!A.isJSXAttribute(s))continue;let a=gN(s);if(!a||!A.isJSXExpressionContainer(s.value))continue;let l=s.value.expression;if(!A.isJSXEmptyExpression(l)){if(xN(a)&&id(l)){let c=Ka(l,n,r),u=qh(o,l,r,n);Ja(n,"repeat-region",t,s,c,u?[u]:void 0);continue}if(bN(a)){let c=id(l)?Ka(l,n,r):mr(l,n,r);Ja(n,"conditional-region",t,s,c)}}}if(o)for(let s of e.children){if(!A.isJSXExpressionContainer(s)||!id(s.expression))continue;let a=Ka(s.expression,n,r),l=qh(o,s.expression,r,n);Ja(n,"repeat-region",t,s,a,l?[l]:void 0)}}finally{n.parentStack.pop()}}function Xa(e,t,n){let r=Qh(e.openingElement);if(r==="Fragment"||cd(e))return Ha(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=QC(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 l=o?t.elements.get(o.key)?.identity.structuralPath:void 0,c=l?`${l}/${a}`:a,u=$i(t.file,t.componentName,c),d={file:t.file,component:t.componentName,structuralPath:c,key:u},f=s?"component-boundary":null,g=sN(e.children,t,n),m=aN(e.openingElement,t,n),p=cN(e.openingElement,t,n),h,x,E=!1;if(s){let S=t.importMap.get(r)??t.importMap.get(eN(r));S&&(h=S.specifier,x=S.exportName,E=ao(S.specifier,t.file))}let b={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:$t(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:h,exportName:x};return t.elements.set(u,b),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),EN(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),SN(e.children,t,n),t.parentStack.pop()),u}function za(e,t,n){return Ha(e.children,t,n)}function Ha(e,t,n){let r=[];for(let o of e)if(A.isJSXElement(o))if(cd(o))r.push(...Ha(o.children,t,n));else{let i=Xa(o,t,n);i&&r.push(i)}else Xo(o)?r.push(...za(o,t,n)):A.isJSXExpressionContainer(o)&&r.push(...Wa(o.expression,t,n));return r}function SN(e,t,n){for(let r of e)A.isJSXElement(r)?Xa(r,t,n):Xo(r)?za(r,t,n):A.isJSXExpressionContainer(r)&&Wa(r.expression,t,n)}function vN(e){return e==="&&"||e==="||"||e==="??"}function Wa(e,t,n){if(A.isJSXEmptyExpression(e))return[];let r=yN(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,l={kind:"repeat-template",collectionExpression:Tn(r.collection,n),collectionSource:ud(r.collection,n,t)};if(A.isArrowFunctionExpression(a)||A.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];A.isIdentifier(u)&&(l.itemParamName=u.name),A.isIdentifier(d)&&(l.indexParamName=d.name)}s.push(l);let c={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:$t(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(c),(A.isArrowFunctionExpression(a)||A.isFunctionExpression(a))&&c.childKeys.push(...Ka(a,t,n)),c.childKeys}if(A.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Tn(e.test,n),conditionSource:Ct(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:$t(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...mr(e.consequent,t,n)),s.childKeys.push(...mr(e.alternate,t,n)),s.childKeys}if(A.isLogicalExpression(e)&&vN(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Tn(e.left,n),conditionSource:Ct(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:$t(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...mr(e.right,t,n)),s.childKeys}if(A.isParenthesizedExpression(e))return Wa(e.expression,t,n);if(A.isJSXElement(e)){let o=Xa(e,t,n);return o?[o]:[]}return Xo(e)?za(e,t,n):[]}function IN(e){let t=e.argument;return t&&(A.isExpression(t)||Xo(t))?t:null}function zi(e,t){let n=[];for(let r of e){if(A.isReturnStatement(r)){let o=IN(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(A.isIfStatement(r)){let o=A.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...zi(o,r.test)),r.alternate){let i=A.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...zi(i,r.test))}continue}if(A.isSwitchStatement(r))for(let o of r.cases){let i=o.test?A.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...zi(o.consequent,i))}}return n}function Ga(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function iy(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier);if(!A.traverseFast(r,f=>{if(A.isJSXElement(f)||A.isJSXFragment(f))return A.traverseFast.stop}))return{graph:Ga(t),localImports:o};let s=new Map,a=[],l=[],c=new Map,u=rN(r);qC(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let g=tN(f);if(!g)return;let m=f.node,p=[];if(A.isArrowFunctionExpression(m))A.isExpression(m.body)||Xo(m.body)?p=[{argument:m.body,statement:A.returnStatement(A.isExpression(m.body)?m.body:null)}]:A.isBlockStatement(m.body)&&(p=zi(m.body.body));else{let v=m.body;A.isBlockStatement(v)&&(p=zi(v.body))}if(p.length===0){f.skip();return}let h=new Map;sd(iN(r.program.body),od(t,g,s,a,u,[h]),h);let x=new Map;for(let v of m.params)for(let P of pr(v))ld(x,P);let E=A.isBlockStatement(m.body)?m.body.body:[],b=p[0]?.statement??null;for(let v of E){if(b&&v===b)break;A.isVariableDeclaration(v)&&sd([v],od(t,g,s,a,u,[h,x]),x)}let S=od(t,g,s,a,u,[h,x]);for(let v of p){let P=mr(v.argument,S,n);for(let I of P)l.includes(I)||l.push(I);if(v.condition){let I={kind:"conditional-branch",conditionExpression:Tn(v.condition,n),conditionSource:Ct(v.condition,n,S)};Ja(S,"conditional-region","",v.statement,P,[I])}}f.skip()}});let d=[...s.keys()];return d.length>0&&c.set(t,d),{graph:{routeId:t,rootKeys:l,elements:s,regions:a,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function dd(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Ya(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function sy(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 zo(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Ee,l=new Map,c=new Map,u=new Map,d=[],f=new Set,g=x=>{let E=`${x.path}\0${x.code}\0${x.message}\0${JSON.stringify(x.details??{})}`;f.has(E)||(f.add(E),d.push(x))},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:[]}))],p=new Set;for(;m.length>0;){let x=m.shift(),{file:E,source:b,depth:S,diagnosticEntryFile:v,importStack:P}=x;if(p.has(E))continue;p.add(E),l.set(E,b);let I=o.validationOnly&&S<i?o.validatedImports?.(E,b):void 0,C,N;if(I)C=Ga(E),N=I;else{let M=a(E,b);if(!M.ok){g(Ya(M.diagnostic,v,P));continue}u.set(E,M.module);let G=o.validationOnly&&S<i?{graph:Ga(E),localImports:M.module.imports.map(K=>K.specifier)}:iy(M.module);C=G.graph,N=G.localImports}let w=[...new Set([...C.elements.values()].map(M=>M.importedFrom).filter(M=>typeof M=="string"&&mt(M)))],L=w.length?await sy(w,M=>ua(E,M,r)):[],D=new Map(w.map((M,G)=>[M,L[G]]));for(let M of C.elements.values())if(M.importedFrom&&mt(M.importedFrom)){let G=M.importedFrom,K=D.get(G);K.ok?(M.importedFrom=K.path,lr(K.path)&&(M.isPublicUiComponent=!0)):ao(G,E)||g(Ya(K.diagnostic,v,dd(P,E,G,K.diagnostic.path)))}if(c.set(E,C),S>=i)continue;let U=await sy(N,async M=>{if($g(M))return null;let G=D.get(M)??await ua(E,M,r);if(!G.ok)return ao(M,E)?null:{diagnostic:Ya(G.diagnostic,v,dd(P,E,M,G.diagnostic.path))};let K=G.path;if(p.has(K)||lr(K))return null;let ge=dd(P,E,M,K);try{let oe=await n(K);return{entry:{file:K,source:oe,depth:S+1,diagnosticEntryFile:v,importStack:ge}}}catch(oe){return{diagnostic:Ya({path:K,code:"import-read-failed",message:`Failed to read imported file: ${K}`,details:{fromFile:E,specifier:M,reason:oe instanceof Error?oe.message:String(oe)}},v,ge)}}});for(let M of U)M&&"entry"in M?m.push(M.entry):M&&g(M.diagnostic)}let h=kN(e,c,s,(o.additionalEntries??[]).map(x=>x.file));return h.diagnostics=d,{graph:h,allSources:l,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[l,c]of t){for(let[u,d]of c.elements)o.set(u,d);for(let u of c.regions)i.push(u);for(let[u,d]of c.fileIndex){let f=s.get(u)??[];s.set(u,[...f,...d])}if(l===e){a=c.rootKeys;continue}r.includes(l)&&(a=[...a,...c.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}function ay(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 QN}from"@vcp-dev/contracts";import{createHash as _N,randomUUID as Sd}from"node:crypto";import dt from"node:fs/promises";import gt from"node:path";var yy=new WeakMap;function Ho(e){return yy.get(e)?.()??e.readIndex()}var In=1,pd=1,RN=2,PN="index.json",CN="recovery.json",NN="transaction-journal.json",AN="document-version.json",Qa={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},ve={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"},ke=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function gr(){return{entries:new Map,blobSizes:new Map}}function Za(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)xy(n,r,t);return n}function xy(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 l=e.blobs.get(s);e.blobs.set(s,{sizeBytes:a,references:(l?.references??0)+1}),l||(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 Ey(e,t={}){let n=HN(e),r=ZN(t.limits),o=fd(n),i=WN(n),s=await Yt(i),a=await Yt(o)||s;a||(await jN(n),await $N(n)),a||await qN(n);let l=gr(),c=await tc(n,l),u=new Set(a?(await sc(n)).map(E=>E.stageId):[]);a||await fy(n,c.entryIds,l);let d=c.digest,f=Za(c.entryIds,l),g=async E=>{let{index:b,sizeBytes:S}=await Zi(n);if(Py(b,E),b.digest!==d){let v=gr();await ky(n,b.entryIds,v,S),f=Za(b.entryIds,v),d=b.digest}return{...ac(b),totalBytes:f.objectBytes+S}},m=async E=>{vd(E),await g(),await uy(n,f,[E.entryId],E.blobIds,E.stageId),await ec(n,E.stageId)},p=async(E,b)=>{let S=await g(b);vy(E,S.entryIds.length);let v=gr();for(let P of S.entryIds.slice(Math.min(S.cursor,E)+1,Math.max(S.cursor,E)+1))await Wi(n,P,v);return S},h=async()=>{if(await Yt(o)||s)throw new ke(ve.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},x={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return gy(n)},async writeDocumentVersion(E){if(await h(),!Number.isInteger(E)||E<0)throw new ke(ve.INVALID_SCHEMA,"document version must be a non-negative integer");let b=await gy(n);E<=b||await Hi(Ty(n),{schemaVersion:1,version:Math.max(b,E)})},async stageAppend(E,b={}){await h();let S=await ON(E,r),v={schemaVersion:pd,stageId:Sd(),entryId:S.entryId,blobIds:S.blobs.map(P=>P.digest)};try{await FN(n,S),await DN(n,v,b.durableManifest!==!1)}catch(P){try{await m(v)}catch(I){throw new ke(ve.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:I})}throw P}return{stageId:v.stageId,entryId:v.entryId,blobIds:v.blobIds}},async discardStage(E){await h(),hd(E);let b=await md(n,E);b&&await m(b)},async previewStagedAppend(E,b){await h();let S=await g(b);return(await cy(n,r,E,S,f)).transition},async previewCursor(E,b){await h();let S=await p(E,b);return Sy(S,S.entryIds,E)},async publishStagedAppend(E,b,S){if(await h(),rc(E,"entryId"),S){hd(S);let N=await md(n,S);if(!N||N.entryId!==E)throw new ke(ve.INVALID_SCHEMA,"history stage does not match the published entry")}let v=await g(b),P=f,I=await cy(n,r,E,v,P),C=await my({rootDir:n,previousDigest:I.current.digest,entryIds:I.entryIds,cursor:I.cursor,readback:async()=>py(n,I.usage),afterWrite:async()=>{S?await ec(n,S):await BN(n,E),await uy(n,I.usage,[...P.entries.keys()].filter(N=>!I.usage.entries.has(N)),[...P.blobs.keys()].filter(N=>!I.usage.blobs.has(N)))}});return f=I.usage,d=C.digest,C},async append(E){await h();let b=await g(),S=await x.stageAppend(E);try{return await x.publishStagedAppend(S.entryId,b.digest,S.stageId)}catch(v){throw await x.discardStage(S.stageId),v}},async readEntry(E){return rc(E,"entryId"),Wi(n,E)},async readBlob(E){rc(E,"blobId");let b=await Oy(n,E),S=await Gi(b,ve.NOT_FOUND,"blob");return Ay(S,E,b),S},async readIndex(){let E=gr(),b=await tc(n,E);return f=Za(b.entryIds,E),d=b.digest,b},async readStatus(){let E=await nc(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 Yt(o)||await Yt(i)}},async readUndoRedoIds(){let E=await nc(n);return{undoIds:E.undoIds,redoIds:E.redoIds,currentId:E.currentId}},async setCursor(E,b){await h();let S=await p(E,b),v=await my({rootDir:n,previousDigest:S.digest,entryIds:S.entryIds,cursor:E,readback:async()=>py(n,f)});return d=v.digest,v},async markRecoveryRequired(E){await Yt(o)||await Hi(fd(n),{schemaVersion:In,reason:GN(E),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await dt.rm(fd(n),{force:!0})},async readTransactionJournal(){return await Yt(i)?qa(i):null},async writeTransactionJournal(E){await h(),wy(E);try{await Hi(i,E)}catch(S){let v=await qa(i).catch(()=>null);if(v&&Buffer.from(Zt(v)).equals(Buffer.from(Zt(E))))return;throw v?new ke(ve.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:S}):S}let b=await qa(i);if(!Buffer.from(Zt(b)).equals(Buffer.from(Zt(E))))throw new ke(ve.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(E){let b=await Yt(i)?await qa(i):null;if(b&&b.transactionId!==E)throw new ke(ve.INVALID_SCHEMA,"transaction journal changed concurrently");try{await dt.rm(i,{force:!0})}catch(S){if(!await Yt(i))return;throw S}if(await Yt(i))throw new ke(ve.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await h();for(let S of u)await ec(n,S),u.delete(S);await UN(n);let E=gr(),b=await tc(n,E);await fy(n,b.entryIds,E),f=Za(b.entryIds,E),d=b.digest}};return yy.set(x,()=>nc(n)),x}async function cy(e,t,n,r,o){rc(n,"entryId");let i=gr(),s=await Wi(e,n,i),a={entries:new Map(o.entries),blobs:new Map(o.blobs),objectBytes:o.objectBytes},l=r.entryIds.slice(0,r.cursor+1);for(let u of r.entryIds.slice(r.cursor+1))by(a,u);xy(a,s.id,i),l.push(s.id);let c=LN(l,t,a);return{current:r,entryIds:c.entryIds,cursor:c.cursor,usage:a,transition:Sy(r,c.entryIds,c.cursor)}}function Sy(e,t,n){return vy(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:TN(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function TN(e,t){return Or(Zt({schemaVersion:In,entryIds:e,cursor:t}))}function vy(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new ke(ve.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function wN(e){if(!wn(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!an(e.expectedIndexDigest)||!an(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!an(n)?!1:t===-1?n===null:an(n)}async function ON(e,t){if(!e.kind.trim())throw new ke(ve.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let l of e.blobs??[]){if(!l.name.trim())throw new ke(ve.INVALID_JSON,"history blob name must not be empty");let c=zN(l.data),u=Or(c);n.push({name:l.name,bytes:c,digest:u,sizeBytes:c.byteLength}),r.push({name:l.name,digest:u,sizeBytes:c.byteLength})}let o={schemaVersion:In,kind:e.kind,manifest:e.manifest,blobs:r},i=Zt({...o}),s=Or(i),a=i.byteLength+n.reduce((l,c)=>l+c.sizeBytes,0);if(a>t.maxEntryBytes)throw new ke(ve.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function FN(e,t){let n=Rd(e,t.entryId),r={id:t.entryId,...t.entryBody},o=new Map(t.blobs.map(l=>[l.digest,l])),i=[...Array.from(o.values(),l=>ly(Pd(e,l.digest),l.bytes,{kind:"blob",digest:l.digest},Nd(e,l.digest))),ly(n,Zt(r),{kind:"entry",digest:t.entryId},Cd(e,t.entryId))],a=(await Promise.allSettled(i)).find(l=>l.status==="rejected");if(a)throw a.reason}async function ly(e,t,n,r){let o=await bd(e)??(r?await bd(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new ke(n.kind==="blob"?ve.BLOB_CORRUPT:ve.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Cy(e,t)}function LN(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+Zt(Ry(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new ke(ve.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");by(n,r.shift()),o-=1}}async function DN(e,t,n){vd(t);let r=_d(e,t.stageId);if(n){await Hi(r,t);return}await XN(r,t)}async function md(e,t){let n=await bd(_d(e,t));if(n===null)return null;let r=qi(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=vd(r);if(o.stageId!==t)throw new ke(ve.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function sc(e){let t=[];for(let n of await ic(kd(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);hd(r);let o=await md(e,r);o&&t.push(o)}return t}async function uy(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 sc(e))if(a.stageId!==o){i.add(a.entryId);for(let l of a.blobIds)s.add(l)}for(let a of new Set(n))i.has(a)||await dy(Rd(e,a),Cd(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await dy(Pd(e,a),Nd(e,a));await Ed(Qi(e)),await Ed(es(e))}async function ec(e,t){await gd(_d(e,t)),await MN(e)}async function MN(e){try{await dt.rmdir(kd(e))}catch(t){if(ts(t)||wn(t)&&t.code==="ENOTEMPTY")return;throw t}}async function BN(e,t){for(let n of await sc(e))n.entryId===t&&await ec(e,n.stageId)}async function gd(e){if(await dt.rm(e,{force:!0}),await Yt(e))throw new ke(ve.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function dy(e,t){await gd(e),await gd(t)}function vd(e){if(!wn(e)||e.schemaVersion!==pd||typeof e.stageId!="string"||!Iy(e.stageId)||!an(e.entryId))throw new ke(ve.INVALID_SCHEMA,"history stage schema is invalid");let t=Ny(e.blobIds,"history stage blobIds");return{schemaVersion:pd,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function hd(e){if(!Iy(e))throw new ke(ve.INVALID_PATH,"history stageId must be a UUID")}function Iy(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 fy(e,t,n=gr()){let r=new Set(t),o=new Set;for(let c of t){let u=await Wi(e,c,n);for(let d of u.blobs)o.add(d.digest)}for(let c of await sc(e)){r.add(c.entryId);for(let u of c.blobIds)o.add(u)}let i=Qi(e),s=await ic(i);for(let c of s){if(!c.endsWith(".json"))continue;let u=hy(c.slice(0,-5));u&&!r.has(u)&&await oc(gt.join(i,c))}let a=es(e),l=await ic(a);for(let c of l){let u=hy(c);u&&!o.has(u)&&await oc(gt.join(a,c))}}async function tc(e,t=gr()){let{index:n,sizeBytes:r}=await Zi(e),{totalBytes:o}=await ky(e,n.entryIds,t,r);return{...ac(n),totalBytes:o}}async function py(e,t){let{index:n,sizeBytes:r}=await Zi(e);return{...ac(n),totalBytes:t.objectBytes+r}}async function Zi(e){let t=Id(e),n=await Gi(t,ve.NOT_FOUND,"index"),r=qi(Buffer.from(n).toString("utf8"),"index");return{index:VN(r),sizeBytes:n.byteLength}}async function nc(e){return ac((await Zi(e)).index)}function ac(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:In,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function ky(e,t,n,r){let o=0,i=new Set;o+=r??(await Zi(e)).sizeBytes;for(let s of new Set(t)){let a=await Wi(e,s,n);o+=n.entries.get(s).sizeBytes;for(let l of a.blobs)i.has(l.digest)||(i.add(l.digest),o+=n.blobSizes.get(l.digest))}return{totalBytes:o}}async function Wi(e,t,n=gr()){let r=n.entries.get(t);if(r)return r.entry;let o=await YN(e,t),i=await Gi(o,ve.NOT_FOUND,"entry"),s=qi(Buffer.from(i).toString("utf8"),`entry ${t}`),a=KN(s);if(a.id!==t)throw new ke(ve.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(Or(Zt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new ke(ve.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);let c=[...new Set(a.blobs.map(d=>d.digest))].filter(d=>!n.blobSizes.has(d)),u=async d=>{let f=await Oy(e,d),g=await Gi(f,ve.NOT_FOUND,"blob");return Ay(g,d,f),g.byteLength};if(c.length===1)n.blobSizes.set(c[0],await u(c[0]));else if(c.length>1){let d=new Array(c.length),f=[],g=0,m=Array.from({length:Math.min(4,c.length)},async()=>{for(;g<c.length&&f.length===0;){let x=g++;try{d[x]=await u(c[x])}catch(E){f.push({index:x,error:E})}}}),p=await Promise.allSettled(m),h=f.sort((x,E)=>x.index-E.index)[0];if(h)throw h.error;for(let x of p)if(x.status==="rejected")throw x.reason;for(let x=0;x<c.length;x++)n.blobSizes.set(c[x],d[x])}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function _y(e,t,n){await Hi(Id(e),Ry(t,n))}function Ry(e,t){return{schemaVersion:In,digest:Or(Zt({schemaVersion:In,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Py(e,t){if(t!==void 0&&e.digest!==t)throw new ke(ve.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function my(e){Py(await nc(e.rootDir),e.previousDigest);let t=Or(Zt({schemaVersion:In,entryIds:e.entryIds,cursor:e.cursor}));try{await _y(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new ke(ve.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await tc(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new ke(ve.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function jN(e){await dt.mkdir(e,{recursive:!0}),await dt.mkdir(Qi(e),{recursive:!0}),await dt.mkdir(es(e),{recursive:!0}),await dt.mkdir(Yi(e),{recursive:!0})}async function $N(e){await dt.rm(Yi(e),{recursive:!0,force:!0}),await dt.mkdir(Yi(e),{recursive:!0})}async function UN(e){let t=Yi(e);await dt.mkdir(t,{recursive:!0});for(let n of await ic(t))n!=="stages"&&await dt.rm(gt.join(t,n),{recursive:!0,force:!0})}function VN(e){if(!wn(e))throw new ke(ve.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==In)throw new ke(ve.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Ny(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new ke(ve.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!an(o))throw new ke(ve.INDEX_CORRUPT,"index digest is invalid");let i=Or(Zt({schemaVersion:In,entryIds:t,cursor:r}));if(o!==i)throw new ke(ve.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:In,digest:o,entryIds:t,cursor:r}}function KN(e){if(!wn(e))throw new ke(ve.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==In)throw new ke(ve.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!an(t))throw new ke(ve.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new ke(ve.ENTRY_CORRUPT,"entry kind is invalid");let r=xd(e.manifest,"entry.manifest"),o=JN(e.blobs);return{id:t,schemaVersion:In,kind:n,manifest:r,blobs:o}}function JN(e){if(!Array.isArray(e))throw new ke(ve.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!wn(t))throw new ke(ve.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new ke(ve.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!an(o))throw new ke(ve.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new ke(ve.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Hi(e,t){await Cy(e,Zt(t))}async function XN(e,t){let n=gt.dirname(e),r=gt.basename(e),o=gt.join(n,`.${r}.${process.pid}.${Sd()}.tmp`);await dt.mkdir(n,{recursive:!0});try{await dt.writeFile(o,Zt(t),{flag:"wx"}),await dt.rename(o,e)}finally{await oc(o)}}async function Cy(e,t){let n=gt.dirname(e),r=gt.basename(e),o=gt.join(n,`.${r}.${process.pid}.${Sd()}.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 Ed(n)}finally{await oc(o)}}function Zt(e){return Buffer.from(JSON.stringify(yd(e)),"utf8")}function yd(e){if(Array.isArray(e))return e.map(t=>yd(t));if(wn(e)){let t={};for(let n of Object.keys(e).sort())t[n]=yd(e[n]);return t}return e}function qi(e,t){try{return JSON.parse(e)}catch(n){throw new ke(ve.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function xd(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=>xd(n,t));if(wn(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=xd(o,t);return n}break}throw new ke(ve.INVALID_JSON,`${t} must be JSON-serializable`)}function Ny(e,t){if(!Array.isArray(e))throw new ke(ve.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!an(n))throw new ke(ve.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function rc(e,t){if(!an(e))throw new ke(ve.INVALID_PATH,`${t} must be a sha256 digest`)}function an(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function Or(e){return`sha256:${_N("sha256").update(e).digest("hex")}`}function zN(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Gi(e,t,n){try{return await dt.readFile(e)}catch(r){throw new ke(t,`${n} not found: ${e}`,{cause:r})}}async function bd(e){try{return await dt.readFile(e)}catch(t){if(ts(t))return null;throw t}}function Ay(e,t,n){if(Or(e)!==t)throw new ke(ve.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Yt(e){try{return await dt.access(e),!0}catch(t){if(ts(t))return!1;throw t}}async function oc(e){try{await dt.rm(e,{force:!0,recursive:!0})}catch{}}async function Ed(e){try{let t=await dt.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function ic(e){try{return await dt.readdir(e)}catch(t){if(ts(t))return[];throw t}}function HN(e){if(typeof e!="string"||e.trim().length===0)throw new ke(ve.INVALID_ROOT,"history store rootDir must be a non-empty string");return gt.resolve(e)}function Id(e){return gt.join(e,PN)}function fd(e){return gt.join(e,CN)}function WN(e){return gt.join(e,NN)}function Ty(e){return gt.join(e,AN)}async function gy(e){try{let t=await dt.readFile(Ty(e),"utf8"),n=qi(t,"document version");if(!wn(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new ke(ve.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(ts(t))return 0;throw t}}async function qa(e){let t=await Gi(e,ve.RECOVERY_PENDING,"transaction journal"),n=qi(Buffer.from(t).toString("utf8"),"transaction journal");return wy(n),n}function wy(e){if(!wn(e)||e.schemaVersion!==RN||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!wN(e.historyTransition)||!Array.isArray(e.files))throw new ke(ve.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!wn(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!an(t.preDigest)||t.postDigest!==null&&!an(t.postDigest))throw new ke(ve.INVALID_SCHEMA,"transaction journal file digest is invalid")}function GN(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Qi(e){return gt.join(e,"entries")}function es(e){return gt.join(e,"blobs")}function Yi(e){return gt.join(e,"tmp")}function kd(e){return gt.join(Yi(e),"stages")}function _d(e,t){return gt.join(kd(e),`${t}.json`)}function Rd(e,t){return gt.join(Qi(e),`${Ly(t)}.json`)}function Pd(e,t){return gt.join(es(e),Ly(t))}function Cd(e,t){return gt.join(Qi(e),`${t}.json`)}function Nd(e,t){return gt.join(es(e),t)}async function YN(e,t){return Fy(Rd(e,t),Cd(e,t))}async function Oy(e,t){return Fy(Pd(e,t),Nd(e,t))}async function Fy(e,t){return await Yt(e)?e:await Yt(t)?t:e}function Ly(e){return e.slice(7)}function hy(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return an(t)?t:null}function wn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ts(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function ZN(e){return{maxEntries:e?.maxEntries??Qa.maxEntries,maxSessionBytes:e?.maxSessionBytes??Qa.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Qa.maxEntryBytes}}async function qN(e){let t=Id(e);await Yt(t)||await _y(e,[],-1)}var eA={affectedCompositions:[]};function $y(e){let t=null,n=new WeakMap;async function r(){return t??=tA(e),t}async function o(i){if(!i)return null;let s=Ad(i);return s?nA(e,s):i}return{async prepareAppend(i){let s=await Ho(e),a=await e.stageAppend(By(i),{durableManifest:!1}),l;try{l=await e.previewStagedAppend(a.entryId,s.digest)}catch(u){throw await e.discardStage(a.stageId),u}let c={kind:"append",entry:i,historyTransition:l};return n.set(c,{expectedDigest:s.digest,stageId:a.stageId,entryId:a.entryId}),c},async prepareUndo(){let i=await r(),s=await o(i.undo.at(-1));if(!s?.historyId)return null;let a=await Ho(e),l=a.entryIds.indexOf(s.historyId);if(l<0)throw new Error("undo entry is missing from index");if(l!==a.cursor)throw new Error("undo state changed before prepare");let c=l-1,u=await e.previewCursor(c,a.digest),d={kind:"undo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:c}),d},async prepareRedo(){let i=await r(),s=await o(i.redo.at(-1));if(!s?.historyId)return null;let a=await Ho(e),l=a.entryIds.indexOf(s.historyId);if(l<0)throw new Error("redo entry is missing from index");if(l!==a.cursor+1)throw new Error("redo state changed before prepare");let c=l,u=await e.previewCursor(c,a.digest),d={kind:"redo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:c}),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 l=await e.publishStagedAppend(s.entryId,s.expectedDigest,s.stageId);Dy(l,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,Wo(l))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let l=i.kind==="undo"?a.undo:a.redo;if(Ad(l.at(-1))!==Ad(i.entry))throw new Error("history state changed before publish");let c=await e.setCursor(s.cursor,s.expectedDigest);Dy(c,i.historyTransition),Object.assign(a,Wo(c))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let l=await Ho(e);if(l.digest===a.publishedIndexDigest&&l.cursor===a.publishedCursor&&l.currentId===a.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}s.stageId&&await e.discardStage(s.stageId),n.delete(i)},async peekUndo(){return o((await r()).undo.at(-1))},async pushUndo(i){let s=await r(),a=i;if(a.historyId){let u=s.entryIds.indexOf(a.historyId);if(u>=0)try{let d=await e.setCursor(u);Object.assign(s,Wo(d));return}catch(d){throw s.redo.push(i),d}}let l=await e.append(By(i)),c=l.currentId;if(!c)throw new Error("history store did not publish an entry");i.historyId=c,Object.assign(s,Wo(l))},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 l=s.entryIds.indexOf(a.historyId);if(l<0)throw s.undo.push(i),new Error("history entry is missing from the durable index");try{let c=await e.setCursor(l-1);Object.assign(s,Wo(c))}catch(c){throw s.undo.push(i),c}},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 Dy(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 Ad(e){return typeof e=="string"?e:e?.historyId}async function tA(e){let t=await Ho(e);return Wo(t)}function Wo(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function nA(e,t){let n=await e.readEntry(t),r=rA(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 My(e,n,r.preSnapshots),postSnapshots:await My(e,n,r.postSnapshots)}}async function My(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(sA(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function By(e){let t=[],n=(i,s)=>i.map((a,l)=>{let c={file:a.file,exists:a.exists!==!1,version:a.version,...a.sha256?{sha256:a.sha256}:{}};if(c.exists){let u=`${s}-${l}`;c.blobName=u,t.push({name:u,data:a.content})}return c}),r=oA(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 rA(e){if(!Vy(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:Uy(t.provenance)}:{},preSnapshots:jy(t.preSnapshots,"preSnapshots"),postSnapshots:jy(t.postSnapshots,"postSnapshots")}}function oA(e){if(e.provenance!==void 0)return Uy(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function Uy(e){let t=QN.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 jy(e,t){return e.map((n,r)=>{if(!Vy(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&&!iA(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 iA(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function sA(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Vy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{GeneratedSiteCapabilitiesSchema as aA}from"@vcp-dev/contracts";var Ky={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 Td(){let e=aA.safeParse(Ky);return e.success?e.data:null}import{randomBytes as cA}from"node:crypto";import cc from"node:path";import{parse as Yy}from"@babel/parser";import lA from"@babel/traverse";import*as Zy from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Od,PageResourceArtifactSchema as uA,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as dA,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as fA,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as pA,parseComponentI18nResourcesJson as mA}from"@vcp-dev/contracts";var Fd="{{$INSTANCE}}",gA=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,hA=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Ld="components/site/generated",yA=/\.(?:tsx?|json)$/,xA=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,bA=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],EA=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),wd=lA,SA=typeof wd=="function"?wd:wd.default;async function Dd(e){let t=uA.safeParse(e.artifact);if(!t.success)return ft("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>cA(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=AA(r());if(!i)return ft("Random instance suffix must be 8 lowercase hex chars.");let s=`${TA(n.resource_id)}-${i}`,a=new Map,l=new Map,c=[];for(let b of n.pages){let S=b.final_route.slice(1);a.set(b.template_page_id,b.final_route),l.set(b.template_page_id,b.title),c.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,f=new Set,g=new Map,m=new Map,p=[],h=new Set(n.pages.flatMap(b=>b.components.map(S=>S.component_id)));for(let b of n.components){if(!h.has(b.component_id))continue;let S=Jy({materialization:b.materialization,packageInstanceId:s,routeByPage:a,titleByPage:l});if(!S.ok)return S;for(let v of S.files){let P=zy(v,d,u);if(P)return P}f.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 v=c[b],P=Jy({materialization:S.materialization,packageInstanceId:s,routeByPage:a,titleByPage:l,pageEntryTarget:v.route_file_path,pageTitle:v.title});if(!P.ok)return P;for(let I of P.files){let C=zy(I,d,u);if(C)return C}f.add(P.entry),m.set(P.entry,P.entryExport),p.push({entry:P.entry,declaredComponentIds:new Set(S.components.map(I=>I.component_id))})}let x=IA(u,f,s,g,p,m);if(!x.ok)return x;for(let b of u)if(await e.exists(b.file))return!b.file.startsWith("app/")&&o>1?Dd({...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:c,files:u})}function Jy(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:Xy(o.pathTemplate,e.packageInstanceId);if(!s)return ft("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 l=i&&e.pageTitle!==void 0?RA(a.data,e.pageTitle,s):a;if(!l.ok)return l;n.push({operation:"create-only",file:s,content:l.data})}let r=e.pageEntryTarget??Xy(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 vA(e,t,n,r){let o,i=e.replace(gA,(l,c)=>{let u=n.get(c);return u||(o=c,l)});if(o)return ft(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(hA,(l,c)=>{let u=r.get(c);return u?JSON.stringify(u):(o=c,l)});if(o)return ft(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(Fd,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?ft("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function Xy(e,t){let n=`${Ld}/${t}`;if(e.split(Fd).length>2)return null;let o=e.replace(Fd,t),i=`${Ld}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=cc.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!yA.test(a)||xA.test(a)?null:a}function zy(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 IA(e,t,n,r,o,i){let s=new Set(e.map(g=>g.file)),a=`${Ld}/${n}`,l=new Map(e.map(g=>[g.file,new Set])),c=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(Od)&&!mA(g.content).success)return ft("Materialization component i18n resources are invalid.",g.file);continue}try{let m=Yy(g.content,{sourceType:"module",plugins:["jsx","typescript"]});c.set(g.file,m);for(let h of m.program.body)if((h.type==="ImportDeclaration"||h.type==="ExportAllDeclaration"||h.type==="ExportNamedDeclaration"&&h.source)&&h.source){let x=h.source.value,E=CA(g.file,x,s,a);if(!E.allowed)return ft(`Materialization import is outside the controlled package: ${x}`,g.file);E.internalPath&&l.get(g.file).add(E.internalPath)}let p;if(SA(m,{Identifier(h){h.isReferencedIdentifier()&&EA.has(h.node.name)&&(p??=h.node.name,h.stop())},JSXOpeningElement(h){h.node.name.type==="JSXIdentifier"&&h.node.name.name.toLowerCase()==="style"&&(p??="style element",h.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=c.get(g);if(!p||!_A(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=Gy(g.entry,l);for(let p of g.declaredComponentIds){let h=r.get(p);if(!h||!m.has(h))return ft(`Page entry does not reach declared component: ${p}`,g.entry)}for(let p of m){let h=u.get(p);if(h&&!g.declaredComponentIds.has(h))return ft(`Page entry imports undeclared component: ${h}`,g.entry)}}let d=new Set;for(let g of t)for(let m of Gy(g,l))d.add(m);if(d.size!==e.length)return ft("Every materialization file must be reachable from a package entry.");let f=NA(e,c,l);return f||{ok:!0}}function kA(e){if(e.length>dA)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>fA)return ft("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>pA?ft("Page resource exceeds the aggregate content byte limit."):null}function _A(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 RA(e,t,n){let r;try{r=Yy(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=Hy(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let l=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&PA(u.key));if(!l||l.type!=="ObjectProperty")return{ok:!0,data:e};let c=Hy(l.value);return c?c.type!=="StringLiteral"&&c.type!=="TemplateLiteral"||c.type==="TemplateLiteral"&&c.expressions.length>0||typeof c.start!="number"||typeof c.end!="number"?{ok:!0,data:e}:{ok:!0,data:e.slice(0,c.start)+JSON.stringify(t)+e.slice(c.end)}:{ok:!0,data:e}}}return{ok:!0,data:e}}function Hy(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&Zy.isExpression(t)?t:null}function PA(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function CA(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=Wy(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:bA.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=cc.posix.normalize(cc.posix.join(cc.posix.dirname(e),t)),i=Wy(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function Wy(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 NA(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Od))continue;let i=o.file.slice(0,-Od.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 l=t.get(s)?.program.directives.some(u=>u.value.value==="use client"),c=[...n].filter(([,u])=>u.has(o.file));if(!l||c.length!==1||c[0]?.[0]!==s)return ft("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function Gy(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 AA(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function TA(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 rT}from"node:crypto";import yr from"node:path";import{parse as oT}from"@babel/parser";import iT from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as uc,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as ox,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as sT,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as aT,SiteEditMaterializationSchema as cT,parseComponentI18nResourcesJson as lT}from"@vcp-dev/contracts";import{parse as HA}from"@babel/parser";import WA from"@babel/traverse";import{GeneratedSiteCapabilitiesSchema as GA,FormDefinitionIdSchema as YA}from"@vcp-dev/contracts";var Qy={colorMixPolicy:"always",includeExtendedColorFunctions:!0},ex=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,tx=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,wA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,OA=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,FA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,LA=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,DA=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,MA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,BA=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,jA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,$A=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,UA=/\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,VA=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,KA=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Md(e,t){let n=lc([...kn(e,wA),...kn(e,OA),...kn(e,FA),...kn(e,t.includeRgbBackgroundImage?LA:DA),...t.includeExtendedColorFunctions?[...kn(e,MA),...kn(e,BA)]:[]]),r=lc([...kn(e,jA),...kn(e,$A)]).filter(o=>t.colorMixPolicy==="always"||ex.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...kn(e,UA).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...kn(e,KA).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:lc(kn(e,tx)),hardCodedSurfaceOccurrences:zA(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?JA(e):[]}}function JA(e){return lc(kn(e,VA))}function kn(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var qy=160,XA=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function zA(e){let t=new RegExp(tx.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,l=n.length-1;for(;a<l;){let c=Math.ceil((a+l)/2);(n[c]??0)<=s?a=c:l=c-1}return a},o=[],i;for(;(i=t.exec(e))!==null;){let s=i[0],a=s.endsWith("/")?s.slice(0,-1):s,l=/^\/(\d+)/.exec(e.slice(i.index+a.length)),c=e.slice(Math.max(0,i.index-64),i.index),u=
|
|
6
|
-
`,i.index),g=e.slice(n[d]??0,f===-1?void 0:f).trim();o.push({token:a,variant:u?.[1]??"",alpha:l?Number(l[1]):null,line:d+1,snippet:g.length>qy?`${g.slice(0,qy-1)}\u2026`:g})}return o}function lc(e){return[...new Set(e)]}var ZA=["@/components/site/","@/lib/generated/","@/lib/cms","@/lib/cms/"],qA=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),nx=new Set(["require","module","exports","__dirname","__filename"]),Bd=WA,QA=typeof Bd=="function"?Bd:Bd.default;function $d(e,t={}){let n=[],r=eT(t.hostCapabilities),o=Md(e,t.style??Qy),i;try{i=HA(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"&&nT(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 QA(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){c(jd(u.node))},OptionalMemberExpression(u){c(jd(u.node))},Identifier(u){u.isReferencedIdentifier()&&c(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)&&YA.safeParse(/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(u)?.[1]).success)&&!(u.startsWith("./")||u.startsWith("../"))){if(t.allowSiteOwnedImports&&ZA.some(d=>d.endsWith("/")?u.startsWith(d):u===d)){l(u);return}r?tT(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}),l(u)}}function l(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 c(u){if(!(!u||!qA.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:nx.has(u)?"commonjs-forbidden":"browser-global-forbidden",message:nx.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=GA.safeParse(e);return t.success?t.data:null}function tT(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)):rx(n)===rx(o)})}function rx(e){return e.replace(/\.(?:jsx?|tsx?|json)$/i,"")}function nT(e){return e.hardCodedSurfaceHits.length>0||e.rawColorHits.length>0||e.privateTokenHits.length>0}function jd(e){return e.type==="Identifier"?e.name:e.type==="MemberExpression"||e.type==="OptionalMemberExpression"?jd(e.object):null}var ux="components/site/generated",ix="{{$INSTANCE}}",dc=5,uT=/^[a-z][a-z0-9-]{0,48}$/,dT=/^[a-f0-9]{8}$/,sx=/\.tsx?$/,fT=/\.json$/,pT=/\.(?:tsx?|json)$/,mT=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Ud=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Vd=iT,gT=typeof Vd=="function"?Vd:Vd.default;function hT(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>ox)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=TT(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=cT.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=CT(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${ux}.`,path:e.generatedRoot}};if(!dx(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=cx(r.data.files),s=cx(e.controlledFiles);if(!wT(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>ox)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[l,c]of r.data.files.entries()){let u=Buffer.byteLength(c.content,"utf8");if(u>sT)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file exceeds the per-file content limit.",file:c.pathTemplate,path:`files[${l}]`}};a+=u}return a>aT?{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 yT(e){let t=hT(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=dx(e.manifest.instanceBaseName),o=Math.max(1,Math.min(dc,e.maxAttempts??dc));for(let i=0;i<o;i+=1){let s=NT(e.instanceNameGenerator?.()??rT(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}`,l=px(n,a),c=xT({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:l,hostCapabilities:e.hostCapabilities??null,availableHostDependencies:e.availableHostDependencies});if(!c.ok)return c;if(!await ET(e.exists,l,c.data.files))return{ok:!0,data:c.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function Kd(e){let t=Math.max(1,Math.min(dc,e.maxAttempts??dc));for(let n=0;n<t;n+=1){let r=await yT({...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 xT(e){let t=bT(e);if(t)return{ok:!1,error:t};let n=[],r=new Set;for(let s of e.manifest.files){let a=ns({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=ns({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=Jd({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 bT(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 ET(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function ns(e){if(e.pathTemplate.split(ix).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(ix,e.instanceName),n=AT(t);return n?px(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||!pT.test(n)||mT.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 Jd(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)),l=new Map,c=new Map(t.map(g=>[g.path,new Set])),u=new Map;for(let g of t){if(fT.test(g.path)){if(g.path.endsWith(uc)){let x=lT(g.content);if(!x.success)return hr("MATERIALIZATION_DATA_UNSUPPORTED",x.error.message,g.path);u.set(g.path,new Set)}else try{JSON.parse(g.content)}catch{return hr("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",g.path)}continue}let m;try{m=oT(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=$d(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}}),h=vT(p.violations,g.path);if(h)return{ok:!1,error:h};l.set(g.path,m)}for(let g of t){if(!sx.test(g.path))continue;let m=l.get(g.path),p=null;if(gT(m,{ImportDeclaration(h){let x=ax({importer:g.path,source:h.node.source.value,instanceRoot:n,filePaths:a});if(!x.allowed)p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:g.path},h.stop();else if(!x.internalPath&&!IT(h.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},h.stop();else if(x.internalPath&&(c.get(g.path).add(x.internalPath),x.internalPath.endsWith(uc))){let E=_T({importer:g.path,imported:x.internalPath,source:h.node.source.value,ast:m});E.ok?u.get(x.internalPath).add(g.path):(p??=E.error,h.stop())}},ExportAllDeclaration(h){p??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:g.path},h.stop()},ExportNamedDeclaration(h){if(h.node.source){let x=ax({importer:g.path,source:h.node.source.value,instanceRoot:n,filePaths:a});!x.allowed||!x.internalPath&&!e.trustedManagedImports?.includes(h.node.source.value)?(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:g.path},h.stop()):x.internalPath&&c.get(g.path).add(x.internalPath)}},CallExpression(h){if(h.node.callee.type==="Import"){p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:g.path},h.stop();return}h.node.callee.type==="Identifier"&&h.node.callee.name==="require"&&(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:g.path},h.stop())},NewExpression(h){h.node.callee.type==="Identifier"&&h.node.callee.name==="Function"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:g.path},h.stop())},MetaProperty(h){h.node.meta.type==="Identifier"&&h.node.meta.name==="import"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:g.path},h.stop())},MemberExpression(h){let x=lx(h.node);x&&Ud.has(x)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},h.stop())},OptionalMemberExpression(h){let x=lx(h.node);x&&Ud.has(x)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},h.stop())},Identifier(h){h.isReferencedIdentifier()&&Ud.has(h.node.name)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h.node.name}.`,file:g.path},h.stop())},JSXAttribute(h){!e.preserveCapturedStyles||h.node.name.type!=="JSXIdentifier"||h.node.name.name!=="style"||ST(h.node.value)||(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:g.path},h.stop())},JSXOpeningElement(h){h.node.name.type==="JSXIdentifier"&&h.node.name.name.toLowerCase()==="style"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:g.path},h.stop())},StringLiteral(h){e.preserveCapturedStyles&&fc(h.node.value)&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:g.path},h.stop())},TemplateElement(h){e.preserveCapturedStyles&&fc(h.node.value.cooked??h.node.value.raw)&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:g.path},h.stop())},JSXElement(h){let x=h.node.openingElement.name;e.preserveCapturedStyles&&x.type==="JSXIdentifier"&&["script","iframe","object","embed"].includes(x.name.toLowerCase())&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Captured components cannot embed executable external documents.",file:g.path},h.stop())}}),p)return{ok:!1,error:p}}if(r.length===0)return hr("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 hr("MATERIALIZATION_PATH_INVALID",`Static prefab contains duplicate source entries: ${g.path}`,g.path);if(d.add(g.path),!sx.test(g.path))return hr("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",g.path);let m=l.get(g.path);if(!m)return hr("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",g.path);if(!RT(m,g.export))return hr("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 hr("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 PT(g.path,c))f.add(m);return f.size!==t.length?hr("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",r[0]?.path):{ok:!0}}function fc(e){return/(?:url|expression)\s*\(|@import|javascript:|-moz-binding|\\/iu.test(e)}function ST(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"||fc(n))return!1;let r=t.value;return r.type==="StringLiteral"&&!fc(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 ax(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return{allowed:!0};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=yr.posix.normalize(yr.posix.join(yr.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 IT(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 _T(e){let t=yr.posix.dirname(e.importer),n=yr.posix.dirname(e.imported),r=yr.posix.basename(e.importer).replace(/\.tsx?$/,""),o=yr.posix.basename(e.imported).slice(0,-uc.length),i=`./${r}${uc}`;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 RT(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 PT(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 hr(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function CT(e){let t=fx(e);return t===ux?t:null}function NT(e){let t=e.trim().toLowerCase();return dT.test(t)?t:null}function dx(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 uT.test(t)?t:null}function fx(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=yr.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function AT(e){let t=fx(e);return!t||t!==e?null:t}function px(...e){return yr.posix.join(...e)}function cx(e){return new Set(e.map(t=>t.pathTemplate))}function TT(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 wT(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function lx(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 yf}from"node:crypto";import uf from"@babel/traverse";function Xd(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 l=Object.freeze([...a]),c=l.find(u=>u.anchorSourceRange!==null&&u.members.length>0)??l.find(u=>u.members.length>0)??l[0];c&&(o.set(s,l),i.set(s,c),r.set(s,Object.freeze({placementUnitKey:s,placementKeys:Object.freeze(l.map(u=>u.placementKey)),sourcePlacementKey:c.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}function pc(e){if(e.node.alternate||!OT(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,l=a.type==="Identifier"?a.name:a.value,c=s.path.parentPath;return!!(l==="notFound"&&c?.isImportDeclaration()&&c.node.importKind!=="type"&&c.node.source.value==="next/navigation")}function OT(e){let t=mx(e);return e.traverse({enter(n){mx(n)||(t=!1,n.stop())}}),t}function mx(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 rw}from"node:crypto";import _x from"node:path";import*as Zo from"@babel/parser";import ef from"@babel/traverse";import tf from"@babel/generator";import*as me from"@babel/types";import Yd from"@babel/generator";import{parse as JT}from"@babel/parser";import Zd from"@babel/traverse";import*as we from"@babel/types";import{PortableInvocationBindingSchema as XT}from"@vcp-dev/contracts";import zd from"@babel/traverse";import*as De from"@babel/types";var gx=typeof zd=="function"?zd:zd.default;function Ut(e){let t=yx(e.module,e.exportName,e.parsedModules??new Map([[e.module.file,e.module]]),new Set);return t?hx(t,e.allowNonRenderingGuards):Fr("component-export-unresolved","The requested local component export is not a statically resolvable function.",e.module.file)}function _n(e){let t=FT(e.module,e.componentName,e.callSourceRange);return t.kind==="local"?hx(t.definition):t.kind==="imported"?!e.imported?.module&&!mt(t.specifier)?Fr("component-external-module-opaque","External package components are opaque to the local source graph.",t.specifier):e.imported?e.imported.module?Ut({module:e.imported.module,exportName:e.imported.exportName,parsedModules:e.imported.parsedModules}):Fr("component-module-unavailable","The component source module is unavailable in the parsed graph.",e.imported.file):Fr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file):Fr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file)}function hx(e,t=!1){let n=jT(e.module.ast,e.node);if(!n)return Fr("component-function-unresolved","The component function has no source AST path.",e.module.file);let r=xx(n,t);if(!r){let s=UT(n);return s?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:!1,roots:[s[0]],returnAlternatives:s}:Fr("component-control-flow-unsupported","Component roots require an expression body or one direct return.",e.module.file)}let o=[],i=bx(r);return gc(r,o)?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:i,roots:o}:Fr("component-root-dynamic","Component return contains an unsupported dynamic or spread root.",e.module.file)}function FT(e,t,n){let r={kind:"unresolved"};return gx(e.ast,{JSXElement(o){if(!MT(o.node.loc,n))return;let i=o.node.openingElement.name;if(!De.isJSXIdentifier(i)||i.name!==t)return;let s=o.scope.getBinding(t);if(!s||s.constantViolations.length>0){o.stop();return}if(LT(s.path)){let l=s.path.parentPath;l?.isImportDeclaration()&&(r={kind:"imported",specifier:l.node.source.value}),o.stop();return}let a=DT(s.path);a&&(r={kind:"local",definition:{node:a,name:t,module:e}}),o.stop()}}),r}function LT(e){return e.isImportSpecifier()||e.isImportDefaultSpecifier()||e.isImportNamespaceSpecifier()}function DT(e){if(e.isFunctionDeclaration())return e.node;if(!e.isVariableDeclarator())return null;let t=e.get("init");return!Array.isArray(t)&&Gd(t.node)?t.node:null}function MT(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 yx(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=Rr(e.file,u,n),g=f?n.get(f):void 0;return g?yx(g,d,n,i):null},a=u=>{let d=BT(e,u);if(d)return{...d,module:e};for(let f of e.ast.program.body)if(!(!De.isImportDeclaration(f)||f.importKind==="type")){for(let g of f.specifiers)if(g.local.name===u){if(De.isImportDefaultSpecifier(g))return s(f.source.value,"default");if(De.isImportSpecifier(g)&&g.importKind!=="type")return s(f.source.value,mc(g.imported))}}return null};for(let u of e.ast.program.body){if(De.isExportDefaultDeclaration(u)&&t==="default"){let d=u.declaration;if(Gd(d))return{node:d,name:KT(d)??"default",module:e};if(De.isIdentifier(d))return a(d.name)}if(!(!De.isExportNamedDeclaration(u)||u.exportKind==="type")){if(u.declaration){let d=VT(u.declaration,t);if(d)return a(d)}for(let d of u.specifiers)if(De.isExportSpecifier(d)&&d.exportKind!=="type"&&mc(d.exported)===t)return u.source?s(u.source.value,mc(d.local)):a(mc(d.local))}}let l=e.ast.program.body.flatMap(u=>{if(!De.isExportAllDeclaration(u)||u.exportKind==="type"||t==="default")return[];let d=s(u.source.value,t);return d?[d]:[]}),c=l.filter((u,d)=>l.findIndex(f=>f.node===u.node&&f.module.file===u.module.file)===d);return c.length===1?c[0]:null}function BT(e,t){for(let n of e.ast.program.body){let r=De.isExportNamedDeclaration(n)?n.declaration:n;if(De.isFunctionDeclaration(r)&&r.id?.name===t)return{node:r,name:t};if(De.isVariableDeclaration(r)){for(let o of r.declarations)if(De.isIdentifier(o.id)&&o.id.name===t&&Gd(o.init))return{node:o.init,name:t}}}return null}function jT(e,t){let n=null;return gx(e,{Function(r){r.node===t&&(n=r,r.stop())}}),n}function xx(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()||$T(i)||t&&i.isIfStatement()&&pc(i))?null:o.get("argument")}function $T(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(!De.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 UT(e){let t=e.get("body");if(!t.isBlockStatement())return null;let n=Hd(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(!De.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(l=>!De.isJSXText(l)||l.value.trim()!=="")||i.node.openingElement.attributes.some(l=>De.isJSXSpreadAttribute(l)||De.isJSXAttribute(l)&&De.isJSXIdentifier(l.name,{name:"children"}))))return null;r.push(i)}return r}function Hd(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=>Hd(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:Hd(e.slice(t+1));return o&&s?[...o,...s]:null}return null}function gc(e,t){if(bx(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()||!gc(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()||gc(n,t)}return e.isParenthesizedExpression()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTypeCastExpression()?gc(e.get("expression"),t):e.isNullLiteral()||e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()}function Wd(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 De.isJSXIdentifier(o)&&Wd(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||!De.isIdentifier(o.node.property,{name:"map"})||i.length!==1)return!1;let s=i[0];if(!s.isArrowFunctionExpression()&&!s.isFunctionExpression())return!1;let a=xx(s);return a!==null&&n(a)}return!1};return n(e)&&t}function VT(e,t){return De.isFunctionDeclaration(e)?e.id?.name===t?t:null:De.isVariableDeclaration(e)&&e.declarations.some(n=>De.isIdentifier(n.id)&&n.id.name===t)?t:null}function Gd(e){return De.isFunctionDeclaration(e)||De.isFunctionExpression(e)||De.isArrowFunctionExpression(e)}function KT(e){return"id"in e&&e.id&&De.isIdentifier(e.id)?e.id.name:null}function mc(e){return De.isIdentifier(e)?e.name:e.value}function Fr(e,t,n){return{ok:!1,diagnostic:{code:e,message:t,file:n}}}var qd=typeof Yd=="function"?Yd:Yd.default,Ex=typeof Zd=="function"?Zd:Zd.default,vx=new Set(["sourceBlockId","source_block_id","originalBlockId","original_block_id"]),zT=new Set(["sourceOrder","source_order","originalOrder","original_order"]),HT=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"]),WT=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,GT=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u;function Dr(e){if(!kx(e)||!Array.isArray(e.bindings))return Lr("INVOCATION_INPUT_INVALID","bindings must be an array in a portable invocation.","bindings");let t=QT(e);if(!t||!GT.test(t))return Lr("INVOCATION_COMPONENT_INVALID","Portable invocation requires a safe JSX component local name.","component");let n=Ix(e.targetBlockId);if(!n.ok)return n;let r=ew(e.targetOrder);if(!r.ok)return r;let o=e.searchParamsIdentifier??"searchParams";if(!WT.test(o))return Lr("INVOCATION_VALUE_UNRESOLVED","The route searchParams binding requires a safe local identifier.","searchParamsIdentifier");let i=[],s=[],a=new Set,l=!1,c=!1,u=0;for(let[f,g]of e.bindings.entries()){let m=XT.safeParse(g);if(!m.success)return Lr("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 Lr("INVOCATION_DUPLICATE_PROP",`Portable invocation contains duplicate prop ${p.propName}.`,`bindings.${f}.propName`);if(a.add(p.propName),zT.has(p.propName))return Lr("INVOCATION_SOURCE_METADATA","Source block order cannot be copied or rebound as a component prop.",`bindings.${f}`);if(vx.has(p.propName)&&p.value.kind!=="target-block-id")return Lr("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 Lr("INVOCATION_DUPLICATE_PROP","A portable invocation may bind the target block identity only once.",`bindings.${f}`);p.value.kind==="route-search-params"&&(l=!0),p.value.kind==="route-params"&&(c=!0),s.push(p),i.push(we.jsxAttribute(we.jsxIdentifier(p.propName),we.jsxExpressionContainer(ZT(p.value,n.value,o))))}let d=we.jsxElement(we.jsxOpeningElement(qT(t),i,!0),null,[],!0);return{ok:!0,plan:{kind:"portable-invocation",component:t,jsx:qd(d,{jsescOption:{minimal:!0}}).code,bindings:s,targetBlockId:n.value,targetOrder:r.value,requiresRouteSearchParams:l,requiresRouteParams:c,searchParamsIdentifier:l?o:null}}}function YT(e){if(!kx(e)||e.jsx===void 0==(e.source===void 0))return Go("BLOCK_METADATA_INPUT_INVALID","Provide exactly one JSX expression or full source module.","input");let t=Ix(e.targetBlockId);if(!t.ok)return Go("BLOCK_METADATA_TARGET_INVALID",t.error.message,"targetBlockId");if(!Number.isSafeInteger(e.targetOrder)||e.targetOrder<0)return Go("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=Ee("portable-entry.tsx",e.source);if(!g.ok)throw new Error(g.diagnostic.message);o=g.module,r=o.ast}else r=JT(n?e.jsx:e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(g){return Go("BLOCK_METADATA_PARSE_FAILED",g instanceof Error?g.message:String(g),n?"jsx":"source")}let i=[],s;if(o&&e.entryExport){let g=Ut({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 Ex(r,{JSXElement(g){Sx(g)||i.push(g.node)},JSXFragment(g){Sx(g)||i.push(g.node)}});if(i.length!==1)return Go("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one JSX root.",n?"jsx":"source");let a=i[0],l=tw(a);if(!l)return Go("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one direct JSX element root.",n?"jsx":"source");let c=0,u=0,d=g=>{let m=nw(g.node.name);!m||!HT.has(m)||(m==="data-site-block-id"||m==="data-vcp-block-id"||vx.has(m)?c+=1:u+=1,g.remove())};s?s.traverse({JSXAttribute:d}):Ex(r,{JSXAttribute:d}),l.openingElement.attributes.push(we.jsxAttribute(we.jsxIdentifier("data-site-block-id"),we.stringLiteral(t.value)),we.jsxAttribute(we.jsxIdentifier("data-site-block-order"),we.jsxExpressionContainer(we.numericLiteral(e.targetOrder))));let f=n?qd(a,{jsescOption:{minimal:!0}}).code:qd(r,{jsescOption:{minimal:!0}}).code;return{ok:!0,plan:{kind:"portable-block-metadata",source:f,jsx:f,targetBlockId:t.value,targetOrder:e.targetOrder,removedSourceBlockIdCount:c,removedSourceOrderCount:u}}}function ZT(e,t,n){return e.kind==="route-params"?we.identifier("params"):e.kind==="route-search-params"?we.identifier(n):e.kind==="target-block-id"?we.stringLiteral(t):Qd(e.value)}function Qd(e){return e===null?we.nullLiteral():typeof e=="string"?we.stringLiteral(e):typeof e=="number"?we.numericLiteral(e):typeof e=="boolean"?we.booleanLiteral(e):Array.isArray(e)?we.arrayExpression(e.map(t=>Qd(t))):we.objectExpression(Object.entries(e).map(([t,n])=>we.objectProperty(we.stringLiteral(t),Qd(n))))}function qT(e){let t=e.split("."),n=we.jsxIdentifier(t[0]);for(let r of t.slice(1))n=we.jsxMemberExpression(n,we.jsxIdentifier(r));return n}function QT(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 Ix(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 tw(e){if(we.isJSXElement(e))return e;let t=e.children.filter(we.isJSXElement),n=e.children.some(r=>we.isJSXText(r)&&r.value.trim().length>0);return t.length===1&&!n?t[0]??null:null}function Sx(e){let t=e.parentPath;for(;t;){if(t.isJSXElement()||t.isJSXFragment())return!0;t=t.parentPath}return!1}function nw(e){return we.isJSXIdentifier(e)?e.name:null}function kx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lr(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}function Go(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}var nf=typeof tf=="function"?tf:tf.default,ow=typeof ef=="function"?ef:ef.default;function ss(e){let t=Tx(e);if(t)return{ok:!1,error:t};let n=e.projection,r=lf(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=aw(n,o),s=yw(e);if(!s.ok)return s;let a={jsx:s.invocation?.jsx??`<${e.component.localName} />`},l=iw(e);if(i){let m=rf(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:l,...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 c=o.containerSourceRange??n.container.sourceRange,u=o.containerSourceHash??(yc(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!u)return rs("Route page composition does not expose a verifiable container boundary.");let d=is(c),f=Px(e.source,d,u,"Route page composition container");if(!f.ok)return f.result;let g=o.anchorSourceRange?is(o.anchorSourceRange):void 0;if(g){if(!o.anchorSourceHash)return rs("Route page composition placement does not expose a verifiable anchor boundary.");let m=Px(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:l,...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 af(e){let t=Ee(e.entryFile,e.source);if(!t.ok)return Mr("PORTABLE_ROUTE_SOURCE_INVALID",t.diagnostic.message);let n=On({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 Mr("PORTABLE_ROUTE_UNSUPPORTED","Portable route does not expose a supported page-composition boundary.",n.projection.diagnostics);let r=n.projection.placements.flatMap(c=>{if(c.relation!==e.anchor.relation)return[];if(e.anchor.sourceRange)return c.anchorSourceRange&&yc(c.anchorSourceRange,e.anchor.sourceRange)?[{placement:c,matchCount:1}]:[];let u=c.members.reduce((d,f)=>d+Nx(f,e.anchor.componentName),0);return u===0?[]:[{placement:c,matchCount:u}]}),o=r.reduce((c,u)=>c+u.matchCount,0);if(o===0)return Mr("PORTABLE_ROUTE_ANCHOR_MISSING","Portable route anchor was not found in the canonical page composition.");if(o!==1||r.length!==1)return Mr("PORTABLE_ROUTE_ANCHOR_AMBIGUOUS","Portable route anchor does not identify exactly one page-composition gap.");let i=ss({routeId:e.routeId,entryFile:e.entryFile,currentDocumentVersion:e.documentVersion,expectedDocumentVersion:e.documentVersion,source:e.source,projection:n.projection,placementKey:r[0].placement.placementKey,component:e.component,invocation:e.invocation});if(!i.ok)return i;let s=e.source,a=i.plan.rewriteStep;if(a.kind==="insert-root-expression"){let c=as({source:s,locator:a.locator,expectedSourceHash:a.sourceHash,action:{kind:"insert",jsx:a.node.jsx,placement:a.placement,replaceOriginal:a.replaceOriginal}});if(!c.ok)return Mr("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message);s=c.source}else{let c=Sn({source:s,locator:a.parentLocator,node:a.node,placement:a.placement,...a.anchorLocator?{anchorLocator:a.anchorLocator}:{}});if(!c.ok)return Mr("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message);s=c.source}if(i.plan.serverParamsStep){let c=wx({source:s,step:i.plan.serverParamsStep});if(!c.ok)return Mr("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message);s=c.source}let l=vn({source:s,moduleSpecifier:i.plan.importStep.moduleSpecifier,imports:i.plan.importStep.imports});return l.ok?{ok:!0,plan:i.plan,patch:{kind:"portable-route-composition-patch",path:e.entryFile,expectedSourceHash:t.module.sourceHash,source:l.source}}:Mr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message)}function Nx(e,t){return(e.label===t?1:0)+e.children.reduce((n,r)=>n+Nx(r,t),0)}function Mr(e,t,n=[]){return{ok:!1,error:{code:e,message:t,diagnostics:n}}}function iw(e){let t=dw(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 as(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return yo(e.source,"Root expression rewrite requires an exact expression locator.");let t=Oi(e.source,"value");if(!t.ok)return yo(e.source,t.diagnostic.message);let n=Ne(t.ast,e.locator);if(!n.ok)return yo(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return yo(e.source,"Resolved value locator does not point to an expression.");let o=Yo(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return yo(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(me.nullLiteral()),{ok:!0,source:nf(t.ast,{}).code};let i;try{i=Zo.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return yo(e.source,s instanceof Error?s.message:String(s))}return!me.isJSXElement(i)&&!me.isJSXFragment(i)?yo(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(sw(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:nf(t.ast,{}).code})}function sw(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 yo(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function cf(e){let t=Tx(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Bx(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(cw(n,o)){let p=rf(e);return p.ok?e.operation==="remove-node"&&!Rx(n,o.placementUnitKey)?rs("The last editable page unit cannot be deleted."):e.operation==="move-node"?rs("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=is(o.sourceRange),a=zn(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?[]:[os(a.diagnostic)]}};if(Yo(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=rf(e);return p.ok?Rx(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}}}:rs("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||!uw(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 c=lf(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!c.ok)return{ok:!1,error:{code:c.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:c.diagnostic.message,diagnostics:[c.diagnostic]}};let u=c.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=is(d),g=zn(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?[]:[os(g.diagnostic)]}};if(Yo(e.source,g.match.node.start??null,g.match.node.end??null)!==u.containerSourceHash)return Cx("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let p=u.anchorSourceRange,h=u.anchorSourceHash;if(!p||!h)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=is(p),E=zn(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?[]:[os(E.diagnostic)]}}:Yo(e.source,E.match.node.start??null,E.match.node.end??null)!==h?Cx("Route page composition target anchor hash no longer matches the current source."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:f,anchorLocator:x,placement:u.relation}}}}return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:f,placement:u.relation}}}}function Rx(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function aw(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&yc(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 cw(e,t){return e.container.kind!=="jsx-container"&&yc(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function rf(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=zn(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?[]:[os(r.diagnostic)]}}}:Yo(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Ax("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function Px(e,t,n,r){let o=zn(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?[]:[os(o.diagnostic)]}}}:Yo(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Ax(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Ax(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function rs(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Cx(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function os(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Tx(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&&!lw(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 lw(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function uw(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function dw(e,t){let n=_x.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=_x.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function is(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Yo(e,t,n){return t==null||n==null?null:`sha256:${rw("sha256").update(e.slice(t,n)).digest("hex")}`}function yc(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 wx(e){let t;try{t=Zo.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=fw(t,e.step);return n.ok?{ok:!0,source:nf(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:n.message}}}function fw(e,t){let n=Dx(e);if(!n)return{ok:!1,message:"Route default function could not be resolved for searchParams wiring."};let r=sf(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."}:Fx(r)!==t.identifier?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:{ok:!0};let o=Ox(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?of():pw()),{ok:!0};let i=n.node.params[0],s=sf(i);return s?(mw(s,t.typescript),{ok:!0}):{ok:!1,message:"Route page parameter is not a supported object pattern."}}function pw(){return me.objectPattern([me.objectProperty(me.identifier("searchParams"),me.identifier("searchParams"),!1,!0)])}function of(){let t=Zo.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 mw(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=Lx(e);if(!o){e.typeAnnotation=of().typeAnnotation;return}if(!me.isTSTypeLiteral(o.typeAnnotation))return;let i=of().typeAnnotation;if(!i||!me.isTSTypeAnnotation(i)||!me.isTSTypeLiteral(i.typeAnnotation))return;let s=i.typeAnnotation.members[0];s&&!gw(o.typeAnnotation)&&o.typeAnnotation.members.push(me.cloneNode(s,!0))}function gw(e){return e.members.some(t=>!("key"in t)||!t.key?!1:Mx(t.key)==="searchParams")}function hw(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 yw(e){if(!e.invocation)return{ok:!0};let t=Dr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!t.ok)return hc(t.error.message);if(t.plan.requiresRouteParams)return hc("A captured native detail parameter has no independently proven target route binding.","UNSUPPORTED_ROUTE_PARAMS");let n;if(t.plan.requiresRouteSearchParams){let r=xw(e.source,e.entryFile);if(!r.ok)return hc(r.message,"UNSUPPORTED_ROUTE_PARAMS");if(n=r.step,r.step.identifier!==t.plan.searchParamsIdentifier&&(t=Dr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder,searchParamsIdentifier:r.step.identifier}),!t.ok))return hc(t.error.message)}return{ok:!0,invocation:t.plan,...n?{serverParamsStep:n}:{}}}function hc(e,t="PORTABLE_INVOCATION_INVALID"){return{ok:!1,error:{code:t,message:e,diagnostics:[]}}}function xw(e,t){let n;try{n=Zo.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=Dx(n);if(!r)return{ok:!1,message:"Portable route searchParams wiring requires a default server function."};let o=/\.(?:ts|tsx)$/iu.test(t),i=Ox(r.node.params,o);return i.ok?{ok:!0,step:{kind:"ensure-search-params",action:i.action,identifier:i.identifier,typescript:o}}:i}function Ox(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=sf(e[0]);if(!n)return{ok:!1,message:"Portable route searchParams wiring requires an object page parameter or an empty signature."};let r=Fx(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&&!bw(n)?{ok:!1,message:"Portable route searchParams wiring cannot safely extend this typed page signature."}:{ok:!0,action:"add",identifier:"searchParams"}}function sf(e){return!e||me.isTSParameterProperty(e)?null:me.isObjectPattern(e)?e:me.isAssignmentPattern(e)&&me.isObjectPattern(e.left)?e.left:null}function Fx(e){for(let t of e.properties)if(!(!me.isObjectProperty(t)||t.computed||Mx(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 bw(e){let t=Lx(e);return t?me.isTSTypeLiteral(t.typeAnnotation):e.properties.length===0}function Lx(e){return e.typeAnnotation&&me.isTSTypeAnnotation(e.typeAnnotation)?e.typeAnnotation:null}function Dx(e){let t=null;return ow(e,{ExportDefaultDeclaration(n){if(t)return;let r=hw(n,n.get("declaration"));r&&(t=r)}}),t}function Mx(e){return me.isIdentifier(e)?e.name:me.isStringLiteral(e)?e.value:null}var Ew=typeof uf=="function"?uf:uf.default;function On(e){if(!e.ast)return Fn(e,[Nt("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=Cw(e.ast);if(!t)return Fn(e,[Nt("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=Aw(t);if(!n.ok)return Fn(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=ww(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return Fn(e,[Nt("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(Fw(r,t))return Fn(e,[Nt("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return ff(e,t,"virtual-route-root",r);if(Ow(r)){let o=Bw({input:e,source:e.source,expression:r});return df(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return Fn(e,[Nt("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!it(r)&&!ls(r)){let o=gf(r),i=Ux({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return df(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=Dw(r);if(!o.ok)return Fn(e,[o.diagnostic]);let i=qo(o.path);if(i.unsupported)return Fn(e,[Nt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(Lw(e.source,r,i.members))return ff(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||it(r);if(i.members.length===0&&s)return ff(e,t,"virtual-route-root",r);let a=o.path===r&&s?"virtual-route-root":"jsx-container",l=o.path.isJSXFragment()?"jsx-fragment":"jsx-element",c=Ux({input:e,containerKind:a,sourceKind:l,source:e.source,containerPath:o.path,members:i.members});return df(e,t,c,{kind:a,sourceKind:l},r)}return Fn(e,[Nt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function lf(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Nt("DOCUMENT_VERSION_STALE","Placement lookup is stale for the requested document version",{expectedDocumentVersion:e.documentVersion,requestedDocumentVersion:n})};let r=e.placementByKey.get(t)??null;return r?{ok:!0,placement:r}:{ok:!1,diagnostic:Nt("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function Bx(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Nt("DOCUMENT_VERSION_STALE","Placement lookup is stale for the requested document version",{expectedDocumentVersion:e.documentVersion,requestedDocumentVersion:n})};let r=e.placementUnitByKey.get(t)??null;return r?{ok:!0,placement:r}:{ok:!1,diagnostic:Nt("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Vx(e){return e.ok?Sw(e.projection):vw(e.projection)}function Sw(e){let t=new Map,n=[];for(let c of e.placements)c.members.length===0&&e.placements.length>1||c.members.length>0&&!c.anchorSourceRange||t.has(c.placementUnitKey)||t.set(c.placementUnitKey,c);let r=new Map,o=new Map;for(let[c,u]of t){let d=u.members.flatMap((p,h)=>Kx(e,u,p,h,e.container.placementKey)),f=d.filter(({member:p})=>p.isBusinessMember).map(({sourceMember:p})=>kw(c,p,u.independent)),g=d.length>0?d:[{sourceMember:{key:`source:${c}: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(c,g.map(({sourceMember:p})=>p)),o.set(c,f);let m=g[0]?.sourceMember.key??c;n.push({key:c,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,l=e.placements.map(c=>({kind:"page-composition",placementKey:c.placementKey,documentVersion:e.documentVersion,composition:e.composition,placementUnitKey:c.placementUnitKey,relation:c.relation}));return{status:"supported",version:e.version,composition:e.composition,container:Iw(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:l}}function vw(e){let t=e.diagnostics.map(_w);return{status:"unsupported",version:e.version,composition:e.composition,reason:Rw(e.diagnostics),diagnostics:t}}function Iw(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 Kx(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,l)=>Kx(e,t,a,l,i))]}function kw(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function _w(e){return{code:Pw(e),message:e.message}}function Rw(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 Pw(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 Cw(e){let t=null;return Ew(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=Nw(o.path);i&&(t=i,n.stop())}}),t}function Nw(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 Aw(e){let t=e.get("body");if(!t.isBlockStatement()){let s=cs(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Nt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")}}let n=t.get("body"),r=n.at(-1);if(!r)return{ok:!1,diagnostic:Nt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Nt("UNSUPPORTED_PAGE_SHAPE","Route default export must end with a direct terminal return",{reason:"terminal-return-required"})};for(let s of n.slice(0,-1)){if(s.isIfStatement()){if(!Tw(s)&&!pc(s))return{ok:!1,diagnostic:Nt("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Jx(s)||Xx(s))return{ok:!1,diagnostic:Nt("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=cs(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Nt("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function Tw(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(Jx(o)||Xx(o))return null;return r}function Jx(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function Xx(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function ww(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 Ow(e){return e.isConditionalExpression()?jx(cs(e.get("consequent")))&&jx(cs(e.get("alternate"))):!1}function jx(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 Fw(e,t){if(e.isIdentifier())return $x(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return $x(n.node.name,t)}return!1}function $x(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 Lw(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&mf(t)}function mf(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(!mf(t))return!1;continue}if(t.isJSXElement()&&!mf(t))return!1}return!0}function Dw(e){return{ok:!0,path:e}}function qo(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:hf(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:Rn(r.node.loc),businessMemberCount:0,parentSourceRange:Rn(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=qo(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=ls(o)?qo(o):null;n||=i?.unsupported??!1,t.push({...gf(o,i?.members),sourceRange:Rn(r.node.loc),parentSourceRange:Rn(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:hf(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:Rn(r.node.loc),businessMemberCount:1,parentSourceRange:Rn(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&it(r)){let o=qo(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=ls(r)?qo(r):null;n||=o?.unsupported??!1,t.push({...gf(r,o?.members),parentSourceRange:Rn(e.node.loc)})}}return{members:t,unsupported:n}}function gf(e,t){let n=e.isJSXElement()&&ls(e)?t??qo(e).members:[],r=e.isJSXElement()&&!ls(e)&&!it(e);return{memberKey:hf(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:Rn(e.node.loc),businessMemberCount:r?1:zx(n),parentSourceRange:Rn(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:Mw(e)}}function ls(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function Mw(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 zx(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function xc(e){return e.length===0?0:Math.max(1,zx(e))}function Ux(e){let t=Rn(e.containerPath.node.loc),n=xf(e.source,e.containerPath.node.start,e.containerPath.node.end),r=Pn(e.input,e.containerKind,e.sourceKind,t),o=Pn(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:xc(e.members)<=1,memberCount:xc(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function Bw(e){let t=Rn(e.expression.node.loc),n=xf(e.source,e.expression.node.start,e.expression.node.end),r=Pn(e.input,"virtual-route-root","atomic-expression",t),o=Pn(e.input,"virtual-route-root","placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:!0,memberCount:1,sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:[{memberKey:Pn(e.input,"virtual-route-root","atomic-member",t),kind:"atomic-expression",nodeType:e.expression.node.type,sourceRange:t,businessMemberCount:1,parentSourceRange:null,children:[],isBusinessMember:!0,label:e.expression.node.type}]}}function Hx(e,t){let n=Rn(t.node.loc),r=xf(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function df(e,t,n,r,o){let i=Hx(e,o);if(!i)return Fn(e,[Nt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=jw(e,n,s),l=Xd(a),c={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Gx(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(c,{placementByKey:{value:l.placementByKey,enumerable:!1},unitByKey:{value:l.unitByKey,enumerable:!1},placementsByUnitKey:{value:l.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:l.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:c}}function jw(e,t,n){if(t.members.length===0)return[t];let r=[],o=(c,u,d,f,g,m,p=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:xc(m)<=1,memberCount:xc(m),sourceRange:f,sourceHash:f?pf(e.source,f):null,relation:c,containerSourceRange:p,containerSourceHash:p?pf(e.source,p):null,anchorSourceRange:g,anchorSourceHash:g?pf(e.source,g):null,members:m}),i=t.placementKey,s=t.members.map(c=>Pn(e,i,"placement-unit",c.sourceRange)),a=s[0]??t.placementUnitKey,l=s.at(-1)??t.placementUnitKey;r.push(o("prepend",Pn(e,i,"prepend",n),a,n,null,[]));for(let c of t.members){let u=c.parentSourceRange??n,d=Pn(e,i,"placement-unit",c.sourceRange);r.push(o("before",Pn(e,d,"before",c.sourceRange),d,c.sourceRange,c.sourceRange,[c],u)),r.push(o("after",Pn(e,d,"after",c.sourceRange),d,c.sourceRange,c.sourceRange,[c],u))}return r.push(o("append",i,l,n,null,[])),r}function ff(e,t,n,r){let o=Hx(e,r);if(!o)return Fn(e,[Nt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=Pn(e,n,"empty-container",void 0),s=Pn(e,n,"empty-unit",void 0),a={placementKey:i,placementUnitKey:s,version:e.version,containerKey:i,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},l=Xd([a]),c={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Gx(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(c,{placementByKey:{value:l.placementByKey,enumerable:!1},unitByKey:{value:l.unitByKey,enumerable:!1},placementsByUnitKey:{value:l.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:l.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:c}}function Fn(e,t){return{ok:!1,projection:{status:"unsupported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,diagnostics:t}}}function Nt(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function Pn(e,t,n,r){return Wx([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function hf(e,t,n){return Wx(["member",e,String(t??-1),String(n??-1)])}function Wx(e){return`pc_${yf("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function xf(e,t,n){return t==null||n==null?null:`sha256:${yf("sha256").update(e.slice(t,n)).digest("hex")}`}function pf(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:${yf("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function Rn(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Gx(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 Zw}from"node:crypto";import*as Ln from"@babel/types";function Yx(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 bf from"@babel/traverse";import*as Qo from"@babel/types";var Uw=typeof bf=="function"?bf:bf.default,Vw=32;function xo(e,t,n,r=new Set){if(r.has(e.ast)||r.size>=Vw)return null;let o=new Set(r).add(e.ast),i;if(Uw(e.ast,{Program(d){i=d,d.stop()}}),!i)return null;let s=(d,f)=>{let g=Rr(e.file,d,n),m=g?n.get(g):void 0;return m?xo(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,bc(f.path.node.imported)):null:f.path.isVariableDeclarator()?f.path.get("init"):f.path},l=[],c=[];for(let d of i.get("body"))if(d.isExportDefaultDeclaration()&&t==="default"){let f=d.get("declaration");l.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(Qo.getBindingIdentifiers(f.node),t)&&l.push(a(t));for(let g of d.node.specifiers)Qo.isExportSpecifier(g)&&g.exportKind!=="type"&&bc(g.exported)===t&&l.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"&&c.push(d.node.source.value);if(l.length)return l.length===1?l[0]:null;let u=c.map(d=>s(d,t)).filter(d=>d!==null);return u.length===1?u[0]:null}function bc(e){return Qo.isIdentifier(e)?e.name:e.value}import*as _e from"@babel/types";var Kw=32;function cn(e,t=new Map,n=new Set){if(n.has(e.node)||n.size>=Kw)return null;let r=new Set(n).add(e.node),o=t.get(e.node);if(o)return us(o,t,r);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTSSatisfiesExpression()||e.isParenthesizedExpression())return cn(e.get("expression"),t,r);if(e.isIdentifier()){let i=e.scope.getBinding(e.node.name);return!i||i.constantViolations.length?null:Sf(i,t,r)}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let i=ln(e.node.property,e.node.computed),s=e.get("object"),a=cn(s,t,r);return i!==null&&a?vc(a,i,t,r):null}if(e.isConditionalExpression())return us([e.get("consequent"),e.get("alternate")],t,r);if(e.isLogicalExpression())return us([e.get("left"),e.get("right")],t,r);if(e.isSequenceExpression()){let i=e.get("expressions").at(-1);return i?cn(i,t,r):null}if(e.isCallExpression()&&_e.isIdentifier(e.node.callee)){let i=e.scope.getBinding(e.node.callee.name);if(!i||!ei(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,l=new Map(t),c=e.get("arguments");for(let[g,m]of a.get("params").entries()){if(!m.isIdentifier())return null;let p=c[g];if(!p?.isExpression())return null;let h=cn(p,t,r);if(!h)return null;let x=m.scope.getBinding(m.node.name);if(!x)return null;l.set(x.identifier,h)}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?cn(f,l,r):null}return[e]}function Sf(e,t=new Map,n=new Set){if(e.constantViolations.length)return null;let r=t.get(e.identifier);if(r)return us(r,t,n);if(!e.path.isVariableDeclarator())return null;let o=e.path.get("init");if(!o.node)return null;let i=cn(o,t,n);if(!i)return null;let s=Ef(e.path.node.id,e.identifier.name);return s?s.reduce((a,l)=>a&&vc(a,l,t,n),i):null}function Ec(e){if(!e.params.every(n=>_e.isIdentifier(n)||_e.isAssignmentPattern(n)&&_e.isIdentifier(n.left)&&xr(n.right)))return!1;if(!_e.isBlockStatement(e.body))return xr(e.body);if(e.body.body.length!==1)return!1;let t=e.body.body[0];return _e.isReturnStatement(t)&&!!t.argument&&xr(t.argument)}function ei(e){if(e.constantViolations.length>0)return!1;if(e.path.isFunctionDeclaration())return Ec(e.path.node);let t=e.path.isVariableDeclarator()?e.path:e.path.findParent(r=>r.isVariableDeclarator()),n=t?.isVariableDeclarator()?t.node.init:null;return _e.isArrowFunctionExpression(n)||_e.isFunctionExpression(n)?Ec(n):!1}function xr(e){let t=!0;return _e.traverseFast(e,n=>{(_e.isCallExpression(n)&&!Sc(n)||_e.isOptionalCallExpression(n)||_e.isNewExpression(n)||_e.isAwaitExpression(n)||_e.isAssignmentExpression(n)||_e.isUpdateExpression(n)||_e.isUnaryExpression(n,{operator:"delete"})||_e.isYieldExpression(n)||_e.isTaggedTemplateExpression(n))&&(t=!1)}),t}function Sc(e){return _e.isIdentifier(e.callee,{name:"useTranslations"})&&e.arguments.length===1&&_e.isStringLiteral(e.arguments[0])}function us(e,t,n){let r=[];for(let o of e){let i=cn(o,t,n);if(!i)return null;r.push(...i)}return r.length?r:null}function vc(e,t,n,r=new Set){let o=[];for(let i of e)if(i.isObjectExpression()){let s=i.get("properties");if(s.some(l=>!l.isObjectProperty()||l.node.computed))return null;let a=s.filter(l=>l.isObjectProperty()&&ln(l.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=>_e.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 us(o,n,r)}function vf(e,t){let n=cn(e,t);return!!(n?.length&&n.every(r=>_e.isLiteral(r.node)&&!r.isRegExpLiteral()||r.isTemplateLiteral()||r.isBinaryExpression()||r.isUnaryExpression()))}function ln(e,t){return!t&&_e.isIdentifier(e)?e.name:_e.isStringLiteral(e)||_e.isNumericLiteral(e)?String(e.value):null}function Ef(e,t){if(_e.isIdentifier(e))return e.name===t?[]:null;if(_e.isObjectPattern(e))for(let n of e.properties){if(!_e.isObjectProperty(n)||n.computed)continue;let r=ln(n.key,!1),o=Ef(n.value,t);if(r!==null&&o)return[r,...o]}if(_e.isArrayPattern(e))for(let[n,r]of e.elements.entries()){if(!r)continue;let o=Ef(r,t);if(o)return[String(n),...o]}return null}function Zx(e,t=new Set,n){return qx(e.get("callee"),t,n)}function qx(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 c=i.node.source.value;if(!(c.startsWith(".")||c.startsWith("@/")))return{kind:"unknown"};let u=r.path.scope.getProgramParent().path.node,d=[...n.values()].find(h=>h.ast.program===u),f=d&&Rr(d.file,c,n),g=f?n.get(f):void 0,m=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()&&r.path.node.importKind!=="type"?ln(r.path.node.imported,!1):null,p=g&&m&&i.node.importKind!=="type"?xo(g,m,n):null;return p?ti(p,o,n):{kind:"guard"}}let s=r.path.isVariableDeclarator()?r.path.get("init"):r.path;if(!s.node)return{kind:"unknown"};let a=ti(s,o,n);if(a.kind!=="sources")return a;let l=[...a.sources];for(let c of r.constantViolations){if(!c.isAssignmentExpression({operator:"="}))return{kind:"guard"};let u=ti(c.get("right"),o,n);if(u.kind!=="sources")return{kind:"guard"};l.push(...u.sources)}return{kind:"sources",sources:l,aliases:a.aliases}}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let r=ln(e.node.property,e.node.computed),o=e.get("object"),i=cn(o);if(!i)return{kind:"unknown"};let s=[],a=new Set(t).add(e.node);for(let l of i){if(!l.isObjectExpression())return{kind:"unknown"};if(r===null||l.node.properties.some(d=>d.type!=="ObjectProperty"))return{kind:"guard"};let c=l.get("properties").filter(d=>d.isObjectProperty()&&ln(d.node.key,d.node.computed)===r);if(c.length!==1||!c[0].isObjectProperty())return{kind:"guard"};let u=ti(c[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 ti(e,new Set(t).add(e.node),n)}function ti(e,t,n){if(e.isIdentifier())return qx(e,t,n);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return ti(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 kc(e,t){return JSON.stringify([t,e])}var Xw=new Set;function rb(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)=>!nb(p)&&[...t].some(h=>e.graph.elements.get(h)?.sourceFile===m);function l(m,p,h,x,E,b=Xw){if(m.isIdentifier())return x&&Ic(m,x)?x.children.some(v=>l(v.path,v.file,h,v.substitution,E,b)):u({path:m,file:p,active:h,substitution:x,unknownIsRelevant:E,aliases:b});if(m.isCallExpression()||m.isOptionalCallExpression()){let v=m,P=Zx(v,b,e.parsedModules);return P.kind==="guard"||P.kind==="sources"&&P.sources.some(I=>l(I,[...e.parsedModules.values()].find(C=>C.ast.program===I.scope.getProgramParent().path.node)?.file??p,h,x,E,P.aliases))?!0:v.get("arguments").some(I=>l(I,p,h,x,E,b))||P.kind==="unknown"&&E}if(m.isJSXElement()){if(it(m))return m.get("children").some(L=>l(L,p,h,x,E,b));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 L=e.parsedModules.get(v.sourceFile);if(!L)return!1;let D=_n({module:L,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:c(D,m,v.sourceFile,h,x,b):D.diagnostic.code==="component-external-module-opaque"?ds(m).some(U=>l(U,p,h,x,!1,b)):a(L.file,D.diagnostic.code)}return m.get("children").some(L=>l(L,p,h,x,E,b))}let P=m.node.openingElement.name;if(!Ln.isJSXIdentifier(P))return!1;if(/^[a-z]/.test(P.name))return m.get("children").some(L=>l(L,p,h,x,E,b));let I=e.parsedModules.get(p),C=m.node.loc;if(!I||!C)return!1;let N=Yw({path:m,file:p,componentName:P.name,parsedModules:e.parsedModules}),w=_n({module:I,componentName:P.name,callSourceRange:{startLine:C.start.line,startColumn:C.start.column,endLine:C.end.line,endColumn:C.end.column},...N?{imported:N}:{}});return w.ok?w.metadataOnly?!1:c(w,m,p,h,x,b):w.diagnostic.code==="component-external-module-opaque"?ds(m).some(L=>l(L,p,h,x,!1,b)):a(I.file,w.diagnostic.code)}if(m.isJSXFragment())return m.get("children").some(v=>l(v,p,h,x,E,b));if(m.isJSXExpressionContainer()||m.isParenthesizedExpression()||m.isTSAsExpression()||m.isTSNonNullExpression()||m.isTSTypeAssertion())return l(m.get("expression"),p,h,x,E,b);let S=!1;return m.traverse({"CallExpression|OptionalCallExpression"(v){l(v,p,h,x,E,b)&&(S=!0),v.skip(),S&&v.stop()},ReferencedIdentifier(v){l(v,p,h,x,E,b)&&(S=!0),S&&v.stop()},JSXElement(v){l(v,p,h,x,E,b)&&(S=!0),v.skip(),S&&v.stop()},JSXFragment(v){l(v,p,h,x,E,b)&&(S=!0),v.skip(),S&&v.stop()}}),S?!0:E&&!bo(m)}function c(m,p,h,x,E,b){let S=`${m.sourceFile}#${m.componentName}`;if(x.has(S))return!1;let v=new Set(x).add(S);return m.returnAlternatives?.some(P=>ds(P).some(I=>l(I,m.sourceFile,v,null,!1,b)))||m.roots.some(P=>l(P,m.sourceFile,v,null,!1,b))?!0:Qx(m.roots).kind==="none"?!1:tb(p).some(P=>l(P,h,v,E,!0,b))}function u(m){if(!m.path.isIdentifier())return m.unknownIsRelevant;let p=Yx({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:l(p.initializer,m.file,m.active,m.substitution,m.unknownIsRelevant,p.aliases)?!0:If(p.initializer).isIdentifier()?!1:m.unknownIsRelevant&&!bo(p.initializer)}let d=(m,p,h,x,E,b)=>{if(m.isIdentifier()){l(m,p,x,b,!1)&&s(p);return}if(m.isJSXElement()){if(it(m)){for(let P of m.get("children"))d(P,p,h,x,E,b);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 P=n.get(v)??[];P.push(kc(v,h)),n.set(v,P)}if(S.boundaryKind==="component-boundary"&&!S.isPublicUiComponent){let P=e.parsedModules.get(S.sourceFile);if(!P)return;let I=_n({module:P,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(!I.ok){if(I.diagnostic.code==="component-external-module-opaque"){ds(m).some(U=>l(U,p,x,b,!1))&&s(p);return}[...t].some(U=>e.graph.elements.get(U)?.sourceFile===P.file)&&!nb(I.diagnostic.code)&&s(P.file);return}if(I.metadataOnly)return;let C=`${I.sourceFile}#${I.componentName}`;if(x.has(C)){s(P.file);return}let N=new Set(x).add(C);I.returnAlternatives?.some(U=>ds(U).some(M=>l(M,I.sourceFile,N,b,!1)))&&s(I.sourceFile);let w=Qx(I.roots),L=Gw(m);if(w.kind==="unproven"||w.kind==="supported"&&L){for(let U of tb(m))if(l(U,p,N,b,!0)){s(p);break}}let D=w.kind==="supported"&&!L?{bindingNode:w.bindingNode,children:m.get("children").map(U=>({path:U,file:p,substitution:b}))}:null;for(let U of I.roots)d(U,I.sourceFile,[...h,v],N,E,D);return}for(let P of m.get("children"))d(P,p,h,x,E,b);return}if(m.isJSXFragment()){for(let S of m.get("children"))d(S,p,h,x,E,b);return}if(m.isJSXExpressionContainer()){let S=m.get("expression");if(b&&!S.isJSXEmptyExpression()){let v=If(S);if(Ic(v,b)){for(let P of b.children)d(P.path,P.file,h,x,E,P.substitution);return}if(zw(S,b))for(let P of b.children)d(P.path,P.file,h,x,!1,P.substitution)}d(S,p,h,x,E,b);return}if(m.isParenthesizedExpression()||m.isTSAsExpression()||m.isTSNonNullExpression()||m.isTSTypeAssertion()){d(m.get("expression"),p,h,x,E,b);return}l(m,p,x,b,!1)&&s(p),m.traverse({JSXElement(S){d(S,p,h,x,!1,b),S.skip()}})},f=e.parsedModules.get(e.entryFile);if(!f)return{occurrences:n,diagnostics:r};let g=Ut({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 If(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();)t=t.get("expression");return t}function bo(e){let t=If(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||bo(n)):t.isConditionalExpression()?bo(t.get("consequent"))&&bo(t.get("alternate")):t.isLogicalExpression()?bo(t.get("left"))&&bo(t.get("right")):!1}function Ic(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 zw(e,t){if(Ic(e,t))return!0;let n=!1;return e.traverse({Identifier(r){Ic(r,t)&&(n=!0,r.stop())}}),n}function Qx(e){let t=e[0]?.getFunctionParent();if(!t)return{kind:"none"};let n=t.get("params")[0];return n?n.isAssignmentPattern()?eb(n.get("left"),!0):eb(n,!1):{kind:"none"}}function eb(e,t){if(e.isObjectPattern()){let n=[],r=!1;for(let i of e.get("properties")){if(i.isObjectProperty()){if(i.node.computed){Gn(i.get("value"))&&(r=!0);continue}let s=i.node.key;(Ln.isIdentifier(s)?s.name:Ln.isStringLiteral(s)?s.value:null)==="children"&&n.push(i);continue}i.isRestElement()&&Gn(i.get("argument"))&&(r=!0)}if(n.length>1)return r||n.some(i=>Gn(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=>Hw(s))?t?{kind:"unproven"}:{kind:"supported",bindingNode:o.node}:{kind:"unproven"}}return Gn(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=>Ww(r))?{kind:"none"}:{kind:"unproven"}}return Gn(e)?{kind:"unproven"}:{kind:"none"}}function Gn(e){if(e.isIdentifier()){let t=e.scope.getBinding(e.node.name);return!!(t&&t.referencePaths.length>0)}return e.isAssignmentPattern()?Gn(e.get("left")):e.isRestElement()?Gn(e.get("argument")):e.isObjectPattern()?e.get("properties").some(t=>t.isObjectProperty()?Gn(t.get("value")):t.isRestElement()?Gn(t.get("argument")):!0):e.isArrayPattern()?e.get("elements").some(t=>t.node?Gn(t):!1):!0}function Hw(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 Ww(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?Ln.isStringLiteral(n)&&n.value!=="children":Ln.isIdentifier(n)&&n.name!=="children"}function Gw(e){for(let t of e.get("openingElement").get("attributes")){if(t.isJSXAttribute()){let n=t.node.name;if(Ln.isJSXIdentifier(n)&&n.name==="children")return!0;continue}if(t.isJSXSpreadAttribute()&&ob(t.get("argument")))return!0}return!1}function tb(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(!Ln.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");ob(r)&&t.push(r)}}return t}function ds(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 ob(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 Yw(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=Rr(e.file,r.node.source.value,e.parsedModules);if(!o)return;let i=n.isImportDefaultSpecifier()?"default":Ln.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 nb(e){return e==="component-export-unresolved"||e==="component-local-binding-unresolved"}function ab(e){let t=[],n=[];return cb(e.element,e,[],e.ownerNode,e.element,[],new Set,t,n),{roots:t,diagnostics:n}}function cb(e,t,n,r,o,i,s,a,l,c=[]){if(c.length>1&&(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent)){l.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(Wd(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){l.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=_n({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){l.push({...d.diagnostic,structuralPath:e.identity.structuralPath});return}if(d.metadataOnly)return;let f=d.sourceFile,g=`${f}#${d.componentName}`;if(s.has(g)){l.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){l.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},...c.length>1?{alternativeLocators:c.map(E=>({key:E.identity.key,structuralPath:E.identity.structuralPath,sourceRange:E.sourceRange}))}:{}}],p=d.roots.length>1?{kind:"component-definition",key:g}:r,h=new Set(s);h.add(g);let x=[];for(let E of d.returnAlternatives??[]){let b=sb(E),S=b?ib(t.graph,f,b):[];if(S.length!==1){l.push({code:"conditional-component-root-unproven",message:"A conditional call site is absent or ambiguous in the source graph.",file:f});return}x.push(S[0])}for(let E of d.roots){let b=sb(E),S=b?ib(t.graph,f,b):[];if(S.length!==1){l.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}cb(S[0],t,m,p,d.roots.length>1?S[0]:o,d.roots.length>1?m:i,h,a,l,x)}}function ib(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 sb(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 _c(e){let t=[],n=[];if(e.projection.entryFile!==e.entryFile||!ub(e.projection.composition,e.composition)||e.graph.composition&&!ub(e.graph.composition,e.composition))return{roots:[],diagnostics:[fs("composition-mismatch",e.entryFile)]};if(!e.parsedModules.has(e.entryFile))return{roots:[],diagnostics:[fs("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(fs("route-member-not-addressable",e.entryFile));continue}let s=Qw(e.graph,e.entryFile,i.sourceRange);if(s.length!==1){t.push(fs(s.length?"route-root-ambiguous":"route-root-unresolved",e.entryFile));continue}let a=s[0],l=ab({element:a,graph:e.graph,parsedModules:e.parsedModules,ownerNode:{kind:"route-member",key:a.parentKey??`${e.entryFile}#${e.projection.container.placementKey}`}});t.push(...l.diagnostics);for(let c of l.roots){let u=c.ownerMember;n.push({...c,parentStructuralPath:u.parentKey?e.graph.elements.get(u.parentKey)?.identity.structuralPath??null:null})}}let o=rb(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=kc(s,i.callChain.map(l=>l.callLocator.key));o.occurrences.get(s)?.filter(l=>l===a).length!==1&&t.push(fs("render-occurrence-unproven",i.element.sourceFile))}return{roots:qw(n,e.composition,o.occurrences),diagnostics:t}}function qw(e,t,n){let r=e.map(i=>{let s=i.element,a=n.get(s.identity.key)??[],l=i.callChain.map(c=>c.callLocator.key);return{rootKey:Zw("sha256").update(JSON.stringify([t,l,s.identity.key])).digest("hex"),rootRef:{key:s.identity.key,...a.length>1?{instanceIndex:a.indexOf(kc(s.identity.key,l)),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(c=>c.callLocator.key),parentStructuralPath:i.parentStructuralPath,siblingRootKeys:[],siblingIndex:0}}),o=new Map;for(let i of r){let s=lb(i);o.set(s,[...o.get(s)??[],i])}return r.map(i=>{let s=o.get(lb(i))??[i];return{...i,siblingIndex:s.indexOf(i),siblingRootKeys:s.filter(a=>a!==i).map(a=>a.rootKey)}})}function lb(e){return JSON.stringify([e.ownerNode.kind,e.ownerNode.key,e.parentStructuralPath,e.ownerCallKeys])}function Qw(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 ub(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function fs(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 tO,SiteEditSourcePathSchema as fb}from"@vcp-dev/contracts";function Rc(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 l={key:n,writeTarget:i,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,l)}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}),db(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function db(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(l=>l.kind===t)&&(a.constraints.push({kind:t,reason:n}),db(s,t,n,r,o))}}function ps(e){let t=[],n={...e.graph,composition:e.composition},r=ja(Rc(n),n),o=[],i=new Map;for(let a of e.roots){let l=e.graph.elements.get(a.rootRef.key),c=e.graph.elements.get(a.ownerMemberKey),u=e.parsedModules.get(a.sourceFile),d=oO(a,e.graph),f=d?e.parsedModules.get(d):void 0;if(!l||!c||c.sourceFile!==d||!u||!fb.safeParse(a.sourceFile).success||!d||!f||!fb.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=Te(u.source),m=tO.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:iO(a,e),capabilities:nO(l,r),...rO(l,r)});if(!m.success){t.push(kf("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:Te(f.source),ownerSourceContent:f.source,sourceHash:g,sourceContent:u.source,ownerLocator:{kind:"jsx-element",file:c.sourceFile,sourceRange:c.sourceRange,structuralPath:c.identity.structuralPath,componentName:c.componentName},rootLocator:{kind:"jsx-element",file:l.sourceFile,sourceRange:l.sourceRange,structuralPath:l.identity.structuralPath,componentName:l.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 nO(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 rO(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 oO(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 iO(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 _f from"@babel/traverse";import{BlockRenderRefSchema as sO,SiteEditPageBlockPositionSchema as aO,SiteEditPageBlockTargetSchema as cO}from"@vcp-dev/contracts";var lO=typeof _f=="function"?_f:_f.default;function ni(e,t,n,r){if(!cO.safeParse(t).success)return qt("INVALID_PARAMS","Invalid page block target.");if(n!==e.documentVersion)return qt("VERSION_STALE","The page block index is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return qt("INVALID_TARGET","The target belongs to another composition.");let o=e.bindings.get(t.blockKey);return o?r&&(!sO.safeParse(r).success||r.key!==o.descriptor.rootRef.key||r.instanceIndex!==o.descriptor.rootRef.instanceIndex||r.instanceCount!==o.descriptor.rootRef.instanceCount)?qt("INVALID_TARGET","The render occurrence does not match the target."):{ok:!0,binding:o}:qt("INVALID_TARGET","The page block target was not found.")}function Pc(e,t){if(!aO.safeParse(t).success)return qt("INVALID_PARAMS","Invalid page block boundary.");if(t.documentVersion!==e.documentVersion)return qt("VERSION_STALE","The page block boundary is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return qt("INVALID_TARGET","The boundary belongs to another composition.");let n=e.bindings.get(t.anchorBlockKey);if(!n)return qt("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 qt("INVALID_TARGET","A verified sibling binding is unavailable.");let o=r.sort((u,d)=>u.root.siblingIndex-d.root.siblingIndex),i=pb(n);if(!i)return qt("INVALID_TARGET","The operation owner call site is unavailable.");let s=mb(n,i);if(s===void 0)return qt("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||!uO(mb(u,pb(u)),s))return qt("INVALID_TARGET","Siblings do not share one proven source boundary.");let a=o.findIndex(u=>u.blockKey===n.blockKey);if(a<0)return qt("INVALID_TARGET","Anchor order is ambiguous.");let l=t.placement==="before"?o[a-1]:n,c=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:l?.blockKey??null,afterBlockKey:c?.blockKey??null}}}function pb(e){return e.ownerLocator.file===e.ownerFile?e.ownerLocator:null}function mb(e,t){if(!t)return;let n=Ee(t.file,e.ownerSourceContent);if(!n.ok)return;let r=[];if(lO(n.module.ast,{JSXElement(i){let s=Rf(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=Rf(o.node);return i?{kind:"jsx-fragment",file:t.file,sourceRange:i}:void 0}if(o.isJSXElement()){let i=Rf(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 uO(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 Rf(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 qt(e,t){return{ok:!1,code:e,message:t}}import yb from"node:path";import{SiteEditSourcePathSchema as SO}from"@vcp-dev/contracts";import Cc from"node:path";import Pf from"@babel/traverse";import*as Br from"@babel/types";import{SiteEditSourcePathSchema as gb,SiteEditPageBlockTargetSchema as dO}from"@vcp-dev/contracts";var fO=typeof Pf=="function"?Pf:Pf.default;function hb(e){if(!e.operationId)return Et("INVALID_PARAMS","An operationId is required.");if(!dO.safeParse(e.target).success)return Et("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 Et("INVALID_TARGET","The request target does not match its resolved block binding.");if(e.documentVersion!==e.binding.documentVersion)return Et("VERSION_STALE","The resolved block belongs to a stale document version.");if(e.operation==="move-node"||e.operation==="remove-node")return Et("UNSUPPORTED_OPERATION","Move and remove are planned by the structural operation task.");if(!e.node)return Et("INVALID_PARAMS","An insert/replacement node is required.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!gb.safeParse(t).success)return Et("INVALID_TARGET","The exact owner source file is unavailable.");let n=e.files.get(t);if(n===void 0)return Et("INVALID_TARGET","The exact owner source is absent from the fixed file map.");if(Te(n)!==e.binding.ownerSourceHash)return Et("VERSION_STALE","The owner source hash changed after target resolution.");let r=e.files.get(e.binding.descriptor.source.file);if(r===void 0||Te(r)!==e.binding.descriptor.source.contentHash)return Et("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 Et("INVALID_TARGET","The insertion boundary is not in the resolved source owner.");let c=o.placement==="before"?o.afterBlockKey:o.beforeBlockKey;if(c!==e.binding.blockKey&&!e.binding.descriptor.siblingBlockKeys.includes(c??""))return Et("INVALID_TARGET","The boundary anchor is not a verified same-owner sibling.");if(!o.parentLocator)return Et("UNSUPPORTED_OPERATION","A root without a source parent has no safe sibling insertion boundary.")}let i=mO(e.node,t,n,e.files);if(!i.ok)return i;let s=e.operation==="replace-node"?$o({source:n,locator:pO(e.binding),node:{jsx:i.value.jsx}}):Sn({source:n,locator:Cf(o.parentLocator),anchorLocator:Cf(o.anchorLocator),placement:o.placement,node:{jsx:i.value.jsx}});if(!s.ok)return Et("UNSUPPORTED_OPERATION",s.diagnostic.message);let a=s.source;if(i.value.import){let c=vn({source:a,moduleSpecifier:i.value.import.moduleSpecifier,imports:i.value.import.specifiers});if(!c.ok)return Et("UNSUPPORTED_OPERATION",c.diagnostic.message);a=c.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 pO(e){return Cf(e.ownerLocator)}function Cf(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 mO(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}>`}}:Et("INVALID_PARAMS","The native JSX tag is invalid.");if(!e.component)return Et("UNSUPPORTED_OPERATION","A materialized component entry is resolved by the materialization task.");let o=gO(t,e.component.source,r);if(!o)return Et("INVALID_TARGET","The component source is not in the safe fixed file map.");let i=Ee(t,n);if(!i.ok)return Et("UNSUPPORTED_OPERATION",i.diagnostic.message);let s=hO(i.module.ast.program.body,e.component.source,e.component.exportName),a=s??xO(bO(e.component.exportName,o),yO(i.module.ast)),l=EO(e.props??{});if(!l.ok)return l;let c=`<${a}${l.value?` ${l.value}`:""} />`;if(s)return{ok:!0,value:{jsx:c}};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:c,import:{moduleSpecifier:e.component.source,specifiers:[u]}}}}function gO(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?Cc.posix.normalize(Cc.posix.join(Cc.posix.dirname(e),t)):null;return r?(/\.(?:tsx?|jsx?)$/i.test(r)?[r]:[".tsx",".ts",".jsx",".js"].map(i=>`${r}${i}`).concat([".tsx",".ts",".jsx",".js"].map(i=>`${r}/index${i}`))).find(i=>gb.safeParse(i).success&&n.has(i))??null:null}function hO(e,t,n){for(let r of e)if(!(!Br.isImportDeclaration(r)||r.source.value!==t)){for(let o of r.specifiers)if(n==="default"&&Br.isImportDefaultSpecifier(o)||n!=="default"&&Br.isImportSpecifier(o)&&(Br.isIdentifier(o.imported)?o.imported.name:o.imported.value)===n)return o.local.name}return null}function yO(e){let t=new Set;return fO(e,{Program(n){n.scope.crawl(),t=new Set(Object.keys(n.scope.bindings)),n.stop()}}),t}function xO(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function bO(e,t){let r=(e==="default"?Cc.posix.basename(t).replace(/\.(?:tsx?|jsx?)$/i,""):e).replace(/[^A-Za-z0-9_$]/g,""),o=r?r[0].toUpperCase()+r.slice(1):"Component";return/^[A-Za-z_$][\w$]*$/.test(o)?o:"Component"}function EO(e){let t=[];for(let[n,r]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_:.-]*$/.test(n))return Et("INVALID_PARAMS","A component prop name is invalid.");let o;try{o=JSON.stringify(r)}catch{return Et("INVALID_PARAMS","Component props must be JSON serializable.")}if(o===void 0)return Et("INVALID_PARAMS","Component props must be JSON serializable.");t.push(`${n}={${o}}`)}return{ok:!0,value:t.join(" ")}}function Et(e,t){return{ok:!1,code:e,message:t}}function xb(e){if(e.materialization.kind!=="static-prefab-materialization"||!e.materialization.files.some(i=>i.path===e.materialization.entry.path))return Nc("MATERIALIZATION_ENTRY_INVALID","The materialization entry must identify one controlled create-only file.");if(!e.materialization.files.every(i=>i.kind==="create-only"&&SO.safeParse(i.path).success))return Nc("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 Nc("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 Nc("INVALID_TARGET","The exact page-block owner source is missing from the fixed file map.");let n=IO(t,e.materialization.entry.path),r=hb({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 IO(e,t){let n=yb.posix.relative(yb.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function Nc(e,t){return{ok:!1,code:e,message:t}}import{PageTemplateIdSchema as FO}from"@vcp-dev/contracts";import Tz from"node:fs";import Oz from"node:path";var kO=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function ms(e){let t=e.map(r=>OO(r.path)),n=_O(t);return n?t.filter(r=>PO(n,r)).map(r=>({routeId:CO(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function Nf(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=wO(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function _O(e){return e.some(r=>r.startsWith("app/")&&!RO(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function RO(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function PO(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 CO(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(AO).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function NO(e){return e.startsWith("(")&&e.endsWith(")")}function AO(e){return!e||e.startsWith("@")||e.startsWith("_")||NO(e)?null:TO(e)}function TO(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function wO(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function OO(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var gs=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function Qt(e,t={}){throw new gs("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Af(e){return FO.safeParse(e).success||Qt("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function bb(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||Qt("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return Qt("invalid-template-key",{path:e})}return Af(t)!==e&&Qt("noncanonical-template-key",{path:e}),t}function LO(e){let t=Nf(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("(")||DO(r)&&!Eb(r)))&&Qt("invalid-public-route",{routeId:e}),t}function DO(e){return e.includes("[")||e.includes("]")}function Eb(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function Sb(e){return e.some(Eb)}function vb(e,t,n="app"){n!=="app"&&n!=="src/app"&&Qt("invalid-app-root");let r=LO(e),o=Af(t),i=Sb(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(l=>Buffer.byteLength(l,"utf8")>255))&&Qt("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function Ib(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function kb(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===".")&&Qt("invalid-file-path",{path:i}),n.has(i)&&Qt("duplicate-file-path",{path:i}),n.set(i,o)}return n}function Tc(e){let t=kb(e.files),n=ms([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new gs("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(!Ib(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||Qt("candidate-must-be-single-page",{path:i});let a=s[1],l=s[2].split("/"),c=Sb(l),u=c?l[0]:l.pop(),d=c?l.slice(1):l,f=bb(u),g=d.length?`/${d.join("/")}`:"/";vb(g,f,a).templateEntryFile!==i&&Qt("candidate-path-mismatch",{path:i,routeId:g});let p=r.get(g);(!p||!p.startsWith(`${a}/`))&&Qt("canonical-entry-missing",{path:i,routeId:g}),o.push({routeId:g,templateId:f,entryFile:i,canonicalEntryFile:p,appRoot:a})}return o.sort((i,s)=>Ac(i.routeId,s.routeId)||Ac(i.templateId,s.templateId))}function wc(e){let t=kb(e.files),n=Tc({files:t}),r=ms([...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)=>Ac(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:Ac(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function MO(e){let t=Nf(e.selector.routeId),n=wc({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&Qt("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||Qt("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function Ac(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as iF}from"@vcp-dev/contracts";import{parse as ZO}from"@babel/parser";import{parse as Gz}from"@babel/parser";import{FormBlockIdSchema as Zz,FormSpecV1Schema as qz}from"@vcp-dev/contracts";import{posix as Vz}from"node:path";import BO from"@babel/traverse";var Tf=BO,Jz=typeof Tf=="function"?Tf:Tf.default,Xz=Symbol("unknown-member");var hs="components/site/generated/forms",eH=`${hs}/vcp-form-runtime.tsx`,Oc="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",tH=new RegExp(`^${hs}/form-(${Oc})\\.spec\\.ts$`),nH=new RegExp(`^${hs}/form-(${Oc})\\.tsx$`),rH=new RegExp(`^@/${hs}/form-(${Oc})$`),oH=new RegExp(`(?:^|/)${hs}/form-(${Oc})(?:\\.tsx?)?$`);var iH=Symbol("invalid-literal");import{createHash as cH}from"node:crypto";import{posix as uH}from"node:path";import{parse as fH}from"@babel/parser";import{FormSpecV1Schema as mH}from"@vcp-dev/contracts";var gH=Symbol("dynamic");import{parse as jO}from"@babel/parser";function Fc(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var $O=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function _b(e){let t=$O.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 UO(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Rb(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function VO(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function wf(e){let t=e;if(t?.type==="StringLiteral"||t?.type==="NumericLiteral"||t?.type==="BooleanLiteral")return t.value;if(t?.type==="NullLiteral")return null;if(t?.type==="ArrayExpression")return(t.elements??[]).map(wf);if(t?.type==="ObjectExpression"){let n={};for(let r of Fc(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=Rb(r.key);if(!o)throw new Error("unsupported object key");n[o]=wf(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Of(e,t){let n=[],r=_b(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=jO(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(c){return n.push({code:"page-seo.parse-failed",message:c instanceof Error?c.message:String(c)}),{found:!1,seo:null,diagnostics:n}}let i;for(let c of Fc(o.program.body)){let u=c.type==="ExportNamedDeclaration"?c.declaration:c;if(u?.type==="VariableDeclaration")for(let d of Fc(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=VO(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 c of Fc(s.properties)){if(c.type!=="ObjectProperty"||c.computed)continue;let u=Rb(c.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=UO(c.value);if(d===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static string; skipped`});continue}a[u]=d;continue}try{let d=wf(c.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 l=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`}),l=a.path),{found:!0,seo:{path:l,...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 KO}from"@babel/parser";var Pb=["page","anchor","external","email","phone","group","file"],JO=["link","cta"],Nb=["description","badge","iconKey"],Ff=["label","targetType","href","role","openInNewTab","nofollow","children",...Nb],XO=new Set(Ff);function xs(e){return Array.isArray(e)?e:[]}function ys(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function zO(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Cb(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Lf(e){let t=[],n;try{n=KO(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 xs(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of xs(s.declarations)){let l=a.id;l?.type==="Identifier"&&l.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 xs(r.elements).forEach((i,s)=>{let a=Ab(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function Ab(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 c of xs(e.properties)){if(c.type!=="ObjectProperty"||c.computed)continue;let u=zO(c.key);u&&(r[u]=c.value)}let o=ys(r.label),i=ys(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!Pb.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${Pb.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 c of Nb){if(r[c]===void 0)continue;let u=ys(r[c]);u!==void 0?s[c]=u:n.push({severity:"warning",path:`${t}.${c}`,message:`${c} 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 c of Object.keys(r))XO.has(c)||c==="group"||c==="icon"||n.push({severity:"warning",code:"unknown-field",path:`${t}.${c}`,message:`unsupported field \`${c}\` ignored; NAV_ITEMS only carries ${Ff.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 c=[];xs(r.children.elements).forEach((u,d)=>{let f=Ab(u,`${t}.children[${d}]`,n);f&&c.push(f)}),s.children=c}if(i==="group")return s.children?s:(n.push({severity:"fatal",path:`${t}.children`,message:"group item requires children"}),null);let a=ys(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 l=ys(r.role);if(l!==void 0&&(JO.includes(l)?s.role=l:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let c=Cb(r.openInNewTab);c!==void 0?s.openInNewTab=c:n.push({severity:"warning",path:`${t}.openInNewTab`,message:"openInNewTab ignored: not a static boolean"})}if(r.nofollow!==void 0){let c=Cb(r.nofollow);c!==void 0?s.nofollow=c:n.push({severity:"warning",path:`${t}.nofollow`,message:"nofollow ignored: not a static boolean"})}return s}import{parse as HO}from"@babel/parser";function bs(e){return Array.isArray(e)?e:[]}function Tb(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function WO(e){let t;try{t=HO(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of bs(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of bs(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=Tb(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 Df(e,t){let n=wb(t);if(!n)return{status:"unsupported",source:e};let r=WO(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Lf(e).diagnostics.some(({severity:c})=>c==="fatal"))return{status:"unsupported",source:e};let s=[],a=c=>{let u=bs(c.elements);for(let[d,f]of u.entries()){if(YO(f,n)){let m=u[d+1],p=u[d-1],h=f.start,x=f.end;if(typeof h!="number"||typeof x!="number")continue;if(m&&typeof m.start=="number")s.push({start:h,end:m.start});else if(p&&typeof p.end=="number")s.push({start:p.end,end:x});else{let E=/^\s*,/.exec(e.slice(x));s.push({start:h,end:E?x+E[0].length:x})}continue}let g=GO(f);g&&a(g)}};if(a(o),s.length===0)return{status:"not_found",source:e};let l=e;for(let c of s.sort((u,d)=>d.start-u.start))l=l.slice(0,c.start)+l.slice(c.end);return{status:"removed",source:l,removedCount:s.length}}function GO(e){if(e.type==="ObjectExpression")for(let t of bs(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return Tb(t.value)}}function wb(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function YO(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of bs(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"&&wb(n??"")===t}import{estimateNavLabelWidth as _H}from"@vcp-dev/contracts";import{parse as CH}from"@babel/parser";function Cn(e,t){let n;try{n=ZO(e,{sourceType:"module",sourceFilename:t.filePath,plugins:["jsx","typescript"]})}catch(C){let N=C.loc;return{form_codes:[],components:[],uncertain_components:[],rendered_component_openings:[],renders_native_form:!1,diagnostics:[{code:"rendered-module.parse-failed",message:C instanceof Error?C.message:"Rendered module failed Babel parsing.",file_path:t.filePath??"",line:N?.line??1}]}}let r=n.program,o=un(r?.body),i=new Map,s=new Map,a=new Map,l=new Map,c=C=>{if(C?.type==="FunctionDeclaration"){let N=C.id;N?.type==="Identifier"&&typeof N.name=="string"&&s.set(N.name,C);return}if(C?.type==="VariableDeclaration")for(let N of un(C.declarations)){let w=N.id,L=N.init;w?.type==="Identifier"&&typeof w.name=="string"&&L&&(jr(L)?s.set(w.name,L):L.type==="Identifier"&&typeof L.name=="string"&&a.set(w.name,L.name))}};for(let C of o){if(C.type==="ImportDeclaration"){let N=C.source?.value;if(typeof N!="string")continue;for(let w of un(C.specifiers)){let L=w.local;if(!(L?.type!=="Identifier"||typeof L.name!="string")){if(w.type==="ImportDefaultSpecifier")i.set(L.name,{source:N,exportName:"default"});else if(w.type==="ImportNamespaceSpecifier")i.set(L.name,{source:N,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(L.name,{source:N,exportName:U})}}}continue}C.type==="ExportNamedDeclaration"?c(C.declaration):c(C)}for(let C of o){if(C.type==="ExportDefaultDeclaration"){let L=C.declaration;L&&jr(L)?l.set("default",L):L?.type==="Identifier"&&typeof L.name=="string"&&l.set("default",L.name);continue}if(C.type!=="ExportNamedDeclaration")continue;let N=C.declaration;if(N?.type==="FunctionDeclaration"){let L=N.id;L?.type==="Identifier"&&typeof L.name=="string"&&l.set(L.name,L.name)}else if(N?.type==="VariableDeclaration")for(let L of un(N.declarations)){let D=L.id;D?.type==="Identifier"&&typeof D.name=="string"&&l.set(D.name,D.name)}let w=C.source?.value;for(let L of un(C.specifiers)){let D=Lb(L.local),U=Lb(L.exported);if(!(!D||!U))if(typeof w=="string"){let M=`#re-export:${U}`;i.set(M,{source:w,exportName:D}),l.set(U,M)}else l.set(U,D)}}let u=new Set,d=[],f=new Set,g=[],m=new Set,p=[],h=new Map,x=!1,E=[],b=new Map,S=new Map,v=(C,N="rendered")=>{let w=Fb(C,i);if(!w)return!1;let L=`${w.source}\0${w.exportName}`;if(N==="uncertain")return!f.has(L)&&!m.has(L)&&(m.add(L),g.push({source:w.source,export_name:w.exportName})),!0;if(!f.has(L)&&(f.add(L),d.push({source:w.source,export_name:w.exportName}),m.delete(L))){let D=g.findIndex(U=>U.source===w.source&&U.export_name===w.exportName);D>=0&&g.splice(D,1)}return!0},P=(C,N="rendered",w=[])=>{let L=`${N}\0${Bf(w)}`,D=b.get(C)??new Set,U=S.get(C)??new Set;if(D.has(L)||U.has(N))return;D.add(L),b.set(C,D),U.add(N),S.set(C,U);let M=new Map(s),G=new Map,K=[],ge=(xe,st=!1)=>{if(Lc(xe)){if(!st&&jr(xe)){if(xe.type==="FunctionDeclaration"){let Je=xe.id;Je?.type==="Identifier"&&typeof Je.name=="string"&&M.set(Je.name,xe)}return}if(xe.type==="VariableDeclarator"){let Je=xe.id,pe=xe.init;Je?.type==="Identifier"&&typeof Je.name=="string"&&pe&&(jr(pe)?M.set(Je.name,pe):G.set(Je.name,pe))}else if(xe.type==="ReturnStatement"){let Je=xe.argument;Je&&K.push(Je)}if(xe.type==="CallExpression"){let Je=xe.callee;if(Je?.type==="Import"&&E.push({code:"rendered-module.dynamic-import",message:"Rendered component graph must use static imports.",file_path:t.filePath??"",line:xe.loc?.start.line??1}),Es(Je)==="cms.forms.getConfig"){let pe=un(xe.arguments)[0];pe?.type==="StringLiteral"&&typeof pe.value=="string"&&pe.value.trim()?N==="rendered"?u.add(pe.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:xe.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:xe.loc?.start.line??1})}}for(let[Je,pe]of Object.entries(xe))if(Je!=="loc")if(Array.isArray(pe))for(let $ of pe)ge($);else ge(pe)}};ge(C,!0);let oe=new Set,Me=new Set,He=(xe,st=N,Je=w)=>{if(!(!Lc(xe)||jr(xe))){if(xe.type==="Identifier"&&typeof xe.name=="string"){let pe=G.get(xe.name),$=`${st}\0${xe.name}\0${Bf(Je)}`;pe&&!oe.has($)&&!Me.has(xe.name)?(oe.add($),Me.add(xe.name),He(pe,st,Je),Me.delete(xe.name)):v(xe.name,st);return}if(xe.type==="CallExpression"){let pe=xe.callee,$=un(xe.arguments),ae=Es(pe),he=pe?.type==="Identifier"&&typeof pe.name=="string"?i.get(pe.name):void 0;if(st==="rendered"&&(ae==="createElement"||ae.endsWith(".createElement")||he?.source==="react"&&he.exportName==="createElement")&&$[0]?.type==="StringLiteral"&&$[0].value==="form"&&(x=!0),pe?.type==="Identifier"&&typeof pe.name=="string"){let Le=M.get(pe.name);if(Le){P(Le,st,Je);return}}if(pe&&jr(pe)){P(pe,st,Je);return}if(eF(pe)){for(let Le of $)if(jr(Le))P(Le,st,Je);else if(Le.type==="Identifier"&&typeof Le.name=="string"){let kt=M.get(Le.name);kt&&P(kt,st,Je)}return}for(let Le of $)tF(Le)&&E.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a JSX-producing call argument is rendered.",file_path:t.filePath??"",line:Le.loc?.start.line??1});return}if(xe.type==="JSXElement"){let pe=xe.openingElement,$=pe?Ob(Je,qO(pe)):Je;He(pe,st,$);for(let ae of un(xe.children))He(ae,st,$);return}if(xe.type==="JSXOpeningElement"){let pe=Dc(xe.name);st==="rendered"&&pe==="form"&&(x=!0);let $=pe?Fb(pe,i):void 0;if(st==="rendered"&&$&&typeof xe.start=="number"){let ae=`${$.source}\0${$.exportName}\0${xe.start}`,he=h.get(ae);if(!he){let Le=nF(xe).get("formBlockId");he={source:$.source,export_name:$.exportName,start_offset:xe.start,...typeof Le=="string"?{static_form_block_id:Le}:{}},h.set(ae,he),p.push(he)}Je.length>0&&(he.static_render_blockers=Ob(he.static_render_blockers??[],Je))}if(pe&&!v(pe,st)){let ae=M.get(pe);ae?P(ae,st,Je):G.has(pe)?He(G.get(pe),st,Je):QO(pe)||/^[A-Z]/.test(pe)&&E.push({code:"rendered-module.dynamic-import",message:`Unable to resolve rendered component ${pe} from a static import.`,file_path:t.filePath??"",line:xe.loc?.start.line??1})}for(let ae of un(xe.attributes))He(ae,"uncertain",Je);return}if(xe.type==="JSXAttribute"){let pe=xe.value,$=pe?.type==="JSXExpressionContainer"?pe.expression:pe;$&&jr($)?P($,"uncertain",Je):He($,"uncertain",Je);return}for(let[pe,$]of Object.entries(xe))if(!(pe==="loc"||pe==="closingElement"))if(Array.isArray($))for(let ae of $)He(ae,st,Je);else He($,st,Je)}},pt=C.body;pt&&pt.type!=="BlockStatement"&&K.push(pt);for(let xe of K)He(xe);U.delete(N)},I=l.get(t.exportName);if(typeof I=="string"){let C=I,N=new Set;for(;a.has(C)&&!N.has(C);)N.add(C),C=a.get(C);if(!v(C)){let w=s.get(C);w?P(w):E.push(Db(t))}}else I?P(I):E.push(Db(t));return{form_codes:[...u],components:d,uncertain_components:g,rendered_component_openings:p,renders_native_form:x,diagnostics:E}}function Bf(e){return e.map(t=>`${t.start_offset}:${t.reason}`).join("|")}function Ob(e,t){return[...new Map([...e,...t].map(r=>[Bf([r]),r])).values()]}function qO(e){let t=new Map;for(let a of un(e.attributes)){if(a.type==="JSXSpreadAttribute"){t.clear();continue}let l=Mb(a.name);if(!l)continue;let c=a.value;t.set(l,c?.type==="JSXExpressionContainer"?c.expression:c)}let n=Dc(e.name)??"unknown",r=[],o=a=>{r.push({element_name:n,line:e.loc?.start.line??1,start_offset:oF(e.start),reason:a})};for(let a of["hidden","inert","aria-hidden","disabled"]){if(!t.has(a)||a==="disabled"&&n!=="fieldset")continue;let l=Mf(t.get(a));(l===!0||(a==="aria-hidden"?l==="true":typeof l=="string"))&&o(a)}let i=t.get("style");if(i?.type==="ObjectExpression"){let a=new Map;for(let c of un(i.properties)){let u=c.key,d=!c.computed&&u?.type==="Identifier"?u.name:u?.type==="StringLiteral"?u.value:void 0;c.type!=="ObjectProperty"||typeof d!="string"?a.clear():a.set(d,Mf(c.value))}a.get("display")==="none"&&o("style.display=none"),a.get("visibility")==="hidden"&&o("style.visibility=hidden");let l=a.get("opacity");(l===0||typeof l=="string"&&l.trim()==="0")&&o("style.opacity=0")}let s=Mf(t.get("className"));if(typeof s=="string"){let a=s.split(/\s+/).filter(Boolean),c={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(c))a.includes(u)&&!a.some(f=>d.has(f.split(":").at(-1)))&&o(`className=${u}`)}return r}function Mf(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"&&un(e.expressions).length===0)return un(e.quasis)[0]?.value?.cooked}}function Fb(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 QO(e){return e.endsWith(".Provider")||e.endsWith(".Consumer")}function jr(e){return e?.type==="FunctionDeclaration"||e?.type==="FunctionExpression"||e?.type==="ArrowFunctionExpression"}function eF(e){let t=Es(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 tF(e){let t=!1;return jf(e,n=>{if(!t){if(n.type==="JSXOpeningElement"){t=!0;return}n.type==="CallExpression"&&Es(n.callee)==="cms.forms.getConfig"&&(t=!0)}}),t}function Lb(e){return e?.type==="Identifier"&&typeof e.name=="string"?e.name:e?.type==="StringLiteral"&&typeof e.value=="string"?e.value:""}function Db(e){return{code:"rendered-module.unresolved-export",message:`Unable to resolve rendered export ${e.exportName}.`,file_path:e.filePath??"",line:1}}function Es(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=Es(e.object),n=e.property;return!t||n?.type!=="Identifier"||typeof n.name!="string"?"":`${t}.${n.name}`}function nF(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=Mb(o.name);i&&t.set(i,rF(o.value))}return t}function rF(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 Mb(e){let t=e;if(t?.type==="JSXIdentifier")return typeof t.name=="string"?t.name:void 0}function oF(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function jf(e,t){if(Lc(e)){t(e);for(let[n,r]of Object.entries(e))if(n!=="loc"){if(Array.isArray(r)){for(let o of r)jf(o,t);continue}jf(r,t)}}}function Lc(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function Dc(e){let t=e;if(!t)return"";if(t.type==="JSXIdentifier")return typeof t.name=="string"?t.name:"";if(t.type==="JSXMemberExpression"){let n=Dc(t.object),r=Dc(t.property);return n&&r?`${n}.${r}`:r||n}return""}function un(e){return Array.isArray(e)?e.filter(t=>Lc(t)):[]}var sF="components/site/generated/",Ss=[".tsx",".ts",".jsx",".js"];function Bb(e){if(e.expectedUrlPath===iF)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(ms(Object.keys(e.files).map(p=>({path:p}))).map(p=>p.entryFile)),n=Object.entries(e.files).filter(([p,h])=>{let x=p.replace(/\\/g,"/");if(!t.has(x))return!1;let E=Of(h,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 p=Tc({files:new Map(Object.entries(e.files))});for(let h of p)h.canonicalEntryFile===r&&o.add(h.entryFile)}catch(p){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:p instanceof Error?p.message:"Invalid page template source."}}let i=aF(e.files);if(!i.ok)return i.error;let s=i.graph,a=dF(o,s),l=fF(o,a,s),c=[...a].filter(p=>!l.has(p)).sort((p,h)=>p.localeCompare(h)),u=[...o,...[...l].sort((p,h)=>p.localeCompare(h))],d=new Set(u),f=u.map(p=>({operation:"delete",file:p})),g=[],m=[];for(let[p,h]of Object.entries(e.files))if(!d.has(p)){if(h.includes("NAV_ITEMS")){let x=Df(h,e.expectedUrlPath);x.status==="removed"?(f.push({operation:"upsert",file:p,content:x.source}),g.push(p)):x.status==="unsupported"&&m.push(`unsupported_navigation:${p}`)}h.includes(e.expectedUrlPath)&&!h.includes("NAV_ITEMS")&&m.push(`preserved_link:${p}`)}return{ok:!0,edits:f,deletedFiles:u,updatedFiles:g,preservedSharedFiles:c,warnings:m}}function aF(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")||!cF(r))continue;let s=Ee(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:l}of s.module.imports){if(lF(l))continue;let c=Kn(r,l),u=uF(c,t);if(!u)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${l} (import-not-found).`}};a.add(u)}n.set(r,a)}return{ok:!0,graph:n}}function cF(e){let t=e.toLowerCase();return Ss.some(n=>t.endsWith(n))}function lF(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!Ss.some(n=>e.endsWith(n)))}function uF(e,t){let n=e.replace(/\\/g,"/");return(Ss.some(o=>n.endsWith(o))?[n]:[...Ss.map(o=>`${n}${o}`),...Ss.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function dF(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(sF)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function fF(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,l])=>!e.has(a)&&!r.has(a)&&l.has(i))&&(r.delete(i),o=!0)}return r}import*as jE from"@babel/parser";import*as Ue from"@babel/types";import*as el from"node:path";import*as Ye from"@babel/types";function jb(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 Yn(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Eo(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(Ye.isObjectPattern(n)||Ye.isArrayPattern(n))return Eo(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(mF(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Eo(e,t,n=!1){return Ye.isIdentifier(e)?e.name===t&&n:Ye.isObjectPattern(e)?e.properties.some(r=>Ye.isObjectProperty(r)?Eo(r.value,t,n):Eo(r.argument,t,n)):Ye.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=Ye.isRestElement(r)?r.argument:r;return Eo(o,t,n)}):Ye.isAssignmentPattern(e)?Eo(e.left,t,!0):Ye.isRestElement(e)?Eo(e.argument,t,n):!1}function ri(e,t){if(e.path.isObjectPattern()){if(t){let r=Dn(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Yn(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Yn(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=$b(r),i=!1,s=o?o.initBinding&&$f(o.initBinding)?(i=Yn(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let l=ri(o.initBinding,{kind:"identifier",expression:o.initBinding.identifier.name,base:o.initBinding.identifier.name,path:[]});return i=l?.hasDefault??!1,l?[{kind:"property",name:l.propName},...l.remainingPath,...o.initPathPrefix]:null})():null:null,a=Dn(e.path.node.id,e.identifier.name);if(s&&a){let l=[...s,...a],[c,...u]=l;return!c||c.kind!=="property"?null:{propName:c.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||Yn(e)}}}}let n=yF(e);if(n){let r=pF(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||Yn(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=gF(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Yn(e)}}let i=vs(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Yn(e)}:null}if($f(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Yn(e)}}return null}function pF(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=$b(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,l=$f(i)?(a=Yn(i),[...s]):(()=>{let u=ri(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(!l)return null;let c=Dn(n.node.id,t.identifier.name);return c?{path:[...l,...c],hasDefault:a||Yn(t)}:null}function $b(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=xF(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function $f(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function mF(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function gF(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=Dn(i.node,t);if(a)return a}return null}function Ub(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let l=Mc(a,e.identifier.name);if(l&&(!n||l.propName===n))return{propName:l.propName,componentName:t,expressionPath:l.expressionPath,displayPath:`${t}.${l.propName}.default`}}}if(e.path.isObjectPattern())for(let a of e.path.get("properties")){if(!a.isObjectProperty())continue;let l=vs(a.node);if(!l||n&&l!==n)continue;let c=a.get("value");if(!c.isAssignmentPattern())continue;let u=c.get("right");if(u.isExpression())return{propName:l,componentName:t,expressionPath:u,displayPath:`${t}.${l}.default`}}let r=hF(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=vs(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 Mc(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=vs(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&Dn(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=Mc(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=Mc(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=Mc(r,t);if(o)return o}}return null}function Dn(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=vs(r);if(!o)continue;let i=Dn(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(Ye.isRestElement(r)){let o=Dn(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=Dn(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return Ye.isAssignmentPattern(e)?Dn(e.left,t,n):null}function hF(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function yF(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 vs(e){return e.computed?null:Ye.isIdentifier(e.key)?e.key.name:Ye.isStringLiteral(e.key)?e.key.value:null}function xF(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 Hb from"@babel/parser";import Kf from"@babel/traverse";import*as oi from"@babel/types";import*as Oe from"@babel/types";var Vb=new WeakMap;function $c(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Bc(n,t):null}if(e.isMemberExpression()){let n=kF(e.node),r=bF(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Bc(o,[...r,...t]):null}return e.isAwaitExpression()||Vf(e.node)?$r(RF(e.node),t,"awaited or fetched expression"):null}function bF(e){let t=[],n=e;for(;Oe.isMemberExpression(n);){if(n.computed)if(Oe.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Oe.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Oe.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Oe.isIdentifier(n)?t:null}function Bc(e,t=[],n){let r=EF(e,t);if(r)return r;let o=SF(e,t,n);if(o)return o;let i=vF(e,t,n);return i||null}function ks(e){return e?.kind==="api-source"}function EF(e,t){if(e.path.isVariableDeclarator()&&Oe.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Uf(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return $r(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&Oe.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(l=>Oe.isObjectProperty(l)&&Xb(l)==="data"&&Is(l.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Uf(a.node))return $r(e.identifier.name,t,"query hook data binding")}let n=IF(e);if(!n||Xb(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()||!Uf(i.node)?null:$r(e.identifier.name,t,"query hook data binding")}function SF(e,t,n){if(e.path.isVariableDeclarator()&&Oe.isArrayPattern(e.path.node.id)){let l=e.path.get("init");if(!l?.isCallExpression()||!Jb(l.node))return null;let[c,u]=e.path.node.id.elements;return!Oe.isIdentifier(c)||c.name!==e.identifier.name||!Oe.isIdentifier(u)?null:Kb(e,u.name,n)?$r(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()||!Jb(i.node)||r.node.elements.findIndex(l=>l===e.path.node)!==0)return null;let a=r.node.elements[1];return Oe.isIdentifier(a)&&Kb(e,a.name,n)?$r(e.identifier.name,t,"state setter is updated by API data"):null}function vF(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()?$r(e.identifier.name,t,"awaited binding result"):Vf(o.node,n)?$r(e.identifier.name,t,"fetch-backed binding result"):null:null}function IF(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isObjectProperty()?t:t?.isAssignmentPattern()&&t.parentPath?.isObjectProperty()?t.parentPath:null}function Is(e,t){return Oe.isIdentifier(e)?e.name===t:Oe.isAssignmentPattern(e)?Is(e.left,t):Oe.isObjectPattern(e)?e.properties.some(n=>Oe.isObjectProperty(n)?Is(n.value,t):Is(n.argument,t)):Oe.isArrayPattern(e)?e.elements.some(n=>!!n&&Is(Oe.isRestElement(n)?n.argument:n,t)):!1}function Kb(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let l=Vb.get(n);l||(l=new WeakMap,Vb.set(n,l)),s=l.get(i.node),s||(s=new Map,l.set(i.node,s));let c=s.get(t);if(c!==void 0)return c}i.traverse({CallExpression(l){Vf(l.node)&&(r=!0),(_F(l.node.callee,t)||l.node.arguments.some(c=>Oe.isIdentifier(c)&&c.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function Uf(e){let t=Uc(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Jb(e){return Uc(e.callee)==="useState"}function Vf(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=jc(e,o=>Oe.isCallExpression(o)&&Uc(o.callee)==="fetch");return t?.set(e,r),r}function kF(e){let t=e;for(;Oe.isMemberExpression(t);)t=t.object;return Oe.isIdentifier(t)?t.name:null}function Xb(e){return e.computed?null:Oe.isIdentifier(e.key)?e.key.name:Oe.isStringLiteral(e.key)?e.key.value:null}function Uc(e){return Oe.isIdentifier(e)?e.name:Oe.isMemberExpression(e)&&Oe.isIdentifier(e.property)?e.property.name:null}function _F(e,t){return jc(e,n=>Oe.isIdentifier(n)&&n.name===t)}function jc(e,t){if(t(e))return!0;let n=Oe.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(Oe.isNode(i)&&jc(i,t))return!0;continue}if(Oe.isNode(o)&&jc(o,t))return!0}return!1}function RF(e){return Oe.isIdentifier(e)?e.name:Oe.isCallExpression(e)?Uc(e.callee)??"api":Oe.isAwaitExpression(e)?"awaited-api":"api"}function $r(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:PF(e,t),reason:n}}function PF(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Wb=typeof Kf=="function"?Kf:Kf.default;function Gb(e,t){let n=Zb(e);if(!n)return{allowed:!0};let r=!1;return Wb(n,{CallExpression(o){if(!qb(o.node,t.sourceRange)||!CF(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||ks($c(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Yb(e,t){let n=Zb(e);if(!n)return{allowed:!0};let r=!1;return Wb(n,{JSXExpressionContainer(o){qb(o.node,t.sourceRange)&&(oi.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 Zb(e){try{return Hb.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function CF(e){let t=e.callee;return oi.isMemberExpression(t)&&oi.isIdentifier(t.property)&&t.property.name==="map"}function qb(e,t){let n=e.loc;return n?zb({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&zb({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function zb(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 Qb from"@babel/parser";import Jf from"@babel/traverse";import*as lt from"@babel/types";import*as ii from"node:path";var Mn=typeof Jf=="function"?Jf:Jf.default;function Ot(e){try{return Qb.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Xf(e){return e.computed?lt.isStringLiteral(e.key)||lt.isNumericLiteral(e.key)?String(e.key.value):null:NF(e.key)}function NF(e){return lt.isIdentifier(e)?e.name:lt.isStringLiteral(e)||lt.isNumericLiteral(e)?String(e.value):null}function So(e){return lt.isParenthesizedExpression(e)||lt.isTSAsExpression(e)||lt.isTSSatisfiesExpression(e)||lt.isTSNonNullExpression(e)||lt.isTSTypeAssertion(e)?So(e.expression):lt.isExpression(e)?e:null}function zf(e){if(lt.isIdentifier(e))return[e.name];if((lt.isMemberExpression(e)||lt.isOptionalMemberExpression(e))&&!e.computed&<.isIdentifier(e.property)){let t=So(e.object),n=t?zf(t):null;return n?[...n,e.property.name]:null}return null}function vo(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?ii.normalize(ii.join(ii.dirname(e),t)).replace(/\\/g,"/"):t}function dn(e,t){return Vc(e)===Vc(t)}function Vc(e){let t=si(e);return t.endsWith("/index")?t.slice(0,-6):t}function si(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function nE(e,t,n){let r=sE(e,t);if(aE(e,r),cE(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 Mn(e,{JSXElement(s){fE(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Kc(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 rE(e,t){let n=new Map,r=i=>{let s=ai(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 AF(i,n))o=r(s)||o}return[...n.values()]}function AF(e,t){let n=[],r=TF(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=_s(s.namespace,o.declaration.name,"default");a&&n.push({file:e.file,namespace:a,exportName:s.exportName});continue}n.push({file:e.file,exportName:"default"})}continue}if(re.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=vo(e.file,o.source.value);for(let s of o.specifiers){if(re.isExportNamespaceSpecifier(s)){let c=Ur(s.exported);for(let u of t.values())dn(u.file,i)&&n.push({file:e.file,namespace:Hf(c,u.namespace),exportName:u.exportName});continue}if(!re.isExportSpecifier(s))continue;let a=Ur(s.local),l=[...t.values()].filter(c=>dn(c.file,i)&&Io(c.namespace,a));if(l.length>0){let c=Ur(s.exported);for(let u of l){let d=_s(u.namespace,a,c);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(ai({file:i,exportName:a}))&&n.push({file:e.file,exportName:Ur(s.exported)})}continue}if(re.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!re.isExportSpecifier(i))continue;let s=Ur(i.local),a=r.get(s)??[];if(a.length>0){let l=Ur(i.exported);n.push({file:e.file,exportName:l});for(let c of a){let u=_s(c.namespace,s,l);u&&n.push({file:e.file,namespace:u,exportName:c.exportName})}}}continue}if(re.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=vo(e.file,o.source.value),s=o.exported;if(s){let a=Ur(s);for(let l of t.values())dn(l.file,i)&&n.push({file:e.file,namespace:Hf(a,l.namespace),exportName:l.exportName});continue}for(let a of t.values())dn(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Hf(e,t){return t?`${e}.${t}`:e}function Io(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function _s(e,t,n){return!Io(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function TF(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=vo(e.file,i.source.value);for(let a of i.specifiers){if(re.isImportDefaultSpecifier(a)){let l=t.get(ai({file:s,exportName:"default"}));l&&r(a.local.name,l);let c=[...t.values()].filter(u=>dn(u.file,s)&&Io(u.namespace,"default"));for(let u of c){let d=_s(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(re.isImportSpecifier(a)){let l=Ur(a.imported),c=[...t.values()].filter(d=>dn(d.file,s)&&Io(d.namespace,l));for(let d of c)r(a.local.name,d);let u=t.get(ai({file:s,exportName:l}));u&&r(a.local.name,u);continue}if(re.isImportNamespaceSpecifier(a))for(let l of t.values())dn(l.file,s)&&r(a.local.name,{...l,namespace:Hf(a.local.name,l.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=So(s.init);if(!a||!re.isIdentifier(a))continue;let l=n.get(a.name)??[];if(l.length===0)continue;let c=n.get(s.id.name)??[],u=new Set(c.map(ai));for(let d of l){let f=_s(d.namespace,a.name,s.id.name),g=f?{...d,namespace:f}:d,m=ai(g);u.has(m)||(r(s.id.name,g),u.add(m),o=!0)}}}return n}function ai(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Vc(e.file)}#${t}`}function Ur(e){return re.isIdentifier(e)?e.name:e.value}function oE(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 Gf(e){let t=wF(e),n=[],r=cE(e.ast,t);return Mn(e.ast,{JSXElement(o){dn(e.file,e.sourceFile)&&Kc(o)===e.sourceComponent||fE(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function iE(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function sE(e,t){let n=iE();return Mn(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function wF(e){let t=iE();return dn(e.file,e.sourceFile)&&OF(t,sE(e.ast,e.sourceComponent)),Mn(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=vo(e.file,o),s=e.componentIdentities.filter(a=>dn(a.file,i));if(s.length!==0)for(let a of r.specifiers){let l=n.scope.getBinding(a.local.name);if(l){if(re.isImportDefaultSpecifier(a)&&s.some(c=>c.exportName==="default")&&t.localBindings.add(l),re.isImportDefaultSpecifier(a)){let c=s.filter(u=>Io(u.namespace,"default"));if(c.length>0){let u=t.namespaceMembers.get(l)??new Set;for(let d of c){let f=tE(d,"default");f&&u.add(f)}t.namespaceMembers.set(l,u)}continue}if(re.isImportSpecifier(a)){let c=re.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>Io(d.namespace,c));if(u.length>0){let d=t.namespaceMembers.get(l)??new Set;for(let f of u){let g=tE(f,c);g&&d.add(g)}t.namespaceMembers.set(l,d);continue}s.some(d=>!d.namespace&&d.exportName===c)&&t.localBindings.add(l);continue}if(re.isImportNamespaceSpecifier(a))for(let c of s){let u=c.namespace?`${c.namespace}.${c.exportName}`:c.exportName,d=t.namespaceMembers.get(l)??new Set;d.add(u),t.namespaceMembers.set(l,d)}}}}}),aE(e.ast,t),t}function OF(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 aE(e,t){Mn(e,{VariableDeclarator(n){if(!n.node.init)return;let r=So(n.node.init);if(r){if(re.isIdentifier(n.node.id)){let o=ko(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Wf(t,i,o);return}if(re.isObjectPattern(n.node.id)){let o=ko(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&dE(n.node.id,o.namespaceMembers,t,n)}}}})}function cE(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Mn(e,{ReferencedIdentifier(r){if(n){r.stop();return}FF(r)||!r.isIdentifier()||!lE(r,t)||LF(r,t)||DF(r)||(n=!0,r.stop())}}),n}function FF(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 lE(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)&&ko(r.node,t,r)?r:null}function LF(e,t){let n=e.findParent(l=>l.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!eE(e,r))return!1;let o=lE(e,t);if(!o)return!1;if(So(r.node)===o.node)return!!ko(r.node,t,r);let s=e.findParent(l=>l.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&eE(e,a)&&!!ko(a.node,t,a)}function DF(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function eE(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function ko(e,t,n){let r=So(e);if(!r)return null;if(re.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let l=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:l?{local:!1,namespaceMembers:new Set(l),unsupported:!1}:null}if(re.isObjectExpression(r))return MF(r,t,n);let o=zf(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?uE(s,o.slice(1).join(".")):null}function MF(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!re.isObjectProperty(i))continue;let s=Xf(i);if(!s||!re.isExpression(i.value)){re.isExpression(i.value)&&(o||=ko(i.value,t,n)!==null);continue}let a=ko(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let l of a.namespaceMembers)r.add(`${s}.${l}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function uE(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 Wf(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 dE(e,t,n,r){for(let o of e.properties){if(re.isRestElement(o)){if(re.isIdentifier(o.argument)){let l=r.scope.getBinding(o.argument.name);l&&Wf(n,l,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!re.isObjectProperty(o))continue;let i=Xf(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=uE(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 l=r.scope.getBinding(a.name);l&&Wf(n,l,s);continue}if(re.isObjectPattern(a)&&s.namespaceMembers.size>0){dE(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function tE(e,t){if(!Io(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 fE(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=pE(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 pE(e){if(re.isJSXIdentifier(e))return[e.name];if(re.isJSXMemberExpression(e)){let t=pE(e.object);return t?[...t,e.property.name]:null}return null}function Kc(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 mE(e,t){let n=Ot(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Gf({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 Ge(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 Zn(e,t){let n=ze(e);return!!(n&&fn(t,n))}function fn(e,t){return t.start>=e.start&&t.end<=e.end}function Nn(e,t){let n=Ne(e,Ge(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Jc(e,t)}function ci(e,t){let n=ze(t);return n?e.slice(n.start,n.end):""}function gE(e,t){return e.start===t.start&&e.end===t.end}function Jc(e,t){let n=null;return Mn(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 Xc(e,t){return Yf(e,t).length>0}function zc(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()&&!BF(o,n,r)))return!0;o=o.parentPath}return!1}function BF(e,t,n){let r=ze(e.node.consequent);if(r&&fn(r,t)&&!fn(r,n))return!1;let o=e.node.alternate?ze(e.node.alternate):null;return!(o&&fn(o,t)&&!fn(o,n))}function Yf(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()&&Zf(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 Zf(e){return e==="&&"||e==="||"||e==="??"}function hE(e,t){let n=ze(e.consequent);if(n&&fn(n,t))return n;let r=ze(e.alternate);return r&&fn(r,t)?r:null}function yE(e){if(!e.knownSourceFiles)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without project-wide source visibility"};if(!e.routeEntryFiles)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without registered route visibility"};let t=new Set(e.knownSourceFiles.map(a=>si(a.file)));if(!t.has(si(e.sourceFile))||!t.has(si(e.targetFile)))return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without source and target file visibility"};for(let a of e.routeEntryFiles)if(!t.has(si(a)))return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component until all registered route entries are loaded"};let n=oE(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 l=Ot(a.content);if(!l)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:l})}let o=rE(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let l=Gf({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(l.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(...l.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!dn(s.file,e.targetFile)||Kc(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 JF}from"@vcp-dev/contracts";function Hc(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 Rs();let a=s.target,l=a.locator;if(a.sourceKind==="repeat-template"){let c=o?.instanceIndex;if(c===void 0)return Rs();let u=jF(a,c,o?.instanceCount);if(!u)return Rs();l=u}return{ok:!0,target:{kind:"value-binding",file:a.file,locator:l}}}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"?Rs():{ok:!0,target:{kind:"jsx-attribute"}}}function Rs(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function jF(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(l=>l.kind==="index");if(s<0)return null;let a=i.map((l,c)=>c===s&&l.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:l);return{...e.locator,path:a}}import*as qn from"@babel/types";import{SiteEditSetPropsParamsSchema as $F}from"@vcp-dev/contracts";function xE(e){let t=e.changes??(e.change?[e.change]:[]);if(!$F.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return Ps("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return Ps("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=rt(e.source,"value");if(!o.ok)return Ps("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 l=Ne(o.ast,a);if(!l.ok||!l.match.path.isObjectExpression())return Ps("unsupported-object",`Repeat item ${s} is not a writable object expression`);let c=s===e.target.sourceItemIndex?UF(r):VF(l.match.path.node,r.name);if(!c)return Ps("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:c})}return{ok:!0,steps:i}}function UF(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function VF(e,t){let n=e.properties.filter(i=>qn.isObjectProperty(i)&&KF(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!qn.isExpression(r.value))return null;let o=Wn(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function KF(e){return qn.isIdentifier(e)?e.name:qn.isStringLiteral(e)?e.value:qn.isNumericLiteral(e)?String(e.value):null}function Ps(e,t){return{ok:!1,errorCode:e,reason:t}}function bE(e){if(e.change.name!=="className"&&e.change.name!=="class")return Cs("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return Cs("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return Cs("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return Cs("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 Cs("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 Cs(e,t){return{ok:!1,errorCode:e,reason:t}}async function SE(e){let t=JF.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return Vr("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 Vr("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 XF(e,r);if(o){if(!o.ok)return Vr("owner-plan-failed",o.reason);EE(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return Vr("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return Vr("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(WF(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=Hc({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return Vr(a.code,a.reason);let l=a.target;if(l.kind==="value-binding"&&r.operation==="set"){qf(n,{type:"update-value",order:n.length,file:l.file,locator:l.locator,value:r.value});continue}if(l.kind==="repeat-property"){let c=xE({source:e.getFileContent(l.target.sourceFile),target:l.target,changes:[r]});if(!c.ok)return Vr("repeat-target-failed",c.reason);EE(n,c.steps);continue}qf(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:zF(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),HF(n)?Vr("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function XF(e,t){return t.name!=="className"&&t.name!=="class"?null:bE({node:e.node,change:t,classNameSource:e.classNameSource})}function zF(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 HF(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 EE(e,t){for(let n of t)qf(e,{...n,order:e.length})}function qf(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 WF(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Qf(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Qf(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)=>Qf(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=>Qf(n[i],r[i]))}return!1}function Vr(e,t){return{ok:!1,errorCode:e,reason:t}}import*as ui from"@babel/types";import*as ue from"@babel/types";function ep(e,t,n){let r=Nn(t,n);return r?Qn(e,r):null}function Qn(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 l=a.node,c=l.property;if(!ue.isIdentifier(c)||c.name!=="map"||l.computed)return null;let u=a.get("object"),d=ci(e,u.node),f=r.node.params.map(p=>ci(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:ue.isOptionalMemberExpression(l)&&l.optional?"?.map":".map",collectionNeedsParens:Wc(u.node),callbackPath:r,collectionPath:u}}function Ns(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=ze(e.node);return n?YF(t).some(r=>{let o=ze(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function YF(e){let t=e.callbackPath.node.body;return ue.isBlockStatement(t)?Kr(t.body):Jr(t)}function Kr(e){let t=[];for(let n of e){if(ue.isReturnStatement(n)){n.argument&&t.push(...Jr(n.argument));continue}if(ue.isBlockStatement(n)){t.push(...Kr(n.body));continue}if(ue.isIfStatement(n)){let r=ue.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...Kr(r)),n.alternate){let o=ue.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...Kr(o))}continue}if(ue.isSwitchStatement(n)){for(let r of n.cases)t.push(...Kr(r.consequent));continue}ue.isTryStatement(n)&&(t.push(...Kr(n.block.body)),n.handler&&t.push(...Kr(n.handler.body.body)),n.finalizer&&t.push(...Kr(n.finalizer.body)))}return t}function Jr(e){return ue.isJSXElement(e)?ZF(e)?vE(e.children):[e]:ue.isJSXFragment(e)?vE(e.children):ue.isParenthesizedExpression(e)||ue.isTSAsExpression(e)||ue.isTSSatisfiesExpression(e)||ue.isTSNonNullExpression(e)||ue.isTSTypeAssertion(e)?Jr(e.expression):ue.isConditionalExpression(e)?[...Jr(e.consequent),...Jr(e.alternate)]:ue.isLogicalExpression(e)&&Zf(e.operator)?Jr(e.right):[]}function vE(e){return e.flatMap(t=>ue.isJSXElement(t)||ue.isJSXFragment(t)?Jr(t):ue.isJSXExpressionContainer(t)&&(ue.isJSXElement(t.expression)||ue.isJSXFragment(t.expression)||ue.isConditionalExpression(t.expression)||ue.isLogicalExpression(t.expression))?Jr(t.expression):[])}function ZF(e){let t=e.openingElement.name;return ue.isJSXIdentifier(t)?t.name==="Fragment":ue.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function IE(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Wc(e){return!(ue.isIdentifier(e)||ue.isThisExpression(e)||ue.isMemberExpression(e)||ue.isOptionalMemberExpression(e)||ue.isCallExpression(e)||ue.isOptionalCallExpression(e))}function kE(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(ue.isMemberExpression(n)||ue.isOptionalMemberExpression(n))&&ue.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function li(e,t){let n=Ot(e);if(!n)return t.isRepeatItemRoot===!0;let r=Ne(n,Ge(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Jc(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Qn(e,o);return i?GF(o,i):t.isRepeatItemRoot===!0}function _E(e,t){let n=Ot(e);if(!n)return!1;let r=Ne(n,Ge(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Jc(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(ue.isMemberExpression(s)||ue.isOptionalMemberExpression(s))&&ue.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as Qe from"@babel/types";function tp(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 qF(e,t){let n=ze(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Zn(a.path.node,n)||Xr(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=tp(i.node.name);s&&o(s,i)}}),[...r].sort()}function np(e,t,n){let r=Ot(e);if(!r)return{ok:!0};let o=Ne(r,Ge(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=Ne(r,Ge(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Vi(o.match.path,i.match.path);if(Xc(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=qF(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function PE(e){let t=e;for(;Qe.isTSQualifiedName(t);)t=t.left;return Qe.isIdentifier(t)?t.name:null}function As(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Gc(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 rp(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=RE(e),i=RE(t);if(!o||!i||!gE(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=hE(s.node,n);if(a&&!fn(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&&fn(a,n)&&!fn(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())&&kE(s)){let a=ze(s.node.body)??ze(s.node);if(a&&!fn(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 RE(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 Xr(e,t,n){return n.scope.getBinding(t)===e}function op(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Xc(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(l=>Gc(l)).map(l=>n.callbackPath.scope.getBinding(l)?.path.node).filter(Boolean)),s=new Set,a=(l,c)=>{let u=c.scope.getBinding(l);!u||Zn(u.path.node,o)||i.has(u.path.node)||Xr(u,l,t)||s.add(l)};return e.traverse({ReferencedIdentifier(l){a(l.node.name,l)},JSXOpeningElement(l){let c=tp(l.node.name);c&&a(c,l)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function ip(e,t,n){let r=ze(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Gc(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return As(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Zn(a.path.node,r)||o.has(a.path.node)||Xr(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function CE(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Gc(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,l)=>{let c=l.scope.getBinding(a);!c||n.has(c.path.node)||Xr(c,a,t)||r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(l){o(l.node.name,l)},TSTypeReference(l){let c=l.node.typeName;if(ui.isIdentifier(c))o(c.name,l);else{let u=PE(c);u&&o(u,l)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function sp(e,t){let n=ze(e.node),r=new Set;return As(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Zn(i.path.node,n)||Xr(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 NE(e){let t=[];for(let n of e.callbackPath.node.params){if(ui.isIdentifier(n)){t.push(n.name);continue}if(ui.isRestElement(n)&&ui.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 AE(e,t){return{...e,callbackParams:t}}function ap(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function Ts(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 TE(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 _o(e){return{file:e.file,component:e.component}}function QF(e){return e.target.kind==="node"?e.target.key:null}function eL(e){return"kind"in e&&e.kind==="page-composition"}function qc(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="block-boundary"}function Yc(e){return!eL(e)&&!qc(e)}function fp(e,t){let n=el.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=el.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function cp(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=zn(n,Ge(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function mp(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 tL(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function nL(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 lp(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function rL(e){let t=nE(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=rp(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=oL({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=$E(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?Wc(o):!0}}}function oL(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||Zn(a.path.node,t))return;let l=aL(s,a,t);if(l){if(l.hasDefault){o="Cannot move prop-backed repeat child because the collection prop has a default value that cannot be preserved safely";return}let c=lL(e.callSitePath,l.propName,e.source);if(!c.ok){o=c.reason;return}let u=iL(c.expression,l.remainingPath);if(!u){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let d=sp(c.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(`${l.range.start}:${l.range.end}`,{...l.range,text:u});return}Xr(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:uL(e.source,t,[...n.values()])}}function iL(e,t){if(t.length===0)return e;let n=$E(e);if(!n)return null;let r=Wc(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=sL(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function sL(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function aL(e,t,n){let r=cL(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=ri(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 cL(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Zn(n.node,t)||n.node.computed||!Ue.isIdentifier(n.node.property))return null;let r=ze(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function lL(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(l=>l.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let o=r.find(l=>l.isJSXAttribute()&&Ue.isJSXIdentifier(l.node.name)&&l.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=ci(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 uL(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 $E(e){try{let n=jE.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=Ue.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&Ue.isExpression(r)?r:null}catch{return null}}function dL(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||Zn(s.path.node,t))return;let a=wE(s,e.sourceFile,e.targetFile);if(a){let l=e.targetParentPath.scope.getBinding(a.localName);if(l){let u=wE(l,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!fL(u.importSpec,a.importSpec))&&r.add(a.localName);return}let c=n.get(a.moduleSpecifier)??[];c.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||c.push(a.importSpec),n.set(a.moduleSpecifier,c);return}r.add(i.node.name)};return As(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 fL(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 wE(e,t,n){let r=pL(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=vo(t,i),a=i.startsWith(".")?fp(n,s):i;if(r.isImportDefaultSpecifier()){let l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:l}}}if(r.isImportNamespaceSpecifier()){let l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:l}}}if(r.isImportSpecifier()){let l=Ue.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:l,local:c===l?void 0:c}}}return null}function pL(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function OE(e,t,n,r){let o=Yf(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let l=ci(e,a.conditionPath.node);if(!l)return{sourceJsx:r,conditionPaths:[]};let c=mL(a.conditionPath,l);if(s.push(a.conditionPath),a.kind==="logical"){i=`${c} ${a.operator} ${hL(i)}`;continue}i=a.branch==="consequent"?`${c} ? ${i} : null`:`${c} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function mL(e,t){return gL(e.node)?t:`(${t})`}function gL(e){return Ue.isIdentifier(e)||Ue.isThisExpression(e)||Ue.isSuper(e)||Ue.isMemberExpression(e)||Ue.isOptionalMemberExpression(e)||Ue.isCallExpression(e)||Ue.isOptionalCallExpression(e)||Ue.isBooleanLiteral(e)||Ue.isNumericLiteral(e)||Ue.isStringLiteral(e)||Ue.isNullLiteral(e)||Ue.isUnaryExpression(e)}function hL(e){return e.trim().startsWith("<")?e:`(${e})`}var yL={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 Zc(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=yL[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 xL(e,t){for(let n of e.program.body){if(!Ue.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>Ue.isImportDefaultSpecifier(o));if(r&&Ue.isImportDefaultSpecifier(r))return r.local.name}return null}function bL(e,t,n){for(let r of e.program.body){if(!Ue.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>Ue.isImportSpecifier(i)&&(Ue.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&Ue.isImportSpecifier(o))return o.local.name}return null}function FE(e){let t=new Set;return Mn(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function LE(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function EL(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=mp(e),o=Ot(t);if(n.exportName!=="default"){let a=o?bL(o,n.source,n.exportName):null;if(a)return{localName:a};let l=o?LE(r,FE(o)):r;return{localName:l,importStep:up(e,l)}}if(!o)return{localName:r,importStep:up(e,r)};let i=xL(o,n.source);if(i)return{localName:i};let s=LE(r,FE(o));return{localName:s,importStep:up(e,s)}}function SL(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??mp(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 vL(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?IL(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function IL(e){return Object.fromEntries(Object.entries(e).filter(t=>pp(t[1])))}function pp(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(pp):typeof e=="object"?Object.values(e).every(pp):!1}function up(e,t=mp(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 DE(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 kL(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function di(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function gp(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function ws(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:gp(e,t.slice(0,n)),index:r.index}}return null}function dp(e,t){return e.locator?e.collectionPathMap?.[t]?gp(e.locator,e.collectionPathMap[t]):ws(e.locator)?RL(e.locator,PL(t,e.collectionIndexMap)):null:null}function _L(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:UE(o,t)}function UE(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=UE(r,t);return o===void 0?void 0:{[n.name]:o}}function RL(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},gp(e,i)}return null}function PL(e,t){return t?.[e]??e}function ME(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 CL(e,t){return NL(e.root,t.root)&&TL(e.path??[],t.path??[])}function NL(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&&AL(e.sourceRange,t.sourceRange)}}function AL(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function TL(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 Qc=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:di(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:di(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:di(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:di(t.kind,t.params.kind)};let r=t;if(qc(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if(!Yc(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=DE(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:di(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:di(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=QF(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):BE(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 BE(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:Ge(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?SE({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[l,c]of Object.entries(o)){if(c===void 0)continue;let u=await this.graph.getElementPropertyWriteTarget?.(r.key,l),d=r.attributes?.find(g=>g.name===l);if((await this.graph.getPropertyState?.(r.key,l,i))?.status==="blocked"||!u&&d?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${l}'`};if(!(typeof d?.resolvedValue=="string"&&d.resolvedValue===c||d?.source===null&&d.value===c)){if(u?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${l}'`};if(u?.kind==="value-binding"&&u.locator){let g=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let m=dp(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:c});continue}a.push({operation:"set",name:l,value:c})}}return a.length>0&&s.push({order:n+s.length,file:r.file,type:"set-property-changes",locator:Ge(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=dp(o,i.instanceIndex);if(!a)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(o.file,a,r);return l.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-array-item",locator:a,value:l.value}]}:l}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:Ge(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Ot(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=Ne(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!tL(a.match.path))return{ok:!0,value:r};let l=nL(r);return l===null?{ok:!1,errorCode:"invalid-params",reason:`${o} value must be a valid number for numeric source`}:{ok:!0,value:l}}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 l=dp(o,i);if(!l)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item could not resolve the selected repeat item"};let c=this.coerceTextValueForValueTarget(o.file,l,s,"update-array-item");return c.ok?this.isValueTargetUnchanged(o.file,l,c.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:l,value:c.value}],r):c}isValueTargetUnchanged(t,n,r){let o=Ot(this.graph.getFileContent(t));if(!o)return!1;let i=Ne(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=ws(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=Ts(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 l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let c=[{order:0,file:r.file,type:"remove-node",locator:Ge(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&c.push({...u,order:c.length}),this.buildPlan(t,n,c,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||mE(n,t)>1)return null;let r=fp(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(!Yc(n.params.position))return qc(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,l=Ts(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};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=Gb(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=Zc(r,n.params.node);if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let p=[],h=0,x=n.params.node.kind==="component-call"?EL(n.params.node,this.graph.getFileContent(r.file)):void 0,E=x?.importStep;return E&&p.push({order:h++,file:r.file,type:"add-import",moduleSpecifier:E.moduleSpecifier,imports:E.imports}),p.push({order:h++,file:r.file,type:"insert-child",parentLocator:Ge(r),node:{jsx:SL(n.params.node,x?.localName)},placement:n.params.position.relation,anchorLocator:i?Ge(i):void 0}),this.buildPlan(t,n,p,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Yc(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 l=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:l?.kind==="external-entry"?l.sourceId:null,node:vL(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(!Yc(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 l=ws(a.locator);if(!l)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let c=_L(a.locator,i.text);if(c===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"?ME(0,a.collectionIndexMap):ME(a.collectionIndexMap?.length??l.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:l.locator,index:u,value:c}],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=Ts(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 li(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:")||_E(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&&li(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let l=this.graph.getFileContent(r.file),c=Ot(l);if(!c)return null;let u=Nn(c,r),d=Nn(c,o);if(!u||!d)return null;let f=Qn(l,u),g=Qn(l,d);if(!Ns(f,g))return null;if(a&&(s==="before"||s==="after")){let p=Nn(c,a),h=p?Qn(l,p):null;if(!Ns(f,h))return null}if(zc(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let m=np(l,r,o);return m.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Ge(r),targetParentLocator:Ge(o),placement:s,anchorLocator:a?Ge(a):void 0,selectionContext:_o(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&&li(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let l=this.graph.getFileContent(r.file),c=Ot(l);if(!c)return null;let u=Nn(c,r),d=Nn(c,o);if(!u||!d)return null;let f=Qn(l,u);if(!f)return null;let g=Qn(l,d);if(Ns(f,g))return null;if(g&&!IE(g,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let b=ep(l,c,a);if(g&&!Ns(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=Zc(o,{kind:"native-tag",tag:r.tag});if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b}}let m=cp(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(zc(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let p=OE(l,u,d,m);for(let b of p.conditionPaths){let S=ip(b,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 h=op(u,d,f,{preserveConditionalBoundary:p.conditionPaths.length>0});if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${h.bindingNames.join(", ")}`};let x=CE(f,d);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let E=f;if(r.component!==o.component){let b=rL({source:l,ast:c,sourceContext:f,sourceNode:r,targetParent:o,targetParentPath:d});if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason};E=b.context}else{let b=sp(f.collectionPath,d);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${b.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:Ge(r),targetParentLocator:Ge(o),placement:s,anchorLocator:a?Ge(a):void 0,repeatExpression:ap(E,p.sourceJsx),selectionContext:_o(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&li(this.graph.getFileContent(r.file),r)||r.file===o.file)return null;let l=this.graph.getFileContent(r.file),c=this.graph.getFileContent(o.file),u=Ot(l),d=Ot(c);if(!u||!d)return null;let f=yE({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=Nn(u,r),m=Nn(d,o);if(!g||!m)return null;let p=rp(f.callSitePath,m);if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let h=Qn(l,g);if(!h)return null;if(Qn(c,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(c,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 N=Zc(o,{kind:"native-tag",tag:r.tag});if(N)return{ok:!1,errorCode:"unsupported-operation",reason:N}}let E=cp(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(zc(g,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=OE(l,g,m,E);for(let N of b.conditionPaths){let w=ip(N,m,h);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=op(g,m,h,{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 v=dL({sourceFile:r.file,targetFile:o.file,sourceContext:h,targetParentPath:m});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason};let P=NE(h);if(!P.ok)return{ok:!1,errorCode:"unsupported-operation",reason:P.reason};let I=AE(h,P.callbackParams),C=[{order:0,file:r.file,type:"remove-node",locator:Ge(r),removeWhitespace:!0}];for(let N of v.imports)C.push({order:C.length,file:o.file,type:"add-import",moduleSpecifier:N.moduleSpecifier,imports:N.imports});return C.push({order:C.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:Ge(o),expression:ap(I,b.sourceJsx),placement:s,anchorLocator:a?Ge(a):void 0,selectionContext:_o(o)}),this.buildPlan(t,n,C,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if(qc(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 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 P=this.graph.getFileContent(r.file),I=Ot(P),C=I?Nn(I,r):null,N=I?Nn(I,S):null,w=C?.parentPath,L=N?.parentPath;if(!C||!N||!w||!L||w.node!==L.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:Ge(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:b.relation,anchorLocator:Ge(S),selectionContext:_o(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=DE(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(kL(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 l=await this.graph.getTextWriteTarget(r.key,0);if(l?.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:${l.sourceId}`,type:"invoke-external-adapter",sourceType:l.sourceType,sourceId:l.sourceId,adapterId:l.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 c=r.file!==s.file,u=n.params.target.relation,d=i.anchorNode,f=this.graph.getTextProvenance?.(r.key,0)??null,g=Ts(r,l,f);if(g&&!lp(g)&&!TE(r,s,l,f))return{ok:!1,errorCode:"unsupported-operation",reason:g};if(r.isRepeatItemRoot&&d?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===d.repeatOwnerKey&&(u==="before"||u==="after")){let b=l,S=await this.graph.getTextWriteTarget(d.key,0);if(b?.kind==="value-binding"&&S?.kind==="value-binding"&&b.locator&&S.locator){let v=ws(b.locator),P=ws(S.locator);if(v&&P&&b.file===S.file&&CL(v.locator,P.locator)){let I=v.index,C=P.index,N=u==="before"?C-(I<C?1:0):C+(I<C?0:1);return this.buildPlan(t,n,[{order:0,file:b.file,type:"move-array-item",locator:v.locator,fromIndex:I,toIndex:N}],o)}}}if(r.isRepeatItemRoot&&li(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=lp(g)?g:m;if(p&&lp(p)){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 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 h=await this.getUpstreamBackedDescendantReason(r);if(h)return{ok:!1,errorCode:"unsupported-operation",reason:h};if(r.tag&&r.tag.toLowerCase()===r.tag){let b=Zc(s,{kind:"native-tag",tag:r.tag});if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b}}if(c)return this.planCrossFileMove(t,n,r,s,o,u,d);let x=np(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:Ge(r),targetParentLocator:Ge(s),placement:u,anchorLocator:d?Ge(d):void 0,selectionContext:_o(s)}];return this.buildPlan(t,n,E,o)}planCrossFileMove(t,n,r,o,i,s,a){let l=[],c=0,u=this.graph.getFileContent(r.file),d=cp(this.graph,r)??`<${r.component} />`,f=Yb(u,r);if(!f.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason??"Cannot move subtree across files"};if(l.push({order:c++,file:r.file,type:"remove-node",locator:Ge(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let m=r.tag??r.component,h={moduleSpecifier:fp(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:m}]:[{kind:"named",imported:r.exportName,local:m===r.exportName?void 0:m}]};l.push({order:c++,file:o.file,type:"add-import",moduleSpecifier:h.moduleSpecifier,imports:h.imports}),l.push({order:c++,file:o.file,type:"insert-child",parentLocator:Ge(o),node:{jsx:d},placement:s,anchorLocator:a?Ge(a):void 0,selectionContext:_o(o)})}else l.push({order:c++,file:o.file,type:"insert-child",parentLocator:Ge(o),node:{jsx:d},placement:s,anchorLocator:a?Ge(a):void 0,selectionContext:_o(o)});let g=this.buildRemoveComponentImportStep(r,u);return g&&l.push({...g,order:c++}),this.buildPlan(t,n,l,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:Te(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 BE(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 XL,parseExpression as zL}from"@babel/parser";import*as _ from"@babel/types";import*as er from"@babel/types";import hp from"@babel/generator";import*as Ze from"@babel/types";var wL=typeof hp=="function"?hp:hp.default,OL=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,FL=/^((?:https?:)?\/\/)[^/@\s]+@/i,LL=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function KE(e,t){let n=pn(e.callee);if(!n)return null;if(n==="fetch")return yp(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(VE(r))return yp(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(VE(r))return yp(e.arguments[0],r,t,["ky client contract"])}return null}function yp(e,t,n,r){if(!e||Ze.isSpreadElement(e)||Ze.isJSXNamespacedName(e))return jL(t,n,r,"missing url argument");let o=Os(e);return{sourceKind:BL(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 Os(e){if(Ze.isStringLiteral(e))return Ro(e.value);if(Ze.isTemplateLiteral(e))return Ro(DL(e));if(Ze.isBinaryExpression(e)&&e.operator==="+"){let t=Os(e.left),n=Os(e.right);return!t&&!n?void 0:Ro(`${t??xp(e.left)}${n??xp(e.right)}`)}if(Ze.isMemberExpression(e)){let t=JE(e);if(t)return`env:${t}`}if(!(Ze.isCallExpression(e)&&pn(e.callee)==="new URL")){if(Ze.isNewExpression(e)&&Ze.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!Ze.isSpreadElement(t)?Os(t):void 0,o=n&&!Ze.isSpreadElement(n)?Os(n):void 0;return o&&r?Ro(`${o} + ${r}`):r??o}if(Ze.isIdentifier(e))return`:${e.name}`}}function DL(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+=xp(r))}return t}function xp(e){if(Ze.isIdentifier(e))return`:${e.name}`;if(Ze.isMemberExpression(e)){let t=JE(e);if(t)return`env:${t}`}return`:${ML(e)}`}function ML(e){return wL(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Ro(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(FL,"$1<redacted>@").replace(LL,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?OL.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function BL(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 jL(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function VE(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function JE(e){return!Ze.isMemberExpression(e.object)||!Ze.isIdentifier(e.object.object,{name:"process"})||!$L(e.object.property,"env")?null:Ze.isIdentifier(e.property)?e.property.name:Ze.isStringLiteral(e.property)?e.property.value:null}function $L(e,t){return Ze.isIdentifier(e)&&e.name===t}function pn(e){if(Ze.isIdentifier(e))return e.name;if(Ze.isMemberExpression(e)){let t=pn(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 UL=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),VL=new Set(["getConfig","submit"]);function br(e,t){let n=XE(pn(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!UL.has(i))return null;let s=bp(e,0),a=i==="getByUrl"||i==="getByUrlStrict",l=a?void 0:s,c=a?s??"/:record-url":l?`/collections/${l}`:"/collections/:collection";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:i,...l?{collection:l}:{},endpointPattern:c,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(!VL.has(i))return null;let s=bp(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=bp(e,0)??KL(e,0,"path")??"/cms/:path",s=JL(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 XE(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 zE(e,t){let n=pn(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 tl(e,t){let n=pn(e.callee),r=t?XE(n,t):n;return typeof r=="string"&&r.startsWith("cms.field.")}function bp(e,t){let n=e.arguments[t];return er.isStringLiteral(n)?n.value:null}function KL(e,t,n){let r=e.arguments[t];if(!er.isObjectExpression(r))return null;for(let o of r.properties)if(er.isObjectProperty(o)&&!o.computed&&(er.isIdentifier(o.key)&&o.key.name===n||er.isStringLiteral(o.key)&&o.key.value===n)&&er.isStringLiteral(o.value))return o.value.value;return null}function JL(e){let t=/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1];return t&&/^[a-z0-9][a-z0-9_-]*$/i.test(t)?t:null}function nl(e){return e.match(/^\/([a-z0-9][a-z0-9_-]*)\/[^/?#]+(?:[?#].*)?$/i)?.[1]??null}import*as Rt from"@babel/types";var Ep=new WeakMap;function tr(e,t){let n=Ep.get(e)?.get(t);if(n!==void 0)return n;let r=new Set([t]),o=c=>{let u=c;for(;Rt.isMemberExpression(u)||Rt.isOptionalMemberExpression(u);)u=u.object;return Rt.isIdentifier(u)?u.name:null},i=!0;for(;i;)i=!1,Rt.traverseFast(e,c=>{if(!Rt.isVariableDeclarator(c)||!c.init)return;let u=o(c.init);if(!(!u||!r.has(u)))for(let d of Object.keys(Rt.getBindingIdentifiers(c.id)))r.has(d)||(r.add(d),i=!0)});let s=c=>{let u=o(c);return u?r.has(u):Object.keys(Rt.getBindingIdentifiers(c)).some(d=>r.has(d))},a=!1;Rt.traverseFast(e,c=>{(Rt.isAssignmentExpression(c)&&s(c.left)||Rt.isUpdateExpression(c)&&s(c.argument)||Rt.isUnaryExpression(c,{operator:"delete"})&&s(c.argument))&&(a=!0)});let l=Ep.get(e)??new Map;return l.set(t,a),Ep.set(e,l),a}function HE(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:l,maxImportDepth:c}=o,u=t.get(s)?.get(a)?.get(l)?.get(c);if(u)return u.pending;let d=i();n.size>=e&&r(n.values().next().value);let f={fromFile:s,exportName:a,targetFile:l,maxImportDepth:c,pending:d},g=t.get(s)??new Map,m=g.get(a)??new Map,p=m.get(l)??new Map;return p.set(c,f),m.set(l,p),g.set(a,m),t.set(s,g),n.add(f),d.catch(()=>{r(f)}),d}}}import*as Vt from"@babel/types";import{posix as Sp}from"node:path";function fi(e,t,n=new Set){if(n.has(e))return;let r=new Set(n).add(e);if(Vt.isBooleanLiteral(e))return e.value;if(Vt.isUnaryExpression(e,{operator:"!"})){let c=fi(e.argument,t,r);return c===void 0?void 0:!c}if(Vt.isLogicalExpression(e)){let c=fi(e.left,t,r),u=fi(e.right,t,r);if(e.operator==="&&")return c===!1||u===!1?!1:c===!0?u:void 0;if(e.operator==="||")return c===!0||u===!0?!0:c===!1?u:void 0}if(!Vt.isCallExpression(e)||!Vt.isIdentifier(e.callee))return;let o=t.imports.get(e.callee.name),i=o?.source.startsWith(".")&&t.file?Sp.normalize(Sp.join(Sp.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=Vt.isExpression(s.body)?s.body:s.body.body.length===1&&Vt.isReturnStatement(s.body.body[0])?s.body.body[0].argument:null;if(!a||!Vt.isExpression(a))return;let l=s.params.flatMap(c=>Vt.isIdentifier(c)?[c.name]:[]);return fi(a,{file:t.file,imports:new Map([...t.imports].filter(([c])=>!l.includes(c))),functions:new Map([...t.functions].filter(([c])=>!l.includes(c)))},r.add(s))}var O2=typeof vp=="function"?vp:vp.default,rS=new WeakMap;function oS(e){let t=new Map;return rS.set(t,new Map([...e].map(n=>[n.file,n]))),t}var HL={maxFunctionDepth:8,maxImportDepth:6},WL=new Set(["src","href","alt","poster","content","title","aria-label"]),WE=new WeakMap;function GL(e,t,n){let r=WE.get(t.fileCache);r||(r=new WeakMap,WE.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=[],l=0,c=0;for(;l<s.length||c<i.length;){let u=s[l],d=i[c];u&&(!d||u.order<d.order)?(a.push(u.element),l++):d&&(!u||d.order<u.order)?(a.push(d.element),c++):(a.push(u.element),l++,c++)}return a}async function fl(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")&&YE(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=Cp(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...HL,...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:Np(n,e.element.componentName)};await iS(e.element.componentName,e.graph,r);let o=[];o.push(...await QL(e.element,e.graph,r),...await eD(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await tD(s,e.element,e.graph,r);a&&o.push(ul(a,"text","children"))}for(let s of e.element.attributes??[]){let a=YE(s,e.element);if(!a)continue;let l=await cS(s.source,e.element,e.graph,r);if(!l&&s.syntaxKind==="expression"&&!(s.source&&Co(s.source.base,e.element,e.graph))){let u=n.jsxElementsByRange.get(pl(e.element.sourceRange))?.openingElement.attributes.find(d=>_.isJSXAttribute(d)&&_.isJSXIdentifier(d.name,{name:s.name}));_.isJSXExpressionContainer(u?.value)&&_.isExpression(u.value.expression)&&!uS(u.value.expression,e.element,e.graph)&&(l=await at(u.value.expression,r))}l&&o.push(ul(l,a,s.name))}let i=pD(o).sort(yS);return{hasDynamicData:i.length>0,bindings:i}}async function iS(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 c of GL(t,n,e)){if(c.sourceFile===n.file&&c.tag===e){s.push(c);continue}!c.importedFrom||!c.exportName||c.importedFrom===n.file&&c.exportName!==i||(c.importedFrom===n.file||await YL(c.importedFrom,c.exportName,n.file,n))&&s.push(c)}if(s.length===0)return;let a=new Map;for(let c of s){let u=`${n.file}#${e}<-${c.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let d=await aS(c.sourceFile,n);if(!d)continue;let f=Gr(d,n,{importDepth:n.importDepth+1});f.paramSources.clear(),f.scopeVariables=bS(d,c.componentName),f.scopeFunction=Np(d,c.componentName),f.lexicalContext=void 0,await iS(c.componentName,t,f);let g=await ZL(c,t,f);for(let[m,p]of g){if(!p)continue;let h=a.get(m)??[];h.push(p),a.set(m,h)}}finally{n.resolvingComponentProps.delete(u)}}}let l=new Map;for(let[c,u]of a){let d=Pp(u);d.length===1&&l.set(c,d[0])}qL(o,l,n)}var GE=new WeakMap;function YL(e,t,n,r){let o=GE.get(r.fileCache);return o||(o=HE(),GE.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>sS(e,t,n,r))}async function sS(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 aS(e,r))?.imports.get(t);if(!s||!mt(s.source))return!1;let a=await Tp(e,s.source,r.exists);return a?a===n?!0:sS(a,s.importedName,n,r,o):!1}async function ZL(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(pl(e.sourceRange));if(o)for(let s of o.openingElement.attributes)!_.isJSXAttribute(s)||!_.isJSXIdentifier(s.name)||!_.isJSXExpressionContainer(s.value)||!_.isExpression(s.value.expression)||r.set(s.name.name,s.value.expression);let i=new Map;for(let[s,a]of r){let l=e.attributes?.find(d=>d.name===s)?.source??null,u=(l?Co(l.base,e,t):null)?await ml(l,e,t,n):uS(a,e,t)?null:await at(a,n);u&&i.set(s,u)}return i}function pl(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function aS(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 Cp(e,r,t.fileCache)}function qL(e,t,n){if(_.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,ll(Object.fromEntries(t),n.file));return}if(_.isObjectPattern(e))for(let r of e.properties){if(!_.isObjectProperty(r)||r.computed||!_.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=_.isAssignmentPattern(r.value)?r.value.left:r.value;_.isIdentifier(i)&&n.paramSources.set(i.name,Dt(o))}}function YE(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":WL.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function QL(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 gl(i.collectionSource,n);s&&r.push(ul(zr(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 gl(i.conditionSource,n);s&&r.push(ul(zr(s),"conditional-region",i.conditionExpression))}return r}async function tD(e,t,n,r){if(!e.source){let i=r.analysis.jsxElementsByRange.get(pl(t.sourceRange))?.children.find(s=>_.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 _.isJSXExpressionContainer(i)&&_.isCallExpression(i.expression)&&tl(i.expression)?lS(i.expression,t,n,r):null}return cS(e.source,t,n,r)}async function cS(e,t,n,r){return e&&Co(e.base,t,n)?ml(e,t,n,r):gl(e,r)}async function ml(e,t,n,r,o){if(!e)return null;let i=Co(e.base,t,n,o);if(!i||i.candidate.itemParamName!==e.base)return null;let s=i.candidate.collectionSource,l=(s?Co(s.base,t,n,i.region):null)?await ml(s,t,n,r,i.region):s?await gl(s,r):await nD(i.candidate.collectionExpression,t,n,r,i.region);return l?Fs(l,e.path,!0):null}async function nD(e,t,n,r,o){let i;try{i=zL(e,{plugins:["typescript","jsx"]})}catch{return null}return lS(i,t,n,r,o)}async function lS(e,t,n,r,o){let i=Gr(r.analysis,r),s=new Set;_.traverseFast(e,a=>{_.isIdentifier(a)&&s.add(a.name)});for(let a of s){let l=Co(a,t,n,o);if(!l)continue;if(l.candidate.itemParamName!==a)return null;let c=await ml({kind:"identifier",expression:a,base:a,path:[]},t,n,r,o);if(!c)return null;i.paramSources.set(a,c)}return at(e,i)}function Co(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&&!ZE(s.sourceRange,r.sourceRange))continue;let a=s.sourceCandidates?.find(l=>l.kind==="repeat-template"&&(l.itemParamName===e||l.indexParamName===e));a&&(!i||ZE(i.region.sourceRange,s.sourceRange))&&(i={candidate:a,region:s})}o=n.elements.get(o)?.parentKey??null}return i}function ZE(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 uS(e,t,n){let r=!1;return _.traverseFast(e,o=>{!r&&_.isIdentifier(o)&&Co(o.name,t,n)&&(r=!0)}),r}async function gl(e,t){if(!e)return null;let n=await _p(e.base,t);return n?Fs(n,e.path,!1):null}async function _p(e,t){let n=t.paramSources.get(e);if(n)return Dt(n);if(t.variableCache.has(e))return mD(t.variableCache.get(e)??null);let r=Wr(e,t);if(r&&r!==t)return _p(e,r);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let o=await oD(e,t);if(o)return t.variableCache.set(e,Dt(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 l=_.isArrayExpression(s)&&s.elements.length===0?await rD(e,t):await at(s,t);return t.variableCache.set(e,l?Dt(l):null),t.resolvingVariables.delete(e),l}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 l=await Ap(a,t);if(l){let c=Gr(l,t,{importDepth:t.importDepth+1}),u=ES(a,l);if(u){let g=(await Po(u,[],c)).returnSource;return t.variableCache.set(e,g?Dt(g):null),t.resolvingVariables.delete(e),g}let d=l.variables.get(a.importedName);if(d){let f=await at(d,c);return t.variableCache.set(e,f?Dt(f):null),t.resolvingVariables.delete(e),f}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function Wr(e,t){return t.scopeVariables?.has(e)||t.scopeFunction?.params.some(n=>Hr(n).includes(e))?t:t.lexicalContext?Wr(e,t.lexicalContext):void 0}function rl(e,t,n=new Set){if(_.isIdentifier(e)){let s=Wr(e.name,t);if(s&&s!==t)return rl(e,s,n)}if(n.has(e))return null;if(n.add(e),_.isStringLiteral(e))return e.value;if(!_.isIdentifier(e))return null;let r=Wr(e.name,t),o=t.paramArguments.get(e.name);if(o)return rl(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?rl(i,t,n):null}function nr(e,t,n=new Set){if(n.has(e))return null;let r=new Set(n).add(e);if(_.isStringLiteral(e))return e.value;if(_.isNumericLiteral(e))return String(e.value);if(_.isIdentifier(e)){if(/token|secret|password|authorization|cookie|credential/i.test(e.name))return":redacted";let o=Wr(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?nr(s.expression,s.context,r):a?nr(a,i,r):null)??`:${e.name}`}if(_.isBinaryExpression(e,{operator:"+"})){let o=nr(e.left,t,r),i=nr(e.right,t,r);return o!==null&&i!==null?o+i:null}if(_.isTemplateLiteral(e)){let o=e.quasis[0]?.value.cooked??"";for(let[i,s]of e.expressions.entries()){if(!_.isExpression(s))return null;o+=(nr(s,t,r)??":param")+(e.quasis[i+1]?.value.cooked??"")}return o}if(_.isCallExpression(e)&&_.isIdentifier(e.callee)&&["encodeURIComponent","decodeURIComponent"].includes(e.callee.name)&&_.isExpression(e.arguments[0])){let o=nr(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 _.isTSAsExpression(e)||_.isTSNonNullExpression(e)||_.isParenthesizedExpression(e)?nr(e.expression,t,r):null}async function rD(e,t){let n=t.scopeFunction;if(!n)return null;let r=[],o=!1,i=0,s=u=>{let d=!1;return _.traverseFast(u,f=>{_.isIdentifier(f,{name:e})&&(d=!0)}),d},a=u=>{let d=u;for(;_.isMemberExpression(d);)d=d.object;return _.isIdentifier(d,{name:e})},l=async(u,d)=>{if(!o){if(_.isFunction(u)){s(u)&&(o=!0);return}if(_.isVariableDeclarator(u)&&(Hr(u.id).includes(e)&&i++,u.init&&s(u.init)&&(o=!0)),(_.isAssignmentExpression(u)||_.isUpdateExpression(u))&&a(_.isAssignmentExpression(u)?u.left:u.argument)){o=!0;return}if(_.isUnaryExpression(u,{operator:"delete"})&&a(u.argument)){o=!0;return}if(_.isCallExpression(u)){if(_.isMemberExpression(u.callee)&&_.isIdentifier(u.callee.object,{name:e})){if(!_.isIdentifier(u.callee.property,{name:"push"})||u.callee.computed||!u.arguments.length){o=!0;return}for(let f of u.arguments){let g=_.isSpreadElement(f)?f.argument:f,m=_.isExpression(g)?await at(g,d):null;m?r.push(kp(m)):o=!0}return}if(u.arguments.some(f=>s(f))){o=!0;return}}if(_.isForOfStatement(u)){let f=await at(u.right,d),g=Gr(d.analysis,d),m=_.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;f&&m&&al(m,kp(f),g),await l(u.body,g);return}for(let f of _.VISITOR_KEYS[u.type]??[]){let g=u[f];for(let m of Array.isArray(g)?g:[g])_.isNode(m)&&await l(m,d)}}};await l(n.body,t);let c=Pp(r);return!o&&i===1&&c.length===1?zr(c[0]):null}async function oD(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(_.isIdentifier(e))return _p(e.name,t);if(_.isMemberExpression(e)||_.isOptionalMemberExpression(e)){let n=_.isMemberExpression(e)?zE(e,{file:t.file}):null;if(n)return gS(n);let r=await iD(e,t);if(!r)return null;let o=fD(e);return Fs(r,o,!1)}if(_.isAwaitExpression(e))return _.isExpression(e.argument)?at(e.argument,t):null;if((_.isCallExpression(e)||_.isOptionalCallExpression(e))&&(_.isMemberExpression(e.callee)||_.isOptionalMemberExpression(e.callee))&&!e.callee.computed&&_.isIdentifier(e.callee.property)&&["trim","trimStart","trimEnd"].includes(e.callee.property.name)&&e.arguments.length===0&&_.isExpression(e.callee.object))return mi(await at(e.callee.object,t));if(_.isCallExpression(e))return fS(e,t);if(_.isObjectExpression(e)){let n=await mS(e,t);return Object.keys(n).length>0?ll(n,t.file):null}if(_.isArrayExpression(e)){let n={};for(let[r,o]of e.elements.entries()){if(!_.isExpression(o))continue;let i=await at(o,t);i&&(n[String(r)]=i)}return Object.keys(n).length?ll(n,t.file):null}if(_.isConditionalExpression(e)){let n=await at(e.consequent,t),r=await at(e.alternate,t);return mi(eS(n,r))}if(_.isLogicalExpression(e)){let n=await at(e.left,t),r=await at(e.right,t);return mi(eS(n,r))}return _.isTSAsExpression(e)||_.isTSSatisfiesExpression(e)||_.isTSNonNullExpression(e)||_.isTypeCastExpression(e)||_.isParenthesizedExpression(e)?at(e.expression,t):null}async function iD(e,t){let n=e;for(;_.isMemberExpression(n)||_.isOptionalMemberExpression(n);)n=n.object;return _.isExpression(n)?at(n,t):null}async function dS(e,t,n=0){if(n>=t.options.maxFunctionDepth)return null;let r=Wr(e,t);if(r){if(r.scopeFunction&&tr(r.scopeFunction,e))return null;let s=r.paramArguments.get(e);return s&&_.isIdentifier(s.expression)?dS(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)||tr(t.analysis.ast,e))return null;let i=await Tp(t.file,o.source,t.exists);return i?{...o,source:i}:null}async function fS(e,t){let n=e.arguments[0],r=_.isExpression(n)?rl(n,t):null,i=pn(e.callee)?.split(".")[0],s=i?await dS(i,t):null,a=r!==null&&!_.isStringLiteral(n)?{...e,arguments:[_.stringLiteral(r),...e.arguments.slice(1)]}:e;if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&_.isObjectExpression(n)){let x=pS(n,"path"),E=x&&nr(x,t);E?.startsWith("/")&&(a={...e,arguments:[{...n,properties:n.properties.map(b=>_.isObjectProperty(b)&&hi(b)==="path"?{...b,value:_.stringLiteral(Ro(E))}:b)},...e.arguments.slice(1)]})}let l=br(a,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map});if(l){if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&l.endpointPattern==="/content/by-url"&&_.isObjectExpression(n)){let x=qE(n,"query"),E=_.isObjectExpression(x)?qE(x,"path"):null,b=E&&nr(E,t),S=b&&nl(b);S&&(l.collection=S,l.evidence.push({file:t.file,reason:"CMS collection namespace from the actual content request path"}))}if(_.isMemberExpression(e.callee)){let x=await Er(e.callee,t);if(x&&!ol(x.node))return null;if(x&&ol(x.node)){let E=await Ip(e,t,{node:x.node,context:x.context});return E&&{...E,...E.sourceKind===l.sourceKind?{operation:l.operation}:{}}}}if((l.operation==="getByUrl"||l.operation==="getByUrlStrict")&&_.isExpression(n)){let x=nr(n,t);x?.startsWith("/")&&(l.endpointPattern=Ro(x))}return gS(l)}if(pn(e.callee)==="Promise.all"&&_.isArrayExpression(n))return at(n,t);if(tl(e)){if(!tl(e,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map})||!_.isExpression(e.callee))return null;let x=await Er(e.callee,t);if(x)return ol(x.node)?Ip(e,t,{node:x.node,context:x.context}):null;let E=e.arguments[0];if(E&&_.isExpression(E))return mi(await at(E,t))}let c=await sD(e,t);if(c)return c;let u=KE(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 cD(e,t);if(d)return d;let f=await lD(e,t);if(f)return f;let g=await uD(e,t);if(g)return g;let m=await Ip(e,t);if(m)return m;let p=[];for(let x of e.arguments)if(_.isExpression(x)){let E=await at(x,t);E&&p.push(E)}let h=Pp(p);return h.length===1?mi(h[0]):null}async function sD(e,t){let n=pn(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=aD(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(_.isIdentifier(s)){let a=await gi(s.name,t);if(a)return(await Po(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!_.isObjectExpression(r))return il(t.file,`${n} without static options`);let o=pS(r,"queryFn");if(!o)return il(t.file,`${n} without queryFn`);if(_.isIdentifier(o)){let i=await gi(o.name,t);return i?(await Po(i.node,[],i.context)).returnSource:il(t.file,`${n} queryFn unresolved`)}return _.isArrowFunctionExpression(o)||_.isFunctionExpression(o)?(await Po(o,[],t)).returnSource:_.isCallExpression(o)?fS(o,t):null}function pS(e,t){for(let n of e.properties){if(!_.isObjectProperty(n)||!_.isExpression(n.value))continue;if(hi(n)===t)return n.value}return null}function qE(e,t){let n=new Set;for(let i of e.properties){if(!_.isObjectProperty(i)||i.computed)return null;let s=hi(i);if(!s||n.has(s))return null;n.add(s)}let r=e.properties.filter(i=>_.isObjectProperty(i)&&hi(i)===t);if(r.length!==1)return null;let o=r[0];return _.isObjectProperty(o)&&_.isExpression(o.value)?o.value:null}function aD(e,t,n){return _.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 cD(e,t){if(!_.isMemberExpression(e.callee)||!_.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=_.isExpression(e.callee.object)?await at(e.callee.object,t):null;if(!r)return null;if(n!=="map")return zr(r);let o=e.arguments[0];if(_.isIdentifier(o)){let i=await gi(o.name,t);if(!i)return zr(r);let s=await Po(i.node,[r],i.context);return{...zr(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(_.isArrowFunctionExpression(o)||_.isFunctionExpression(o)){let i=await Po(o,[r],t);return{...zr(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return zr(r)}async function lD(e,t){return!_.isMemberExpression(e.callee)||!_.isIdentifier(e.callee.property,{name:"json"})||!_.isExpression(e.callee.object)?null:at(e.callee.object,t)}async function uD(e,t){return!_.isMemberExpression(e.callee)||!_.isIdentifier(e.callee.property,{name:"then"})||!_.isExpression(e.callee.object)?null:mi(await at(e.callee.object,t))}async function Ip(e,t,n){let r=n;if(!r&&_.isIdentifier(e.callee))r=await gi(e.callee.name,t)??void 0;else if(!r&&_.isMemberExpression(e.callee)){let s=await Er(e.callee,t);s&&ol(s.node)&&(r={node:s.node,context:s.context})}if(!r)return null;let o=[];for(let s of e.arguments){if(!_.isExpression(s)){o.push(il(t.file,`unsupported argument for ${pn(e.callee)??"call"}`));continue}let a=await at(s,t);o.push(a)}return(await Po(r.node,o,r.context,{arguments:e.arguments,context:t})).returnSource}function ol(e){return _.isFunctionDeclaration(e)||dl(e)||_.isObjectMethod(e)&&e.kind==="method"}async function Er(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(_.isTSAsExpression(e)||_.isTSSatisfiesExpression(e)||_.isTSNonNullExpression(e))return Er(e.expression,t,o);if(_.isIdentifier(e)){let i=Wr(e.name,t),s=i??t;if(tr(i?.scopeFunction??t.analysis.ast,e.name))return r;let a=s.paramArguments.get(e.name);if(a)return Er(a.expression,a.context,o);let l=i?i.scopeVariables?.get(e.name):s.analysis.variables.get(e.name);if(l)return Er(l,s,o);if(i)return null;let c=s.analysis.functions.get(e.name);if(c)return{node:c,context:s};let u=s.analysis.imports.get(e.name);if(!u||s.importDepth>=s.options.maxImportDepth)return null;let d=await Ap(u,s);return d?Er(_.identifier(u.importedName),Gr(d,s,{importDepth:s.importDepth+1}),o):null}if(_.isMemberExpression(e)&&_.isExpression(e.object)){let i=e.computed?_.isStringLiteral(e.property)?e.property.value:null:_.isIdentifier(e.property)?e.property.name:null;if(!i)return null;let s=await Er(e.object,t,o);if(!s)return null;if(!_.isObjectExpression(s.node))return{node:null,context:s.context};if(s.node.properties.some(c=>_.isSpreadElement(c)||c.computed))return{node:null,context:s.context};let a=s.node.properties.filter(c=>(_.isObjectMethod(c)||_.isObjectProperty(c))&&(_.isIdentifier(c.key)?c.key.name:_.isStringLiteral(c.key)?c.key.value:null)===i);if(a.length===0)return null;if(a.length!==1)return{node:null,context:s.context};let l=a[0];return _.isObjectMethod(l)?l.kind==="method"?{node:l,context:s.context}:null:_.isObjectProperty(l)&&_.isExpression(l.value)?Er(l.value,s.context,o):null}return{node:e,context:t}}async function gi(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),dl(r.expression))return{node:r.expression,context:r.context};if(_.isIdentifier(r.expression))return gi(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 Ap(i,t);if(!s)return null;let a=Gr(s,t,{importDepth:t.importDepth+1}),l=ES(i,s);return l?{node:l,context:a}:gi(i.importedName,a)}async function Po(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=Gr(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 h of Hr(d))o.paramSources.delete(h),o.paramArguments.delete(h);let g=_.isAssignmentPattern(d)?d.left:d,m=r?.arguments[f];_.isIdentifier(g)&&_.isExpression(m)&&r&&o.paramArguments.set(g.name,{expression:m,context:r.context});let p=t[f];p&&al(d,kp(p),o)});let a=dD(e,o),l=null,c,u=!1;for(let d of a){let f=Gr(n.analysis,o);if(_.isObjectExpression(d)){c={...c??{},...await mS(d,f)},l=l??ll(c,n.file);continue}let g=await at(d,f);if(g){if(!l){l=g;continue}let m=Rp(l,g);if(!m){u=!0,l=null;continue}l=m}}return{returnSource:u?null:l,...c?{objectReturnMap:c}:{}}}function al(e,t,n){if(_.isIdentifier(e)){n.paramSources.set(e.name,Dt(t));return}if(_.isAssignmentPattern(e)){al(e.left,t,n);return}if(_.isObjectPattern(e))for(let r of e.properties){if(!_.isObjectProperty(r)||r.computed||!_.isIdentifier(r.key))continue;let o=Fs(t,[{kind:"property",name:r.key.name}],!0),i=_.isAssignmentPattern(r.value)?r.value.left:r.value;o&&al(i,o,n)}}function dD(e,t){if(_.isArrowFunctionExpression(e)&&_.isExpression(e.body))return[e.body];let n=[],r=e.body;if(!_.isBlockStatement(r))return n;let o=i=>{if(_.isFunction(i)&&i!==e)return;if(_.isReturnStatement(i)){i.argument&&_.isExpression(i.argument)&&n.push(i.argument);return}if(_.isIfStatement(i)){let a=fi(i.test,{file:t.file,imports:new Map([...t.analysis.imports].filter(([l])=>!Wr(l,t))),functions:t.analysis.functions});if(a!==void 0){a?o(i.consequent):i.alternate&&o(i.alternate);return}}let s=_.VISITOR_KEYS[i.type];for(let a of s??[]){let l=i[a];if(Array.isArray(l))for(let c of l)_.isNode(c)&&o(c);else _.isNode(l)&&o(l)}};return o(r),n}async function mS(e,t){let n={};for(let r of e.properties){if(!_.isObjectProperty(r))continue;let o=hi(r);if(!o||!_.isExpression(r.value))continue;let i=await at(r.value,t);i&&(n[o]=i)}return n}function hi(e){return _.isIdentifier(e.key)&&!e.computed?e.key.name:_.isStringLiteral(e.key)?e.key.value:null}function fD(e){let t=[],n=e;for(;_.isMemberExpression(n)||_.isOptionalMemberExpression(n);){let r=n.property;n.computed?_.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):_.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):_.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return _.isIdentifier(n),t}function Fs(e,t,n){if(t.length===0)return Dt(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?Fs(s,t.slice(1),n):null}let i=Dt(e);if(i.sourceType==="cms-field"){let s=t.filter(l=>l.kind==="property").map(l=>l.name);if(s[0]==="data"&&s[1]==="items")return i.valuePath=pi(i.valuePath,"data.items[]"),i.cmsFieldRoot=!1,i;let a=s[0]==="fields"?0:s[0]==="data"&&s[1]==="fields"?1:-1;return a>=0?(a===1&&(i.valuePath=pi(i.valuePath,"data")),i.fieldPath=pi(i.fieldPath,s.slice(a+1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=pi(i.fieldPath,s.join(".")),i):(i.valuePath=pi(i.valuePath,QE(t)),i)}return i.valuePath=pi(i.valuePath,QE(t)),i}function QE(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function pi(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function gS(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 zr(e){let t=Dt(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function kp(e){let t=Dt(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&!t.fieldPath&&(t.cmsFieldRoot=!1),t}function mi(e){return e?{...Dt(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function eS(e,t){return e?t?Rp(e,t):Dt(e):t?Dt(t):null}function Rp(e,t){if(cl(e)!==cl(t))return null;let n=xS(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Pp(e){let t=new Map;for(let n of e){let r=cl(n),o=t.get(r);t.set(r,o?Rp(o,n):Dt(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 ll(e,t){let n=Object.values(e)[0];return{sourceKind:n?.sourceKind??"unknown-api",sourceType:n?.sourceType??"api-field",endpointPattern:n?.endpointPattern,operation:n?.operation,collection:n?.collection,confidence:n?.confidence??"partial",readonly:!0,evidence:n?.evidence??[{file:t,reason:"object return map"}],fieldMap:e}}function il(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function ul(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 hS(e){let t=[...e].sort(yS),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 pD(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 yS(e,t){return tS(e.targetKind)-tS(t.targetKind)||xS(e.confidence,t.confidence)||nS(e.sourceKind)-nS(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function tS(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function nS(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function xS(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Cp(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=rS.get(n)?.get(e),i=o?.source===t?o.ast:XL(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=[],l=[];_.traverse(i,{enter(d){switch(_.isFunction(d)&&(s.functionParents.set(d,a.at(-1)??null),a.push(d)),d.type){case"CallExpression":l.push(d);break;case"JSXElement":{let f=d.loc;if(!f)return;let g=pl({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)_.isImportSpecifier(g)&&_.isIdentifier(g.local)?s.imports.set(g.local.name,{source:f,importedName:_.isIdentifier(g.imported)?g.imported.name:g.imported.value,localName:g.local.name,isDefault:!1}):_.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&&(_.isFunctionDeclaration(f)||_.isFunctionExpression(f)||_.isArrowFunctionExpression(f)||_.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,h]of sl(d.id,_.isExpression(d.init)?d.init:null))m.set(p,h);if(_.isArrayPattern(d.id)&&_.isCallExpression(d.init)&&pn(d.init.callee)==="useState"){let[p,h]=d.id.elements;_.isIdentifier(p)&&_.isIdentifier(h)&&s.stateSetters.set(p.name,h.name)}_.isIdentifier(d.id)&&dl(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(!_.isExportSpecifier(m))continue;let p=_.isIdentifier(m.exported)?m.exported.name:m.exported.value,h=m.local.name;s.imports.set(p,{source:g,importedName:h,localName:p,isDefault:h==="default"})}if(_.isFunctionDeclaration(f)&&f.id?.name&&s.functions.set(f.id.name,f),_.isVariableDeclaration(f))for(let m of f.declarations)_.isIdentifier(m.id)&&dl(m.init)&&s.functions.set(m.id.name,m.init);break}case"ExportDefaultDeclaration":{let f=d.declaration;if((_.isFunctionDeclaration(f)||_.isFunctionExpression(f)||_.isArrowFunctionExpression(f))&&s.functions.set("default",f),_.isIdentifier(f)){let g=s.functions.get(f.name);g&&s.functions.set("default",g)}break}}},exit(d){_.isFunction(d)&&a.pop()}});let c=new Set(s.stateSetters.values()),u=(d,f)=>{let g=s.stateSetterCandidates.get(d)??[];g.push(f),s.stateSetterCandidates.set(d,g)};if(c.size>0)for(let d of l){let f=_.isIdentifier(d.callee)?d.callee.name:null;f&&c.has(f)&&_.isExpression(d.arguments[0])&&u(f,d.arguments[0]);let g=new Set;for(let m of d.arguments)_.isIdentifier(m)&&m.name!==f&&c.has(m.name)&&g.add(m.name);for(let m of g)u(m,d)}return n.set(e,s),s}function sl(e,t){return _.isIdentifier(e)?[[e.name,t]]:_.isAssignmentPattern(e)?sl(e.left,t):_.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!_.isRestElement(n)?sl(n,t?_.memberExpression(t,_.numericLiteral(r),!0):null):[]):_.isObjectPattern(e)?e.properties.flatMap(n=>{if(!_.isObjectProperty(n)||n.computed)return[];let r=hi(n);return r?sl(n.value,t?_.memberExpression(t,_.stringLiteral(r),!0):null):[]}):[]}function Hr(e){return!e||_.isVoidPattern(e)?[]:_.isIdentifier(e)?[e.name]:_.isObjectPattern(e)?e.properties.flatMap(t=>_.isObjectProperty(t)?Hr(t.value):Hr(t.argument)):_.isArrayPattern(e)?e.elements.flatMap(t=>t?Hr(_.isRestElement(t)?t.argument:t):[]):_.isAssignmentPattern(e)?Hr(e.left):_.isRestElement(e)?Hr(e.argument):[]}function dl(e){return _.isFunctionExpression(e)||_.isArrowFunctionExpression(e)}function bS(e,t){let n=Np(e,t);return n?e.functionVariables.get(n):void 0}function Np(e,t){return e.functions.get(t)??e.functions.get("default")}async function Ap(e,t){let n=await Tp(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Cp(n,r,t.fileCache)}function ES(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Tp(e,t,n){return mt(t)?oo(e,t,n):null}function Gr(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 mD(e){return e?Dt(e):null}function Dt(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,Dt(n)]))}:{}}}import*as Op from"@babel/parser";import wp from"@babel/traverse";import*as de from"@babel/types";import{classifySiteEditPropertyName as gD}from"@vcp-dev/contracts";var Fp=typeof wp=="function"?wp:wp.default;function Lp(e){let t=gD(e.propertyName);if(t.owner!=="generic")return mn("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return mn("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return mn("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return mn("missing-instance-index","A repeat property target requires an instance index");let r;try{r=Op.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(h){return mn("repeat-not-found",`Unable to parse repeat source: ${h instanceof Error?h.message:String(h)}`)}let o=hD(r,e.element.sourceRange);if(!o)return mn("repeat-not-found","The selected element is not inside a supported map repeat");if(!de.isIdentifier(o.callback.params[0]))return mn("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=yD(r,o.collection,e.file,e.sources);if(!i)return mn("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:l}=i,c=[],u=[];for(let[h,x]of s.elements.entries()){if(!x||!de.isObjectExpression(x)||!RS(x))return mn("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let E=[{kind:"index",index:h}];c.push(E),u.push({kind:"value",root:a.root,path:E})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return mn("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let f=n.instanceIndex;if(f>=d)return mn("index-out-of-range",`Selected repeat instance ${f} is outside the source collection`);let g=s.elements[f];if(!g||!de.isObjectExpression(g))return mn("unsafe-collection","Selected repeat item is not an object");let m=ID(e.element,e.propertyName),p=SD(g,e.propertyName);return p?{ok:!0,sourceFile:l,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[f],sourceItemIndex:f,sourceItemPath:c[f],collectionIndexMap:Array.from({length:d},(h,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:p,selectedResolution:vD(g,e.propertyName),...m?{property:m}:{},selectionRef:n}:mn("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function hD(e,t){let n=[];return Fp(e,{CallExpression(r){let o=SS(r.node);o&&IS(o.callback,t)&&n.push({...o,span:vS(r.node)})},OptionalCallExpression(r){let o=SS(r.node);o&&IS(o.callback,t)&&n.push({...o,span:vS(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function SS(e){let t=e.callee;if(!de.isMemberExpression(t)&&!de.isOptionalMemberExpression(t)||t.computed||!de.isIdentifier(t.property)||t.property.name!=="map"||!de.isExpression(t.object))return null;let n=e.arguments[0];return!n||!de.isExpression(n)||!de.isArrowFunctionExpression(n)&&!de.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function yD(e,t,n,r){let o=Ls(t);if(o&&de.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:CS(o)}},sourceFile:n};if(!de.isIdentifier(t))return null;let i=[];if(Fp(e,{VariableDeclarator(s){de.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=Ls(i[0].init);return!s||!de.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return xD(e,t.name,n,r)}function xD(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!de.isImportDeclaration(o))continue;let i=o.specifiers.find(f=>f.local.name===t);if(!i||!de.isStringLiteral(o.source)||!de.isImportSpecifier(i))continue;let s=ED(n,o.source.value,r);if(!s)return null;let a=de.isIdentifier(i.imported)?i.imported.name:i.imported.value,l=r.get(s);if(l===void 0)return null;let c;try{c=Op.parse(l,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=bD(c,a),d=u?Ls(u):null;return!d||!de.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function bD(e,t){let n=null;return Fp(e,{VariableDeclarator(r){n||!de.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!de.isExpression(r.node.init)||(n=r.node.init)}}),n}function ED(e,t,n){let r=Kn(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 Ls(e){return de.isParenthesizedExpression(e)?Ls(e.expression):de.isTSAsExpression(e)?_S(e.typeAnnotation)?Ls(e.expression):null:de.isTSSatisfiesExpression(e)?null:e}function _S(e){return de.isTSTypeReference(e)&&de.isIdentifier(e.typeName)&&e.typeName.name==="const"}function RS(e){return e.properties.every(t=>!de.isObjectProperty(t)||t.computed||!de.isExpression(t.value)?!1:hl(t.value))}function hl(e){if(de.isTSAsExpression(e)&&_S(e.typeAnnotation))return hl(e.expression);if(de.isTSSatisfiesExpression(e))return!1;if(de.isArrayExpression(e))return e.elements.every(n=>!n||de.isSpreadElement(n)||!de.isExpression(n)?!1:hl(n));if(de.isObjectExpression(e))return RS(e);let t=Wn(e);return t.status==="resolved"||t.status==="undefined"}function SD(e,t){let n=e.properties.filter(o=>de.isObjectProperty(o)&&PS(o.key)===t);if(n.length>1)return null;let r=n[0];return r?de.isExpression(r.value)?hl(r.value)?"static":de.isIdentifier(r.value)||de.isMemberExpression(r.value)?"binding":null:null:"missing"}function vD(e,t){let n=e.properties.filter(o=>de.isObjectProperty(o)&&PS(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!de.isExpression(r.value)?{status:"undefined"}:Wn(r.value)}function ID(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function PS(e){return de.isIdentifier(e)?e.name:de.isStringLiteral(e)?e.value:de.isNumericLiteral(e)?String(e.value):null}function CS(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 vS(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function IS(e,t){let n=CS(e);return kS(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&kS(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function kS(e,t,n,r){return e===n?t-r:e-n}function mn(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as aM}from"@vcp-dev/contracts";import*as ye from"@babel/types";import $s from"node:path";import*as q from"@babel/types";import*as FS from"@babel/parser";import Dp from"@babel/traverse";import*as Ie from"@babel/types";function xl(e,t){let n=[],r=e;for(;Ie.isMemberExpression(r);){if(r.computed)if(Ie.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(Ie.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!Ie.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!Ie.isIdentifier(r)||r.name!==t?null:n}function NS(e){if(Ie.isIdentifier(e))return{base:e.name,path:[]};if(!Ie.isMemberExpression(e))return null;let t=[],n=e;for(;Ie.isMemberExpression(n);){if(n.computed)if(Ie.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ie.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!Ie.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return Ie.isIdentifier(n)?{base:n.name,path:t}:null}function Kt(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 rr=Symbol("not-closed-literal");function yl(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:rr;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return yl(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||Ie.isSpreadElement(n))return rr;let r=yl(n);if(r===rr)return rr;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!Ie.isObjectProperty(n)||n.computed||n.shorthand||!Ie.isExpression(n.value))return rr;let r=Ie.isIdentifier(n.key)?n.key.name:Ie.isStringLiteral(n.key)?n.key.value:null;if(!r)return rr;let o=yl(n.value);if(o===rr)return rr;t[r]=o}return t}default:return rr}}function AS(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,l,c,u,d){let f=yl(i);if(f!==rr)return f;if(!Ie.isTemplateLiteral(i)){if(Ie.isTSAsExpression(i)||Ie.isTSSatisfiesExpression(i)||Ie.isTSNonNullExpression(i))return await n(i.expression,s,a,l,c,u,d);if(Ie.isIdentifier(i)){let g=s.getBinding(i.name);if(!g)return;let m=await t({currentFile:a,binding:g,readFile:l,exists:c,fileCache:u,visited:d});return m?.kind==="static"?m.value:void 0}if(Ie.isArrayExpression(i)){let g=[];for(let m of i.elements){if(!m||Ie.isSpreadElement(m))return;let p=await r(m,s,a,l,c,u,d);if(p===void 0)return;g.push(p)}return g}if(Ie.isObjectExpression(i)){let g={};for(let m of i.properties){if(!Ie.isObjectProperty(m)||m.computed)return;let p=null;if(Ie.isIdentifier(m.key)?p=m.key.name:Ie.isStringLiteral(m.key)&&(p=m.key.value),!p)return;if(m.shorthand){if(!Ie.isIdentifier(m.value))return;let x=await r(m.value,s,a,l,c,u,d);if(x===void 0)return;g[p]=x;continue}if(!Ie.isExpression(m.value))return;let h=await r(m.value,s,a,l,c,u,d);h!==void 0&&(g[p]=h)}return g}if(Ie.isMemberExpression(i)){let g=await o(i,s,a,l,c,u,d);if(!g)return;let m=s.getBinding(g.base);if(!m)return;let p=await t({currentFile:a,binding:m,readFile:l,exists:c,fileCache:u,visited:d});return!p||p.kind!=="static"?void 0:Kt(p.value,g.path)}}}async function r(i,s,a,l,c,u,d){if(!Ie.isSpreadElement(i))return await n(i,s,a,l,c,u,d)}async function o(i,s,a,l,c,u,d){if(Ie.isIdentifier(i))return{base:i.name,path:[]};if(!Ie.isMemberExpression(i))return null;let f=[],g=i;for(;Ie.isMemberExpression(g);){if(g.computed){let m=g.property;if(Ie.isNumericLiteral(m))f.unshift({kind:"index",index:m.value});else if(Ie.isStringLiteral(m))f.unshift({kind:"property",name:m.value});else{let p=Ie.isExpression(m)?await n(m,s,a,l,c,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(!Ie.isIdentifier(g.property))return null;f.unshift({kind:"property",name:g.property.name})}g=g.object}return Ie.isIdentifier(g)?{base:g.name,path:f}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var LS=typeof Dp=="function"?Dp:Dp.default,TS=new WeakMap;function DS(e){try{return FS.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function bl(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=DS(n);return e.set(t,{source:n,ast:o}),o}function El(e,t){return Mp(Ds(e).expressionRanges,t,!1)}function MS(e,t){return Ds(e).exactExpressions.get(BS(t))??null}function Sl(e,t){return Mp(Ds(e).jsxRanges,t,!0)}function Ds(e){let t=TS.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return LS(e,{Expression(r){let o=r;n.expressions.push(o);let i=wS(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=BS(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=wS(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(OS),n.jsxRanges.sort(OS),TS.set(e,n),n}function wS(e,t){let n=Ms(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function BS(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function OS(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function Mp(e,t,n,r){let o=0,i=e.length;for(;o<i;){let l=o+Math.floor((i-o)/2),c=e[l].range;c.startLine<t.startLine||c.startLine===t.startLine&&c.startColumn<t.startColumn?o=l+1:i=l}let s=null,a=n?1/0:-1;for(let l=o;l<e.length;l++){let c=e[l],u=c.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(c.path))continue;((n?c.span<a:c.span>a)||c.span===a&&(!s||c.traversalIndex>s.traversalIndex))&&(s=c,a=c.span)}return s?.path??null}function Ms(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 yi(e,t){if(t)return Bp(e,t);let n=NS(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Bp(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Bs(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of Ds(e).expressions){if(Bp(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function jS(e,t,n,r){return Mp(Ds(e).expressionRanges,r,!0,o=>Bp(o.node,t)===n)}function xi(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function js(e){let t=null;if(LS(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function Bn(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=DS(o),s={source:o,ast:i};return n.set(e,s),s}function kD(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 _D(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,l=a&&q.isLogicalExpression(a,{operator:"&&"})?a.right:null,c=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(l,{operator:"!"})||!q.isBinaryExpression(l.argument,{operator:"in"})||!q.isIdentifier(l.argument.left,{name:r.name})||!q.isIdentifier(l.argument.right,{name:n.name})||!q.isReturnStatement(c)||!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 RD(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 $S(e,t){let n=RD(e.path);if(!n)return null;let r=ri(e,t);return r?{...n,...r}:null}function US(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function jp(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 $p(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 VS(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(p){let{currentFile:h,binding:x,readFile:E,exists:b,fileCache:S,visited:v}=p,P=`${h}::${x.kind}::${x.identifier.name}`;if(v.has(P))return null;v.add(P);try{let I=await a({currentFile:h,binding:x,readFile:E,exists:b,fileCache:S,visited:v});if(I)return I;if(x.path.isImportSpecifier()||x.path.isImportDefaultSpecifier())return await g({currentFile:h,binding:x,readFile:E,exists:b,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,fileCache:S,visited:v});if(x.kind==="param")return null;if(x.path.isVariableDeclarator()){let C=x.path.node.init;if(!C||!q.isExpression(C))return null;let N=_D(C);if(N&&!x.path.scope.getBinding("Proxy")&&!x.path.scope.getBinding("Reflect")){let D=x.path.scope.getBinding(N),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=x.path.get("init");if(w&&!Array.isArray(w)&&w.isExpression()){let D=await t({currentFile:h,expressionPath:w,readFile:E,exists:b,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:h,callPath:w,readFile:E,exists:b,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v});if(U)return U}}let L=await r(C,x.path.scope,h,E,b,S,v);return L===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:x.identifier.name},value:L,sourceKind:"binding"}}if(x.path.isIdentifier()&&x.path.parentPath?.isExportDefaultDeclaration()){let C=x.path.parentPath.node.declaration;if(!q.isExpression(C))return null;let N=await r(C,x.path.scope,h,E,b,S,v);return N===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:x.identifier.name},value:N,sourceKind:"binding"}}return null}finally{v.delete(P)}}async function a(p){let{currentFile:h,binding:x,readFile:E,exists:b,fileCache:S,visited:v}=p;if(!x.path.isVariableDeclarator()||!x.path.get("id").isArrayPattern())return null;let P=x.path,I=P.node.init;if(!I||!q.isCallExpression(I))return null;let C=kD(I);if(!C||!q.isArrayPattern(P.node.id)||P.node.id.elements.findIndex(U=>q.isIdentifier(U)&&U.name===x.identifier.name)!==0)return null;let w=C==="useReducer"?1:0,L=I.arguments[w];if(!L||!q.isExpression(L))return null;let D=await r(L,P.scope,h,E,b,S,v);return D===void 0?null:{kind:"static",file:h,root:{kind:"hook-state",name:x.identifier.name,hook:C},value:D,sourceKind:"binding"}}async function l(p){let h=p.expressionPath.scope.getBinding(p.sourceInfo.base);if(!h||!h.constant||h.kind!=="param"||!p.graph)return null;let x=$S(h,p.sourceInfo);if(!x)return null;let E=[...p.graph.elements.values()].filter(S=>US(S,p.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 v=await Bn(S.sourceFile,p.readFile,p.fileCache),P=v.ast?Sl(v.ast,S.sourceRange):null;if(!P)return null;let I=P.parentPath;for(;I&&!I.isFunction();){if(I.isJSXElement()){let M=I.node.openingElement.name;if(!q.isJSXIdentifier(M)||!/^[a-z]/.test(M.name))return null}else if(!I.isJSXFragment()&&!I.isReturnStatement()&&!I.isBlockStatement())return null;I=I.parentPath}if(!I)return null;let C=P.get("openingElement").get("attributes").filter(M=>M.isJSXAttribute()&&q.isJSXIdentifier(M.node.name,{name:x.propName}));if(C.length!==1)return null;let N=C[0];if(!N?.isJSXAttribute())return null;let w=N.get("value"),L=w.isJSXExpressionContainer()?w.get("expression"):w;if(!L.isExpression())return null;let D=await r(L.node,L.scope,S.sourceFile,p.readFile,p.exists,p.fileCache,p.visited),U=D===void 0?void 0:Kt(D,x.remainingPath);if(U===void 0)return null;b.push(U)}return b}async function c(p){let h=$S(p.binding,p.sourceInfo);if(!h||!p.graph)return null;let x=["component-prop",p.currentFile,p.binding.identifier.start??p.binding.path.node.start??-1,h.componentName,h.propName].join(":");if(p.visited.has(x))return null;p.visited.add(x);try{return await u(p,h,p.graph)}finally{p.visited.delete(x)}}async function u(p,h,x){let E=[...x.elements.values()].filter(N=>US(N,p.currentFile,h.componentName,h.exportName));if(E.length!==1)return null;let b=E[0],S=b.attributes?.find(N=>N.name===h.propName);if(S&&!S.source){let N=await d({caller:b,propName:h.propName,remainingPath:h.remainingPath,readFile:p.readFile,fileCache:p.fileCache});if(N)return jp(N,{componentName:h.componentName,propName:h.propName,file:b.sourceFile})}if(!S?.source){let N=await f({caller:b,propName:h.propName,remainingPath:h.remainingPath,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(N)return jp(N,{componentName:h.componentName,propName:h.propName,file:b.sourceFile});let w=Ub(p.binding,h.componentName,h.propName);if(!w||w.propName!==h.propName)return null;let L=await r(w.expressionPath.node,w.expressionPath.scope,p.currentFile,p.readFile,p.exists,p.fileCache,p.visited);if(L===void 0)return null;let D=h.remainingPath;return D.length>0&&Kt(L,D)===void 0?null:{kind:"value",file:p.currentFile,root:{kind:"binding",name:h.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 Bn(b.sourceFile,p.readFile,p.fileCache);if(!v.ast)return null;let P=jS(v.ast,v.source,S.source.expression,S.sourceRange)??Bs(v.ast,v.source,S.source.expression);if(!P)return null;let I={...S.source,expression:xi(S.source.expression,h.remainingPath),path:[...S.source.path,...h.remainingPath]},C=await o({currentFile:b.sourceFile,expressionPath:P,sourceInfo:I,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 C?jp(C.kind==="external"?C:{...C,displayExpression:I.expression},{componentName:h.componentName,propName:h.propName,file:b.sourceFile}):null}async function d(p){let h=await Bn(p.caller.sourceFile,p.readFile,p.fileCache);if(!h.ast)return null;let x=Sl(h.ast,p.caller.sourceRange);if(!x)return null;let E=x.get("openingElement").get("attributes").find(P=>P.isJSXAttribute()&&P.node.name.type==="JSXIdentifier"&&P.node.name.name===p.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 v=Ms(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 h=await Bn(p.caller.sourceFile,p.readFile,p.fileCache);if(!h.ast)return null;let x=Sl(h.ast,p.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 v=await i({expression:S.node,scope:S.scope,source:h.source,currentFile:p.caller.sourceFile,readFile:p.readFile,exists:p.exists,fileCache:p.fileCache,visited:p.visited});if(!v)continue;let P=[{kind:"property",name:p.propName},...p.remainingPath],I={...v,expression:xi(v.expression,P),path:[...v.path,...P]},C=await o({currentFile:p.caller.sourceFile,expressionPath:S,sourceInfo:I,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 C.kind==="external"?C:{...C,displayExpression:I.expression}}return null}async function g(p){let{currentFile:h,binding:x,readFile:E,exists:b,fileCache:S,visited:v}=p,P=x.path.parentPath;if(!P||!P.isImportDeclaration())return null;let I=P.node.source.value;if(typeof I!="string")return null;let C=await oo(h,I,b);if(!C)return null;if(x.path.isImportDefaultSpecifier()){let M=await Bn(C,E,S),G=M.ast?$p(M.ast,"default"):null,K=await m({file:C,exportName:"default",readFile:E,exists:b,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:C,root:G?.kind==="default-expression"?K.root:{kind:"default-export"},value:K.value,sourceKind:"imported-binding"}}if(!x.path.isImportSpecifier())return null;let N=x.path.node.imported,w=q.isIdentifier(N)?N.name:N.value,L=await Bn(C,E,S),D=L.ast?$p(L.ast,w):null,U=await m({file:C,exportName:w,readFile:E,exists:b,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:C,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:h,exportName:x,readFile:E,exists:b,fileCache:S,visited:v}=p,P=`export::${h}::${x}`;if(!v.has(P)){v.add(P);try{let I=await Bn(h,E,S);if(!I.ast)return;let C=$p(I.ast,x);if(!C)return;if(C.kind==="default-expression"){let D=C.expression;if(!D||!q.isIdentifier(D))return;let U=js(I.ast).getBinding(D.name);return U?await s({currentFile:h,binding:U,readFile:E,exists:b,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v})??void 0:void 0}if(C.kind==="re-export"){if(!C.source||!C.name)return;let D=await oo(h,C.source,b);return D?m({...p,file:D,exportName:C.name}):void 0}let N=C.name;if(!N)return;let w=js(I.ast).getBinding(N);return w?await s({currentFile:h,binding:w,readFile:E,exists:b,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v})??void 0:void 0}finally{v.delete(P)}}}return{resolveExportValue:m,resolveComponentPropBinding:c,resolveComponentPropValues:l,resolveBindingTarget:s}}import*as le from"@babel/types";function Vp(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=Dn(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!PD(s,r)?null:{callPath:s,basePath:i}}function PD(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 zS(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:$c(r,t)}function KS(e,t){return e?le.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function JS(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=Up(i,t,n,r,o);return typeof s=="number"?s:void 0}function Up(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=xl(e,t);if(i)return Kt(r,i);let s=xl(e,n);return s?Kt(o,s):void 0}if(le.isBinaryExpression(e)&&e.operator==="-"){let i=le.isExpression(e.left)?Up(e.left,t,n,r,o):void 0,s=le.isExpression(e.right)?Up(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function CD(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 ND(e,t,n){let r=No(e,t,n);return typeof r=="boolean"?r:void 0}function No(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=xl(e,t);return r?Kt(n,r):void 0}if(le.isUnaryExpression(e)&&e.operator==="!"){let r=No(e.argument,t,n);return r===void 0?void 0:!r}if(le.isLogicalExpression(e)){let r=No(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&No(e.right,t,n);if(e.operator==="||")return r||No(e.right,t,n)}if(le.isBinaryExpression(e)){let r=le.isExpression(e.left)?No(e.left,t,n):void 0,o=le.isExpression(e.right)?No(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 HS(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 WS(e){return e.some(t=>t.kind==="dynamic")}function XS(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function GS(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 AD(e,t){let n=[],r=[];for(let o of t){let i=Kt(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 YS(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(m){let{currentFile:p,callPath:h,readFile:x,exists:E,fileCache:b,visited:S}=m,v=h.node.callee;if(!le.isMemberExpression(v)||!le.isIdentifier(v.property)||v.property.name!=="map")return null;let P=h.get("callee");if(!P.isMemberExpression())return null;let I=P.get("object");if(Array.isArray(I)||!I.isExpression())return null;let C=await a({currentFile:p,expressionPath:I,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:b,visited:S});return!C||!Array.isArray(C.value)||C.value.length===0?null:C}async function a(m){let{currentFile:p,expressionPath:h,readFile:x,exists:E,fileCache:b,visited:S}=m;if(h.isIdentifier()){let v=h.scope.getBinding(h.node.name);if(!v)return null;let P=await t({currentFile:p,binding:v,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:b,visited:S});return P?.kind==="static"?P:null}if(h.isCallExpression())return c({currentFile:p,callPath:h,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:b,visited:S});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let v=h.get("expression");if(!Array.isArray(v)&&v.isExpression())return a({...m,expressionPath:v})}if(h.isArrayExpression()){let v=Ms(h.node);if(!v)return null;let P=await n(h.node,h.scope,p,x,E,b,S);return Array.isArray(P)?{kind:"static",file:p,root:{kind:"expression",sourceRange:v},value:P,sourceKind:"binding"}:null}if(h.isMemberExpression()){let v=await r({expression:h.node,scope:h.scope,currentFile:p,readFile:x,exists:E,fileCache:b,visited:S});if(!v)return null;let P=await o({currentFile:p,expressionPath:h,sourceInfo:v,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:b,visited:S});if(!P||P.kind==="external")return null;let I=await l({currentFile:p,expressionPath:h,provenance:P,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:b,visited:S});if(!I||I.kind!=="static")return null;if(P.collectionPathMap?.length){let N=AD(I.value,P.collectionPathMap);if(N)return{kind:"static",file:P.file,root:P.root,value:N.value,sourceKind:P.sourceKind,collectionPathMap:N.collectionPathMap}}let C=Kt(I.value,P.path);return Array.isArray(C)?{kind:"static",file:P.file,root:P.root,value:C,sourceKind:P.sourceKind,pathPrefix:P.path,collectionIndexMap:P.collectionIndexMap,collectionPathMap:P.collectionPathMap}:null}return null}async function l(m){let{provenance:p}=m;if(p.root.kind==="binding"){let b=m.expressionPath.scope.getBinding(p.root.name);if(!b&&p.file!==m.currentFile){let S=await Bn(p.file,m.readFile,m.fileCache);b=S.ast?js(S.ast).getBinding(p.root.name):void 0}return b?await t({currentFile:p.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(p.root.kind!=="expression")return null;let h=await Bn(p.file,m.readFile,m.fileCache);if(!h.ast)return null;let x=MS(h.ast,p.root.sourceRange);if(!x)return null;let E=await n(x.node,x.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 c(m){return await u(m)??await d(m)??await f(m)}async function u(m){let{callPath:p}=m,h=p.node.callee;if(!le.isMemberExpression(h)||!le.isIdentifier(h.property)||h.property.name!=="filter")return null;let x=p.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]=p.node.arguments;if(!le.isArrowFunctionExpression(S)&&!le.isFunctionExpression(S))return null;let v=S.params[0];if(!le.isIdentifier(v))return null;let P=CD(S);if(!P)return null;let I=[],C=[],N=[];for(let[w,L]of b.value.entries()){let D=ND(P,v.name,L);if(typeof D!="boolean")return null;if(D){I.push(L),C.push(b.collectionIndexMap?.[w]??w);let U=b.collectionPathMap?.[w];U&&N.push(U)}}return{...b,value:I,pathPrefix:b.pathPrefix,collectionIndexMap:C,...N.length>0?{collectionPathMap:N}:{}}}async function d(m){let{callPath:p}=m,h=p.node.callee;if(!le.isMemberExpression(h)||!le.isIdentifier(h.property)||h.property.name!=="slice")return null;let x=p.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,v]=p.node.arguments,P=KS(S,0),I=KS(v,b.value.length);if(P===null||I===null)return null;let C=Math.max(0,P<0?b.value.length+P:P),N=Math.max(0,I<0?b.value.length+I:I),w=b.value.map((D,U)=>b.collectionIndexMap?.[U]??U).slice(C,N),L=b.collectionPathMap?.slice(C,N);return{...b,value:b.value.slice(C,N),pathPrefix:b.pathPrefix,collectionIndexMap:w,...L?{collectionPathMap:L}:{}}}async function f(m){let{callPath:p}=m,h=p.node.callee;if(!le.isMemberExpression(h)||!le.isIdentifier(h.property)||h.property.name!=="sort"&&h.property.name!=="toSorted")return null;let x=p.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]=p.node.arguments;if(!le.isArrowFunctionExpression(S)&&!le.isFunctionExpression(S))return null;let[v,P]=S.params;if(!le.isIdentifier(v)||!le.isIdentifier(P))return null;let I=b.value.map((N,w)=>({value:N,sourceIndex:b.collectionIndexMap?.[w]??w,originalIndex:w})),C=[...I];for(let N of I)for(let w of I)if(JS(S,v.name,P.name,N.value,w.value)===void 0)return null;return C.sort((N,w)=>{let L=JS(S,v.name,P.name,N.value,w.value)??0;return L===0?N.originalIndex-w.originalIndex:L}),{...b,value:C.map(N=>N.value),pathPrefix:b.pathPrefix,collectionIndexMap:C.map(N=>N.sourceIndex),...b.collectionPathMap?{collectionPathMap:C.map(N=>b.collectionPathMap?.[N.originalIndex]).filter(N=>!!N)}:{}}}async function g(m){let p=null,h=!1,x,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 P=Vp(m.expressionPath,v.base),I;if(P){h=!0;let C=await s({currentFile:m.currentFile,callPath:P.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(!C||!Array.isArray(C.value))return null;I=C.value.map((N,w)=>{let L=Kt(C.value,[{kind:"index",index:w},...P.basePath,...v.path]);return XS(L)}),x??=C.collectionIndexMap}else{let C=await i({...m,sourceInfo:v});if(!C)return null;I=C.map(XS)}if(I.some(C=>C===null)||p!==null&&p!==I.length)return null;p=I.length,E.push(I)}if(p===null||p===0)return null;let b=[];for(let S=0;S<p;S+=1){let v=[...m.rootPath],P=0;for(let I of m.segments){if(I.kind==="dynamic"){let C=E[P]?.[S];if(!C)return null;v.push(C),P+=1;continue}v.push({...I})}b.push(v)}return{sourceKind:h||p>1?"repeat-template":"binding",...x?{collectionIndexMap:x}:{},collectionPathMap:b}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:g}}var{normalizeExpressionWithScope:TD,evaluateStaticExpression:vl}=AS({resolveBindingTarget:e=>Il(e)}),{resolveRepeatCollectionTarget:wD,resolveCollectionCallTarget:OD,resolveDynamicMemberPathMap:FD}=YS({resolveBindingTarget:e=>Il(e),evaluateStaticExpression:vl,buildExpressionSourceInfo:or,resolveSourceInfoProvenance:An,resolveComponentPropValues:e=>MD(e)}),{resolveExportValue:LD,resolveComponentPropBinding:DD,resolveComponentPropValues:MD,resolveBindingTarget:Il}=VS({resolveExternalExpression:Gp,resolveCollectionCallTarget:OD,evaluateStaticExpression:vl,resolveSourceInfoProvenance:An,buildExpressionSourceInfo:or});function iv(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var ZS=new WeakMap;function BD(e){let t=ZS.get(e);return t||(t=new WeakMap,ZS.set(e,t)),t}function qS(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 sv(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=bl(s,t,n);if(!a)return null;let l=El(a,r.sourceRange);if(!l)return null;let c=await or({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!c){let f=await Qp({currentFile:t,expressionPath:l,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});return f?Xp(f,yi(l.node,n)):null}let u=new Set,d=await sM({currentFile:t,expressionPath:l,segment:{...r,source:c},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:u});return d?Xp(d,c.expression):null}async function bi(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=bl(i,t,n);if(!s)return null;let a=e.sourceRange?El(s,e.sourceRange):e.expression!==void 0?Bs(s,n,e.expression):null;if(!a)return null;let l=kl(a);if(!l.isIdentifier()&&!l.isMemberExpression())return null;let c=new Set,u=await or({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:c}),d=u?await An({currentFile:t,expressionPath:l,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:c}):await mv({currentFile:t,expressionPath:l,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:c});return Xp(d,e.expression??yi(l.node,n))}async function Wp(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=bl(i,t,n);if(!s)return gn("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?jD({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}):$D({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function or(e){if(ye.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!ye.isMemberExpression(e.expression))return null;let t=await TD(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:yi(e.expression,e.source),base:t.base,path:t.path}:null}function Xp(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 jD(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:l}=e,c=El(r,o.sourceRange),u=c?await or({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:l}):null;if(!u){if(!c||c.isStringLiteral()||c.isTemplateLiteral()&&c.node.expressions.length===0)return QS(t,o.value);let f=await Qp({currentFile:t,expressionPath:c,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});return f?f.kind==="external"?ov(t,f):Hp(t,yi(c.node,n),f):UD({expression:c.node,scope:c.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:l,functionCallContracts:e.functionCallContracts})}if(!c)return gn("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await An({currentFile:t,expressionPath:c,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});if(!d){let f=zp(c.node);if(f)return gn(f.code,f.message);let g=c.scope.getBinding(u.base);if(g?.path.isVariableDeclarator()){let m=zp(g.path.node.init);if(m)return gn(m.code,m.message)}return g?.path.isVariableDeclarator()&&ye.isCallExpression(g.path.node.init)?VD("unsupported-expression",dv(g.path.node.init,e.functionCallContracts)):gn("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?ov(t,d):Hp(t,u.expression,d)}async function $D(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:l}=e;if(!o.conditionSource)return gn("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let c=Bs(r,n,o.conditionExpression);if(!c)return gn("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await An({currentFile:t,expressionPath:c,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});if(!u)return gn("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return gn("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=Hp(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 QS(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 UD(e){let t=await cv(e);if(t.length===0)return gn("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(KD(e.expression))return av(t);if(uv(e.expression))return gn("unsupported-expression","i18n helpers require a static message id string");if(ye.isMemberExpression(e.expression)&&e.expression.computed&&!ye.isNumericLiteral(e.expression.property)&&!ye.isStringLiteral(e.expression.property))return gn("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return gn(n.code,n.message)}function gn(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function VD(e,t){return av([{code:e,message:t}])}function av(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function KD(e){return ye.isCallExpression(e)||ye.isConditionalExpression(e)||ye.isLogicalExpression(e)||ye.isBinaryExpression(e)}function Us(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 cv(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:l}=e,c=zp(t);if(c)return[c];if(ye.isCallExpression(t))return[{code:"unsupported-expression",message:dv(t,l)}];if(ye.isMemberExpression(t)&&t.computed){let u=t.property;if(!ye.isNumericLiteral(u)&&!ye.isStringLiteral(u)){if(!ye.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let f=await vl(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 ye.isBinaryExpression(t)?Us([...await Kp(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):ye.isLogicalExpression(t)?Us([...await Kp(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"}]):ye.isConditionalExpression(t)?Us([...await Kp(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 zp(e){return uv(e)?ev("i18n helpers require a static message id string"):WD(e)?ev("CMS helpers require static entry id and field path string arguments"):null}async function Kp(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await cv({...t,expression:o}));return r}function JD(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:[XD(e.sourceType)]}}async function Gp(e){for(let n of qD){if(!tv(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return rv(nv(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(!tv(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return rv(nv(r),e.externalAdapters)}return null}function XD(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function zD(e){return{code:"external-source-readonly",message:e}}function ev(e){return{code:"unsupported-expression",message:e}}function Yp(e){return!e||!ye.isCallExpression(e)?null:ye.isIdentifier(e.callee)?e.callee.name:ye.isMemberExpression(e.callee)&&!e.callee.computed&&ye.isIdentifier(e.callee.object)&&ye.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function tv(e,t){if(!t||t.length===0)return!0;let n=Yp(e.node);return n?t.includes(n):!1}function nv(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Us(e.diagnostics??[])}:{match:e,diagnostics:[]}}function rv(e,t){let n=JD(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:Us([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function HD(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!ye.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!ye.isStringLiteral(n)||!ye.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 WD(e){return!!e&&ye.isCallExpression(e)&&ye.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!ye.isStringLiteral(e.arguments[0])||!ye.isStringLiteral(e.arguments[1]))}function lv(e){if(!(!e||!ye.isCallExpression(e))){if(ye.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&ye.isStringLiteral(t)?t.value:null}if(ye.isMemberExpression(e.callee)&&!e.callee.computed&&ye.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&ye.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!ye.isObjectExpression(t))return null;for(let n of t.properties)if(ye.isObjectProperty(n)&&!n.computed&&(ye.isIdentifier(n.key)&&n.key.name==="id"||ye.isStringLiteral(n.key)&&n.key.value==="id")&&ye.isStringLiteral(n.value))return n.value.value;return null}}}function uv(e){return lv(e)===null}async function GD(e,t,n){let r=new Set,o=$s.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=$s.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"]:[$s.posix.join(i,"locales"),$s.posix.join(i,"messages")];for(let a of s){let l=$s.posix.join(a,`${t}.json`);if(await n(l))return l}}return null}async function YD(e){let t=lv(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await GD(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function ZD(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!ye.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!ye.isExpression(n))return null;let o=await vl(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:[zD("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var qD=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>HD(e)},{helperNames:["apiField"],resolve:e=>ZD(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>YD({currentFile:e,expressionPath:t,exists:n})}];function Zp(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function ov(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 Hp(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(c=>c.kind==="index"),i=iM(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,l=[...n.chainPrefix??[]];return n.sourceKind==="binding"?l.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:n.editMode!=="readonly"}):n.sourceKind==="imported-binding"?l.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"&&l.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:n.editMode!=="readonly"}),n.path.length>0&&n.sourceKind!=="repeat-template"&&l.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:n.editMode!=="readonly"}),i&&l.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"?l.map(c=>({...c,canEditHere:!1})):l,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var QD=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function qp(e,t){let n=[...QD,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function dv(e,t){let n=e.callee;return ye.isIdentifier(n)&&qp(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 Qp(e){let t=await Gp(e);if(t)return t;let n=await fv({...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 or({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 An({...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 rM(e)}async function fv(e){let t=await jn({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=kl(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:Zp(t.provenance)}async function jn(e){let t=kl(e.expressionPath),n=nM(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 or({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 An({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 or({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 An({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 jn({...e,expressionPath:r,allowComposed:!0}),a=await jn({...e,expressionPath:o,allowComposed:!1}),l=await jn({...e,expressionPath:i,allowComposed:!1});return Jp(s,a,l)}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 jn({...e,expressionPath:r,allowComposed:!0}),s=await jn({...e,expressionPath:o,allowComposed:!0});return Jp(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 jn({...e,expressionPath:r,allowComposed:!0}),s=await jn({...e,expressionPath:o,allowComposed:!0});return Jp(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:jn({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function kl(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=Yp(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:jn({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(ye.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:jn({...e,expressionPath:o,allowComposed:!1})}}return null}function Jp(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!tM(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function tM(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 nM(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function rM(e){if(!e.expressionPath.isCallExpression())return null;let t=Yp(e.expressionPath.node);if(!t)return null;let n=qp(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 pv({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?Zp(i):null}async function pv(e){let t=await Gp({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 or({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 An({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 Qp({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 oM(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!ye.isCallExpression(t))return null;let n=t.callee;if(!ye.isIdentifier(n))return null;let r=qp(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 pv({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?Zp(a):null}function iM(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=xi(t,e.path);return{sourceId:o,displayPath:o}}async function sM(e){let t=e.segment.source;return t?An({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 An(e){let t=e.sourceInfo,n=Vp(e.expressionPath,t.base);if(n){let c=await wD({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(!c){let p=zS(n.callPath,[...n.basePath,...t.path]);return ks(p)?qS(e.currentFile,p.sourceId,p.displayPath):null}let u=GS(c,[...n.basePath,...t.path]),d=c.collectionIndexMap?.[0]??0,f=[...c.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],g=[{kind:"index",index:0},...n.basePath,...t.path];return Kt(c.value,g)===void 0?null:{kind:"value",file:c.file,root:c.root,path:u?.[0]??f,sourceKind:"repeat-template",collectionIndexMap:c.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let c=t.path[0],u=r.path.parentPath;if(!c||c.kind!=="property"||!u?.isImportDeclaration())return null;let d=await oo(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let f=await LD({file:d,exportName:c.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 Kt(f.value,g)===void 0?null:{kind:"value",file:f.file,root:f.root,path:g,sourceKind:"imported-binding",collectionIndexMap:f.collectionIndexMap}}let o=jb(r);if(o){let c=o.expressionPath,u=await or({expression:c.node,scope:c.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let d=await An({...e,expressionPath:c,sourceInfo:{...u,expression:xi(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}else if(r.constant){let d=`dynamic-alias:${e.currentFile}:${c.node.start}`;if(e.visited.has(d))return null;e.visited.add(d);try{let f=await mv({...e,expressionPath:kl(c),memberSuffix:t.path});if(f?.kind==="value")return f}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await fv({currentFile:e.currentFile,expressionPath:c,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 DD({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 oM({currentFile:e.currentFile,binding:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(i)return i;let s=Bc(r,t.path,BD(e.fileCache));if(ks(s))return qS(e.currentFile,s.sourceId,s.displayPath);let a=await Il({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:Kt(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 mv(e){let t=HS(e.expressionPath.node);if(!t||!WS(t.segments))return null;let n=await An({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 FD({...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 Il({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>Kt(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:yi(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function gv(e){let t=aM(e.propertyName);if(t.owner==="blocked")return Yr(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return Yr(t.owner,{code:"owner-delegated",message:`Property '${e.propertyName}' is owned by ${t.owner}`});let n=e.element.attributes?.filter(c=>c.name===e.propertyName)??[];if(n.length>1)return Yr("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 c of i)o.push({kind:"spread",order:c.order,spread:c,target:await lM(e,c)});o.sort((c,u)=>c.order-u.order);let s=o.at(-1);if(!s)return{status:"missing",owner:"generic"};if(o.filter(c=>c.kind==="spread"&&c.order>s.order).some(c=>!c.target))return Yr("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}:Yr("generic",{code:"ambiguous-property-source",message:`The final spread source for '${e.propertyName}' is not provably writable`});let l=o.filter(c=>c.kind==="spread"&&c.order<s.order);return e.operation==="remove"&&l.length>0?Yr("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):cM(e,s.attribute)}async function cM(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await bi({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}}:Yr("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 bi({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"?Yr("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 lM(e,t){let n=t.source?.expression;if(!n)return;let r=await bi({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:uM(r,e.propertyName)}}function uM(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 Yr(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function hv(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(Ao(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=>mM(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>dM({...r,graph:e},n)}function dM(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=pM(n,r,o,t),a=s?.tag??(Ao(r.tag)?r.tag:r.componentName),l=s?.identity.key??t(r,o)??n,c=hM(s),u=yM(n,r,o,i,s),d=fM(n,r,o,i,l);return{componentName:a,instanceKey:l,templateOwner:gM(s??r,a),...c.length>0?{variantKeys:c}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:xM(d),alternativeStrategies:bM(d)}}function fM(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return em(e,n)?"instance":!Ao(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function pM(e,t,n,r){if(Ao(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 mM(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function gM(e,t){return Ao(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function hM(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 yM(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 l=a?.chain.find(u=>u.kind==="component-prop");if(!l)continue;let c=l.displayName.split(".").pop();c&&i.add(c)}return i.size===0&&Ao(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(Ao(r.tag))return r;n=r.parentKey}return null}function Ao(e){return/^[A-Z]/.test(e)}function xM(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function bM(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function bv(e){let t=e.isRepeat??(e.graph?CM(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=PM(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>EM({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,l=(e.element.attributeSpreads??[]).slice().sort((u,d)=>u.order-d.order).map(u=>({raw:u.raw,sourceRange:NM(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."}]})),c=t&&e.selectionRef?.instanceIndex!==void 0&&i;return{documentVersion:e.documentVersion,...e.selectionRef?{selectionRef:e.selectionRef}:{},items:s,spreads:l,creation:t?{selection:c?"materialize":"unsupported",template:"unsupported"}:{selection:a?"unsupported":"direct",template:a?"unsupported":"direct"}}}function EM(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=SM(t,n,e.isRepeat),s=["selection","template"].map(h=>({scope:h,result:Hc({state:n,scope:h,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:h})=>h.ok)?.result,l=a?.ok?a.target:void 0,c=l?.kind==="value-binding"&&o&&(JSON.stringify(l.locator.root)!==JSON.stringify(o.selectedParentObjectLocator.root)||JSON.stringify(l.locator.path??[])!==JSON.stringify([...o.selectedParentObjectLocator.path??[],{kind:"property",name:t.name}]))?null:o,u=vM(t,n,c,e.isRepeat),d=l?_M(l,e.element,t.name):void 0,f=s.filter(({result:h})=>h.ok).map(({scope:h})=>h),g=f.length>0?kM(n,o,e.element):"unsupported",m=o?"repeat-item":e.isRepeat?"repeat-template":"node",p=RM(t,n,r);if(f.length===0&&p.length===0){let h=s.find(({result:x})=>!x.ok)?.result;h&&!h.ok&&p.push({code:h.code,message:h.reason})}return{name:t.name,source:i,resolution:u,editMode:g,sourceScope:m,allowedWriteScopes:f,...d?{effectiveWriteTarget:d}:{},diagnostics:p}}function SM(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?yv(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:yv(IM(e))}function IM(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 yv(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 _M(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:xv({...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:xv(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function RM(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 PM(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function CM(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 xv(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 NM(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 AM(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var TM=160;function Ev(e,t,n,r={}){let o=Ko(e),i=[];for(let[s,a]of e.elements){let l=n.get(s),c={canUpdateText:r.canUpdateTextByKey?.get(s)??l?.canUpdateText??!1,canInsertChild:l?.canInsertChild??!1,canMove:l?.canMove??!1,canRemove:l?.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:c,...r.dynamicDataSummaryByKey?.get(s)?{dynamicDataSummary:r.dynamicDataSummaryByKey.get(s)}:{}})}return{composition:o,routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:i}}function Sv(e,t,n,r,o,i,s,a,l,c,u){let d=Ko(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=Rv(f.textSegments,s),h=Pv(e,t,f,m,p),x=p?LM(p):void 0,E=DM(i,p),b=f.textSegments.map(I=>({index:I.index,value:I.value,editable:Cv(I,m,s?.get(I.index)??null),source:o.get(I.index)??null})),S=kv(f,t),v=f.childKeys.map(I=>{let C=t.elements.get(I);return C?{key:I,tag:C.tag,label:C.tag}:null}).filter(I=>I!==null),P=[];if(f.parentKey){let I=t.elements.get(f.parentKey);if(I)for(let C of I.childKeys){if(C===e)continue;let N=t.elements.get(C);N&&P.push({key:C,tag:N.tag,label:N.tag})}}return{composition:d,key:e,tag:f.tag,componentName:f.componentName,sourceFile:f.sourceFile,sourceLocator:Iv(f),label:f.tag,capabilities:h,writeTarget:i,effectiveWriteTarget:E,provenanceChain:x,componentSemantic:l,styleSource:c,conditional:a,...u?{dynamicData:u}:{},textSegments:b,boundaryKind:f.boundaryKind,isOpaque:f.isOpaque,ancestors:S,children:v,siblings:P}}function vv(e,t,n,r,o,i,s,a){let l=Ko(t),c=t.elements.get(e),u=n.nodes.get(e),d=r.get(e);if(!c||!u||!d)throw new Error(`Node not found: ${e}`);let f=Rv(c.textSegments,i),g=wM(c);return{composition:l,key:e,tag:c.tag,...g?{linkSourceKind:g}:{},componentName:c.componentName,sourceFile:c.sourceFile,sourceLocator:Iv(c),label:c.tag,capabilities:Pv(e,t,c,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:c.textSegments.map(m=>{let p=o.get(m.index);return{index:m.index,editable:Cv(m,d,i?.get(m.index)??null),source:p?{kind:p.kind}:null}}),boundaryKind:c.boundaryKind,isOpaque:c.isOpaque,ancestors:kv(c,t)}}function wM(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 Iv(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:OM(e.sourceRange),structuralPath:e.identity.structuralPath,...FM(e.textSegments)}}function kv(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 OM(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function FM(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,TM)}:{}}function _v(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 Rv(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function Pv(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,l=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"},c=r.canUpdateText&&Nv(l.mode);return{...r,canUpdateText:c,editModes:{updateText:l,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 Cv(e,t,n){return!e.editable||!t.canUpdateText?!1:n?Nv(n.editMode):!0}function Nv(e){return e==="direct"||e==="proxy"||e==="upstream"}function LM(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 DM(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}:AM(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 tm=["set-class-name-source","apply-style-draft"];function Av(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:tm,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:tm,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:tm}}import Tv from"node:path";function rm(){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 Ov(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=$M(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 l=t.has(a),c=n?await n(a):!1;if(l||c)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 _l(e){let t=()=>MM(e);return e.mutex?e.mutex.runExclusive(t):t()}async function MM(e){let t=await Ov(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=BM(e.overlay,t.plan),r;try{r=await e.buildCandidate({overlay:n,plan:t.plan})}catch(c){return{ok:!1,stage:"build",reason:"Candidate build failed.",error:c,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(c){return nm({candidate:r,plan:t.plan,failedStage:"commit",error:c,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let s=r;try{let c=await e.validateCandidate({candidate:r,plan:t.plan,receipt:i});c!==void 0&&(s=c)}catch(c){return nm({candidate:r,plan:t.plan,failedStage:"validate",error:c,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let a;try{a=await e.publishCandidate({candidate:s,plan:t.plan,history:o,receipt:i})}catch(c){return nm({candidate:s,plan:t.plan,failedStage:"publish",error:c,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let l={candidate:s,plan:t.plan,history:o,receipt:i,published:a};try{await e.swapCandidate?.(l)}catch(c){return wv("swap",c,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(l)}catch(c){return wv("finalize",c,"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 BM(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 nm(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:jM(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 wv(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function jM(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 $M(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)||Tv.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Tv.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 UM=50,VM=8*1024*1024;function Mv(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??UM),s=Math.max(0,t.maxUndoBytes??VM);return{prepareRewritePlan:a,execute:l,executeFilePlan:c,undo:u,redo:d};async function a(I){let C=[...I.steps].sort((M,G)=>M.order-G.order),N=C.filter(M=>M.type!=="invoke-external-adapter");if(N.length!==C.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let w=new Set(N.map(M=>M.file)),L=await E(w),D=new Map(L.map(M=>[M.file,M.exists===!1?"":M.content])),U;for(let M of N){let G=Dv(M,D.get(M.file)??"");if(!G.ok)return{ok:!1,errorCode:G.errorCode,reason:G.reason};D.set(M.file,G.source),U=G.selectionRef??U}return{ok:!0,filePlan:{operationId:I.operationId,kind:"source-edit",target:I.target,documentVersion:I.documentVersion,conflictPolicy:"compare-and-swap",edits:[...D].map(([M,G])=>({operation:"upsert",file:M,content:G,baseContentHash:L.find(K=>K.file===M)?.sha256??null}))},...U?{selectionRef:U}:{}}}async function l(I){let C=[...I.steps].sort((K,ge)=>K.order-ge.order),N=C.filter(K=>K.type!=="invoke-external-adapter"),w=C.filter(K=>K.type==="invoke-external-adapter"),L=new Set(N.map(K=>K.file));if(N.length>0&&w.length>0)return{ok:!1,operationId:I.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(N.length===0)return h(I,w);let D=await E(L),U=new Map;for(let K of D)U.set(K.file,K.exists===!1?"":K.content);let M;for(let K of N){let ge=U.get(K.file)??"",oe=Dv(K,ge);if(!oe.ok)return{ok:!1,operationId:I.operationId,errorCode:oe.errorCode,reason:oe.reason,rolledBack:!1};U.set(K.file,oe.source),oe.selectionRef&&(M=oe.selectionRef)}let G=await S([...U].map(([K,ge])=>({file:K,content:ge,exists:!0,version:0,sha256:Te(ge)})),D);return G.ok===!1?{ok:!1,operationId:I.operationId,errorCode:G.rolledBack?"writeback-failed":"rollback-failed",reason:G.reason,rolledBack:G.rolledBack}:(n.push({operationId:I.operationId,preSnapshots:D,postSnapshots:G.snapshots,plan:I}),f(),r.length=0,{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:Math.max(...G.snapshots.map(K=>K.version)),affectedFiles:[...L],...M?{selectionRef:M}:{}})}async function c(I){let C=new Set(I.edits.map(G=>G.file)),N=await E(C),w=x(I,N);if(w)return{ok:!1,operationId:I.operationId,errorCode:"stale-version",reason:w.reason,affectedFiles:[w.file],rolledBack:!1};let L=new Map(N.map(G=>[G.file,G])),D=I.edits.find(G=>G.operation==="create-only"&&L.get(G.file)?.exists!==!1);if(D)return{ok:!1,operationId:I.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${D.file}`,affectedFiles:[D.file],rolledBack:!1};let U=I.edits.map(G=>G.operation==="delete"?{file:G.file,content:"",exists:!1,version:0}:{file:G.file,content:G.content,exists:!0,version:0,sha256:Te(G.content)}),M=await S(U,N,new Set(I.edits.filter(G=>G.operation==="create-only").map(G=>G.file)));return M.ok===!1?{ok:!1,operationId:I.operationId,errorCode:M.rolledBack?"writeback-failed":"rollback-failed",reason:M.reason,rolledBack:M.rolledBack}:(n.push({operationId:I.operationId,preSnapshots:N,postSnapshots:M.snapshots,plan:{operationId:I.operationId,kind:I.kind,target:I.target,documentVersion:I.documentVersion,steps:[],preSnapshots:N}}),f(),r.length=0,{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:Math.max(...M.snapshots.map(G=>G.version)),affectedFiles:[...C]})}async function u(){let I=n.at(-1);if(!I)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let C=await S(I.preSnapshots,I.postSnapshots);return C.ok===!1?{ok:!1,operationId:I.operationId,errorCode:C.rolledBack?"writeback-failed":"rollback-failed",reason:C.reason,rolledBack:C.rolledBack}:(n.pop(),r.push(I),{ok:!0,operationId:I.operationId,kind:I.plan.kind,target:I.plan.target,resultVersion:Math.max(...C.snapshots.map(N=>N.version)),affectedFiles:I.preSnapshots.map(N=>N.file)})}async function d(){let I=r.at(-1);if(!I)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let C=await S(I.postSnapshots,I.preSnapshots);return C.ok===!1?{ok:!1,operationId:I.operationId,errorCode:C.rolledBack?"writeback-failed":"rollback-failed",reason:C.reason,rolledBack:C.rolledBack}:(r.pop(),n.push(I),f(),{ok:!0,operationId:I.operationId,kind:I.plan.kind,target:I.plan.target,resultVersion:Math.max(...C.snapshots.map(N=>N.version)),affectedFiles:I.postSnapshots.map(N=>N.file)})}function f(){for(;n.length>i;)n.shift();for(;n.length>0&&g()>s;)n.shift()}function g(){return n.reduce((I,C)=>I+m(C),0)}function m(I){return p(I.preSnapshots)+p(I.postSnapshots)}function p(I){return I.reduce((C,N)=>C+N.file.length+N.content.length,0)}async function h(I,C){let N=[];for(let w of C){let L=w.capability??"write-text",D=o.find(M=>M.sourceType===w.sourceType&&(w.adapterId===void 0||M.adapterId===w.adapterId)&&(M.capabilities===void 0||M.capabilities.includes(L)));if(!D)return{ok:!1,operationId:I.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:I.operationId,errorCode:"writeback-failed",reason:U.reason??`External adapter failed for ${w.sourceType}`,rolledBack:!1};N.push(w.file)}return{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:0,affectedFiles:N}}function x(I,C){if(I.conflictPolicy!=="compare-and-swap")return null;let N=new Map(C.map(w=>[w.file,w]));for(let w of I.edits){if(w.operation==="create-only")continue;if(w.baseContentHash===void 0)return{file:w.file,reason:`Source file ${w.file} is missing baseContentHash. Reopen the file before saving.`};let L=N.get(w.file),D=w.baseContentHash;if(D===null){if(L?.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(L?.exists===!1||L?.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(I){let C=[];for(let N of I)C.push(await b(N));return C}async function b(I){if(!await e.exists(I))return{file:I,content:"",version:0,exists:!1};let N=Math.max(1,e.getVersion(I)),w=await e.readFile(I);return{file:I,content:w,version:N,exists:!0,sha256:Te(w)}}async function S(I,C,N=new Set){let w=[];try{for(let L of I){if(N.has(L.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(L.file,L.content)}else await v(L);let D=e.bumpVersion(L.file);w.push(L.file),L.version=D}}catch(L){let D=await P(C.filter(M=>w.includes(M.file)));if(D.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${D.failedFiles.join(", ")}: ${Lv(L)}`,rolledBack:!1,instanceConflict:Fv(L)};let U=Fv(L);return{ok:!1,reason:`${U?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Lv(L)}`,rolledBack:!0,instanceConflict:U}}return{ok:!0,snapshots:I.map(KM)}}async function v(I){if(I.exists===!1){await e.deleteFile(I.file);return}await e.writeFile(I.file,I.content)}async function P(I){let C=[];for(let N of I)try{await v(N),e.bumpVersion(N.file)}catch{C.push(N.file)}return C.length===0?{ok:!0}:{ok:!1,failedFiles:C}}}function Fv(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function KM(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:Te(e.content)}:{}}}function Lv(e){return e instanceof Error?e.message:String(e)}function Dv(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 Mt(vn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return Mt(Vo({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return Mt(po({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return Mt(Sn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return Mt(Ca({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return Mt(Ji({source:t,locator:e.locator,next:e.value}));case"update-array-item":return Mt(Ji({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return Mt(Fa({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return Mt(Na({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return Mt(La({source:t,locator:e.locator,index:e.index}));case"move-array-item":return Mt(Da({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return Mt(go({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return Mt(Aa({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 JM(e,t);case"set-property-changes":return Mt(Ta({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return Mt(wa({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return Mt(Oa({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return Mt(Ba({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function JM(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!Yh(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!==Te(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:Gh({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function Mt(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 Rl,SiteEditCompositionContextSchema as XM,SiteEditCompositionSelectorSchema as zM}from"@vcp-dev/contracts";var Jt=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function Bv(e,t){throw new Jt("INVALID_COMPOSITION",e,{value:t})}function Pl(e){let t=XM.safeParse(e);return t.success?t.data:Bv("Invalid SiteEditCompositionContext.",e)}function jv(e){let t=[],n=new Map,r=new Map;for(let c of e.compositions){let u=Pl(c?.context);if(typeof c.entryFile!="string"||!c.entryFile)throw new Jt("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Rl(u);if(n.has(d))throw new Jt("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let f=r.get(c.entryFile);if(f)throw new Jt("DUPLICATE_COMPOSITION",`Entry file ${c.entryFile} is registered more than once.`,{entryFile:c.entryFile,context:f});let g={context:u,entryFile:c.entryFile,key:d};t.push(g),n.set(d,g),r.set(c.entryFile,d)}if(t.length===0)throw new Jt("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let c of e.initialDocumentVersions??[]){let u=Pl(c?.composition);if(!Number.isInteger(c?.version)||(c?.version??-1)<0)throw new Jt("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:c?.version});let d=Rl(u);if(!n.has(d))throw new Jt("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new Jt("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:d});o.set(d,c.version)}function i(c){let u=zM.safeParse(c);if(!u.success)return Bv("Invalid SiteEditCompositionSelector.",c);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 Jt("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new Jt("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(c){let u=Pl(c),d=Rl(u),f=n.get(d);if(!f)throw new Jt("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return f}function a(c){let u=Pl(c?.context);if(typeof c.entryFile!="string"||!c.entryFile)throw new Jt("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Rl(u),f=n.get(d);if(f){if(f.entryFile===c.entryFile)return f;throw new Jt("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let g=[...n.values()].find(p=>p.entryFile===c.entryFile);if(g)throw new Jt("DUPLICATE_COMPOSITION",`Entry file ${c.entryFile} is registered more than once.`,{entryFile:c.entryFile,context:g.context});let m={context:u,entryFile:c.entryFile,key:d};return t.push(m),n.set(d,m),m}function l(c){let u=n.get(c);if(!u)return;n.delete(c);let d=t.findIndex(f=>f.key===c);return d>=0&&t.splice(d,1),o.delete(c),u}return{entries:t,byKey:n,initialVersions:o,register:a,unregister:l,resolveSelector:i,resolveContext:s,getByKey:c=>n.get(c),routeIds:()=>[...new Set(t.map(({context:c})=>c.routeId))]}}function om(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 $v(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 l=o++;try{n[l]=await t(e[l])}catch(c){r.push({index:l,error:c})}}}),s=await Promise.allSettled(i),a=r.sort((l,c)=>l.index-c.index)[0];if(a)throw a.error;for(let l of s)if(l.status==="rejected")throw l.reason;return n}import{composeSiteEditRepeatInstanceKey as HM,stripSiteEditRepeatInstanceKeys as Uv}from"@vcp-dev/contracts";function Vv(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Uv(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 WM(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 Cl(e){return e?.map(t=>({...t}))}function im(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=Cl(e.collectionPathMap?.[t])??Cl(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:Cl(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Cl(o)??[])}}function Kv(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)=>HM(g,m),l=(g,m,p)=>{let h=o.get(g);if(!h)return a(g,p);let x=a(g,p),E={...h,key:x,parentKey:m,childKeys:[]};return i.push(E),E.childKeys=h.childKeys.flatMap(b=>c(b,p,x)),x},c=(g,m,p)=>{if(!r.has(g))return[l(g,p,m)];let h=d(g,m),x=[];for(let E=0;E<h;E+=1)x.push(l(g,p,[...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)){l(g,null,[]);continue}let m=d(g,[]);for(let p=0;p<m;p+=1)l(g,null,[p])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(g,m){let p=new Set;for(let h of f(g)){let x=n.get(h);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 GM(E))b.length<=m.length||YM(b,m)&&p.add(b[m.length])}}return p.size>0?p.size:WM(n.get(g))}function f(g){let m=s.get(g);if(m)return m;let p=[g],h=o.get(g);for(let x of h?.childKeys??[])p.push(...f(x));return s.set(g,p),p}}function Jv(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Xv(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((Uv(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function GM(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 YM(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 zv(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 l=i.childKeys.map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label})),c=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:l,siblings:c}}function Hv(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(l=>[l.key,l])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let l=o.get(a);if(!l)break;s.push({key:l.key,tag:l.tag,label:l.label}),a=l.parentKey}return s.reverse(),{...e,key:i.key,ancestors:s}}function Wv(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function ZM(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var Vs=class extends Error{constructor(t){let n=t.map(Wv);super(ZM(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Gv(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof Vs?{routeId:e,message:n,diagnostics:t.diagnostics.map(Wv)}:{routeId:e,message:n}}function sm(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function am(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function Ks(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Yv(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function Nl(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 Zv(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((c,u)=>c.preDigest===r[u]),i=t.files.every((c,u)=>c.postDigest===r[u]),s=t.historyTransition,a=n.digest===s.expectedIndexDigest,l=n.digest===s.publishedIndexDigest&&n.cursor===s.publishedCursor&&n.currentId===s.publishedCurrentId;return o&&a?"safely-uncommitted":i&&l?"durably-committed":"ambiguous"}var iB=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,sB=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],qv=32,Tl=256;function aB(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Qv={maxEntries:50,maxBytes:8*1024*1024};function cB(){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 Ua(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 eI(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 lB(){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>Qv.maxEntries||uB(e)>Qv.maxBytes;)e.shift()}}function uB(e){return e.reduce((t,n)=>t+dB(n),0)}function dB(e){return tI(e.preSnapshots)+tI(e.postSnapshots)+fB(e.provenance)}function fB(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function tI(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function nI(e,t){return{key:QM(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document:null,pageBlockIndex:null,pageComposition:null,pageCompositionProjection:null,documentIndex:null,pagePlacementByKey:null,pagePlacementUnitByKey:null,pageUnitByKey:null,pagePlacementsByUnitKey:null,dependencyFiles:new Set([t]),detailProjections:null,fileVersions:new Map,styleContext:null}}var wl=class extends Error{constructor(t){super(t.reason),this.result=t}},To=class extends Error{constructor(t){super(sm(t)),this.failedRoutes=t}};function rI(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=en(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(en(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function pB(e,t,n){if(!n)return;let r=en(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 mB=/\.(?:[cm]?[jt]sx?)$/i,gB=/\.json$/i,hB=/\.(?:css|scss|sass)$/i,yB=/\.mdx$/i,xB=/\.ya?ml$/i;function bB(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 EB(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function SB(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=lI(await e.listFiles(i)),a=new Map(s.files.map(c=>[c.path,c]));for(let[c,u]of n)if(vB(c,i.roots??[])){if(!u.exists){a.delete(c);continue}a.set(c,{path:c,sizeBytes:Buffer.byteLength(u.content,"utf8")})}let l=[...a.values()].sort((c,u)=>c.path.localeCompare(u.path));return s.truncated?{files:l,truncated:s.truncated}:l},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 lI(e){return Array.isArray(e)?{files:e}:e}function IB(e){if(!tB(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!==rB||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(mB.test(e.path)){let t=Jn({source:e.content,profile:so({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(gB.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Ht(t)}`,details:{path:e.path}}}if(hB.test(e.path)){let t=oI({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(yB.test(e.path)){let t=oI({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(xB.test(e.path))try{oB(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Ht(t)}`,details:{path:e.path}}}return{ok:!0}}function oI({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,l=!1,c=!0;for(let d=0;d<e.length;d+=1){let f=e[d]??"",g=e[d+1]??"";if(n==="mdx"&&c&&e.startsWith("```",d)){l=!l;let m=e.indexOf(`
|
|
8
|
-
`,d);if(
|
|
9
|
-
`||f==="\r";continue}if(s){f==="*"&&
|
|
1
|
+
import*as oC from"@babel/parser";import*as Yt from"@babel/types";import*as Jr from"node:path";var Wu=[".tsx",".ts",".jsx",".js"],iC=Wu.map(e=>`/index${e}`),sC=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 ah(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&sC.has(n[1].toLowerCase())}function ch(e){let t=[];for(let n of e.program.body)Yt.isImportDeclaration(n)&&typeof n.source.value=="string"&&kt(n.source.value)&&t.push(n.source.value),Yt.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&kt(n.source.value)&&t.push(n.source.value),Yt.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&kt(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)&&kt(r.value)&&t.push(r.value)}),t}function kt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function rr(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=Jr.dirname(e);return Jr.join(n,t).replace(/\\/g,"/")}async function aC(e,t){for(let n of lh(e))if(await t(n))return n;return null}function lh(e){return[...Wu.some(t=>e.endsWith(t))?[e]:[],...Wu.map(t=>`${e}${t}`),...iC.map(t=>`${e}${t}`)]}function Xr(e,t,n){let r=rr(e,t);if(!kt(t)||!uh(e,t,r))return null;for(let o of lh(r))if(n.has(o))return o;return null}async function _o(e,t,n){let r=await Ja(e,t,n);return r.ok?r.path:null}async function Ja(e,t,n){let r=rr(e,t);try{if(!uh(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 aC(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 uh(e,t,n){if(!kt(t)||t.includes("\0")||t.includes("\\")||Jr.posix.isAbsolute(n))return!1;let r=Jr.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!Jr.posix.isAbsolute(e)}import{createHash as lC}from"node:crypto";import*as dh from"@babel/parser";function Co(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function le(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Co(t,n,r,o)}}function Gu(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Co(t,n,r,o)}}var cC={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function or(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:dh.parse(t,{sourceType:"module",plugins:cC[n]})}}catch(r){return{ok:!1,source:t,diagnostic:Co("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Yu(e,t){return or({source:e,profile:fh(t.kind)})}function as(e,t){return or({source:e,profile:fh(t)})}function fh(e){return"next-app-entry"}function Ro(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 Te=(e,t)=>{let n=or({source:t,profile:Ro({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${lC("sha256").update(t).digest("hex")}`,ast:n.ast,imports:ch(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function uC(e,t){return Te(e,t)}function dC(e,t){return rr(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as fC,parseComponentI18nResourcesJson as pC,resolveSiteTextDirection as mC,SiteLocaleSchema as gC}from"@vcp-dev/contracts";var hC=["i18next","react-i18next"],yC="components/ui/site-locale-provider.tsx",xC="components/ui/component-i18n-provider.tsx",ph="app/layout.tsx";async function cs(e){let t=e.files.filter(f=>f.path.endsWith(fC));if(t.length===0)return{ok:!0};for(let f of["package.json",ph,yC,xC])if(!await e.exists(f))return zr(`Target snapshot is missing required i18n host file: ${f}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return zr("Target snapshot package.json is invalid.")}let r=mh(n)&&mh(n.dependencies)?n.dependencies:{},o=hC.filter(f=>typeof r[f]!="string"||r[f].trim().length===0);if(o.length>0)return zr(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(ph),s=Zu(i,"html","lang"),a=Zu(i,"html","dir"),l=Zu(i,"SiteLocaleProvider","locale"),c=gC.safeParse(s);if(!c.success||!a||!l||s!==l||a!==mC(c.data))return zr("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 zr("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=c.data;if(e.targetLocale&&e.targetLocale!==u)return zr("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let f of t){let m=pC(f.content);if(!m.success)return zr(`Component i18n resource is invalid: ${f.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(m.data,u)&&!Object.hasOwn(m.data,d))return zr(`Component i18n resource ${f.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function Zu(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 mh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zr(e){return{ok:!1,message:e}}import Qu from"@babel/generator";import*as Eh from"@babel/parser";import ed from"@babel/traverse";import*as dt from"@babel/types";import{computeSiteEditSourceIdentityKey as EC}from"@vcp-dev/contracts";var gh="data-vcp-ui-component",Xa="components/ui";function Cr(e){if(!e)return!1;let t=qu(e);return t===Xa||t.startsWith(`${Xa}/`)||t.includes(`/${Xa}/`)||t.endsWith(`/${Xa}`)}function Po(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Cr(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Cr(qu(`${bC(t)}/${e}`)):Cr(e):!1}function qu(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 bC(e){let t=qu(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as XV}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as HV,isSiteEditRuntimeTextTag as WV}from"@vcp-dev/contracts/site-edit-runtime-capability";var hh={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 SC=typeof Qu=="function"?Qu:Qu.default,IC=typeof ed=="function"?ed:ed.default,vC=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),kC="suppressHydrationWarning",_C=new Set(["SiteEditBootstrap"]);function CC(e){let t=NC(e.file,e.projectRoot);if(!PC(e.source)||Cr(t))return{code:e.source,elements:[]};let n=e.attributes??hh,r=Eh.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=TC(r,t);return IC(r,{JSXElement(s){let a=s.node.openingElement,l=a.name;if(!OC(l)||Sh(a,n.key))return;let c=FC(s)??"default",u=MC(s),d=EC(t,c,u),f=Ha(l)??"unknown",m=AC(l)?"jsx":"component-call";if(m==="component-call"&&!DC(s.node.children)&&_C.has(f))return;let g=m==="component-call"&&wC(f,i);LC(a,n.key,d),g&&yh(a,gh),RC(s)&&yh(a,kC),o.push({key:d,tag:f,componentName:c,sourceFile:t,sourceKind:m})}}),o.length===0?{code:e.source,elements:o}:{code:SC(r,{jsescOption:{minimal:!0}}).code,elements:o}}function RC(e){return!e.findParent(t=>t.isJSXElement())}function PC(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function NC(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 AC(e){return dt.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function Ha(e){return dt.isJSXIdentifier(e)?e.name:dt.isJSXMemberExpression(e)?vh(e):null}function TC(e,t){let n=new Set;for(let r of e.program.body)if(!(!dt.isImportDeclaration(r)||!Po(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function wC(e,t){let n=e.split(".")[0]??e;return t.has(n)}function OC(e){let t=Ha(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!vC.has(t)}function Sh(e,t){return e.attributes.some(n=>dt.isJSXAttribute(n)&&dt.isJSXIdentifier(n.name,{name:t}))}function LC(e,t,n){Ih(e,dt.jsxAttribute(dt.jsxIdentifier(t),dt.stringLiteral(n)))}function yh(e,t){Sh(e,t)||Ih(e,dt.jsxAttribute(dt.jsxIdentifier(t),null))}function Ih(e,t){let n=e.attributes.findIndex(r=>dt.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function vh(e){return`${dt.isJSXIdentifier(e.object)?e.object.name:vh(e.object)}.${e.property.name}`}function FC(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&dt.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 DC(e){return e.some(t=>dt.isJSXElement(t)||dt.isJSXFragment(t))}var xh=new WeakMap,za=new WeakMap,td=new WeakMap;function MC(e){let t=xh.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=BC(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return xh.set(e.node,o),o}function BC(e){let t=Ha(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${bh(e,t)}`:`${t}#${bh(e,t)}`}function bh(e,t){let n=kh(e)??e.getFunctionParent();if(!n)return 0;let r=td.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=td.get(n.node);o||(o=new Map,td.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()?Wa(n):jC(n);for(let l of a)if(Ha(l.node.openingElement.name)===t){if(i.set(l.node,s),l.node===e.node)return s;s+=1}return i.get(e.node)??0}function jC(e){let t=za.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!kh(r)&&n.push(r)}}),za.set(e.node,n),n}function kh(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 Wa(e){let t=za.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(...Wa(o));continue}o.isJSXExpressionContainer()&&n.push(...No(o.get("expression")))}return za.set(e.node,n),n}function No(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return Wa(e);if(e.isParenthesizedExpression())return No(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return No(e.get("right"));if(e.isConditionalExpression())return[...No(e.get("consequent")),...No(e.get("alternate"))];if(e.isCallExpression()&&UC(e.node)){let t=e.get("arguments")[0];return $C(t)}return[]}function $C(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return Wa(t);if(t.isParenthesizedExpression())return No(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?No(r):[]}return[]}function UC(e){return dt.isMemberExpression(e.callee)&&dt.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as oj,SiteEditPatchPlanSchema as ij}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 Ga(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 Ya(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 Za(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:VC(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 qa(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 VC(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 gB,computeSiteEditCompositionKey as hB,getSiteEditSourceDeleteProtectionReason as yB,isSiteEditTextSourcePath as xB,parseSiteEditRepeatInstanceKey as bB,SITE_EDIT_SOURCE_DELETE_CAPABILITY as EB,stripSiteEditRepeatInstanceKeys as pn}from"@vcp-dev/contracts";import uu from"node:path";import{parse as SB}from"yaml";import sd from"node:path";import{TextDecoder as JC}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Ch,SITE_EDIT_SOURCE_ALLOWED_DIRS as Rh,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Ph,SiteEditCompositionContextSchema as XC,SiteEditSourceFileResponseSchema as nd,SiteEditSourceLocationSchema as zC,SiteEditSourcePathSchema as Qa,SiteEditSourceTreeResponseSchema as HC,isSiteEditTextSourcePath as WC}from"@vcp-dev/contracts";import{createHash as KC}from"node:crypto";var ls=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(l=>a===l||a.startsWith(`${l}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let l=Buffer.byteLength(this.files.get(a)??"","utf8"),c=a.split("/").length;if(t.maxDepth!==void 0&&c>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+l>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:l}),s+=l}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function je(e){return`sha256:${KC("sha256").update(e).digest("hex")}`}var GC=[...Ph,...Ch,...Rh];function ad(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return XC.parse(e.composition)}var rd=2e3,od=12,id=24*1024*1024,_h=512*1024,YC=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),ZC={".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"},qC={".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"},QC=new JC("utf-8",{fatal:!0});async function ec(e,t={}){let n=ad(t),{files:r,truncated:o}=await sR(e,t),i=lR(r.map(s=>s.metadata));return HC.parse({composition:n,nodes:i,defaultPath:uR(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function tc(e,t,n={}){let r=ad(n),o=Qa.parse(t.path),i=await tR(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(ld(o)){let a=Th(o),l=await rR(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return nd.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...l})}let s=await cd(e,o);return s.ok?nd.parse({composition:r,path:o,kind:"text",language:wh(o),sizeBytes:s.sizeBytes,contentHash:je(s.content),readonly:!1,content:s.content}):nd.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function cd(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=eR(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 eR(e){if(e.includes(0))return null;try{return QC.decode(e)}catch{return null}}async function tR(e,t,n){if(!oR(t,n))return null;let r=await nR(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function nR(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(ld(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function rR(e,t){if(!YC.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>_h)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>_h?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function oR(e,t){return Ph.some(n=>n===e)||Ch.some(n=>n===e)||Rh.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Qa.safeParse(n);return r.success&&r.data===e})}function nc(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return zC.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 iR(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function sR(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Nh(await e.listFiles({roots:aR(t),maxFiles:rd+1,maxDepth:od,maxTotalBytes:id+1})),r=new Map,o=new Set(n.truncated?.reasons),i=0;for(let a of[...n.files].sort((l,c)=>l.path.localeCompare(c.path))){let l=Qa.safeParse(a.path);if(!l.success)continue;let c=l.data;if(c.split("/").length>od){o.add("max-depth");continue}if(r.size>=rd){o.add("max-files");break}if(i+a.sizeBytes>id){o.add("max-total-bytes");break}r.set(c,{path:c,sizeBytes:a.sizeBytes,metadata:cR(c,a.sizeBytes,ad(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,l)=>a.path.localeCompare(l.path)),...o.size>0?{truncated:{reasons:iR([...o]),maxFiles:rd,maxDepth:od,maxTotalBytes:id}}:{}}}function aR(e){let t=new Set(GC);for(let n of e.routeEntryFiles??[]){let r=Qa.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function cR(e,t,n){return ld(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Th(e),readonly:!0}:{composition:n,path:e,kind:"text",language:wh(e),sizeBytes:t,readonly:!1}}function lR(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 l=s===r.length-1,c=o.find(u=>u.name===a);if(c||(c=l?{kind:"file",name:a,path:i,file:n}:{kind:"directory",name:a,path:i,children:[]},o.push(c)),l){if(c.kind!=="file")throw new Error(`Source tree path collision: ${n.path}`);c.file=n}else{if(c.kind!=="directory")throw new Error(`Source tree path collision: ${n.path}`);o=c.children}}}return Ah(t)}function Ah(e){return e.map(t=>t.kind==="directory"?{...t,children:Ah(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function uR(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 ld(e){return!WC(e)}function Th(e){let t=sd.posix.extname(e).toLowerCase();return!t&&sd.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":ZC[t]??"application/octet-stream"}function wh(e){let t=sd.posix.extname(e).toLowerCase();return qC[t]??"plaintext"}import*as wo from"@babel/types";import ud from"@babel/traverse";import*as ir from"@babel/types";function gt(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(ir.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(ir.isIdentifier(s)&&s.name==="Fragment"||ir.isStringLiteral(s)&&s.value==="Fragment")&&Oh(i.parentPath)}if(!ir.isJSXMemberExpression(t)||!ir.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!ir.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())&&Oh(r.parentPath)}function Oh(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var Hr=typeof ud=="function"?ud:ud.default,rc=new WeakMap,oc=new WeakMap;function sr(e,t){let n=Yu(e,t);if(!n.ok)return Gu(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=De(n.ast,t);return r.ok?{ok:!0,match:{locatorKind:r.match.locatorKind,node:r.match.node,start:r.match.start,end:r.match.end}}:Gu(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function De(e,t){return t.kind==="jsx-node"?Mh(e,t):t.kind==="jsx-attribute"?hR(e,t):t.kind==="value"?yR(e,t):t.kind==="expression"?xR(e,t):t.kind==="directive"?bR(e,t):t.kind==="export"?ER(e,t):{ok:!1,diagnostic:Co("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Mh(e,t){return t.strategy==="source-range"?dR(e,t):fR(e,t)}function dR(e,t){let n=null;if(Hr(e,{JSXElement(o){if(!To(o.node,t.sourceRange))return;let i=Pt("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!To(o.node,t.sourceRange))return;let i=Pt("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!To(o.node,t.sourceRange))return;let i=Pt("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!To(o.node,t.sourceRange))return;let i=Pt("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Dt("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!wR(r.path,t.expectedIdentity)?Dt("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function fR(e,t){if(t.structuralPath===""){let r=mR(e,t.component);if(r){let o=gR(r);if(o)return o}}let n=null;return Hr(e,{JSXElement(r){if(ds(r)!==t.component||fd(r)!==t.structuralPath)return;let i=Pt("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(ds(r)!==t.component||fd(r)!==t.structuralPath)return;let i=Pt("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=pR(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Dt("jsx-node","locator-miss","JSX node not found for structural-path locator")}function pR(e,t,n){let r=null;return Hr(e,{JSXElement(o){if(ds(o)!==t||!To(o.node,n))return;let i=Pt("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(ds(o)!==t||!To(o.node,n))return;let i=Pt("jsx-node",o);i&&(r=i,o.stop())}}),r}function mR(e,t){let n=null;return Hr(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 gR(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 Dt("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Dt("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 Dt("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function hR(e,t){let n=Mh(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(l=>OR(l,t.name));if(!s||!s.isJSXAttribute())return Dt("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Pt("jsx-attribute",s);return a?{ok:!0,match:a}:Dt("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function yR(e,t){let n=SR(e,t);if(!n.ok)return n;let r=IR(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Pr(r.match.path.node.loc,t.expectedRange)?Dt("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function xR(e,t){let n=null;return Hr(e,{Identifier(r){if(!PR(r))return;let o=Fh(r);if(!o||!Dh(o,t))return;let i=Pt("expression",r);i&&(t.expectedRange&&!Pr(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Fh(r);if(!o||!Dh(o,t))return;let i=Pt("expression",r);i&&(t.expectedRange&&!Pr(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Dt("expression","locator-miss","Expression not found")}function bR(e,t){let n=null;return Hr(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Pr(i.node.loc,t.expectedRange))return;let s=Pt("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Dt("directive","locator-miss",`Directive '${t.value}' not found`)}function ER(e,t){let n=null;return Hr(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let l=r.get("declaration");if(l.isFunctionDeclaration()&&l.node.id?.name==="generateMetadata"){let f=Pt("export",l);if(!f||t.expectedRange&&!Pr(l.node.loc,t.expectedRange))return;n=f,r.stop();return}if(!l.isVariableDeclaration())return;let c=pd(l,"generateMetadata");if(!c||!c.isVariableDeclarator())return;let u=c.get("init");if(!u.node)return;let d=Pt("export",u);if(!d||t.expectedRange&&!Pr(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=pd(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Pr(s.node.loc,t.expectedRange))return;let a=Pt("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Pt("export",o);i&&(t.expectedRange&&!Pr(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Dt("export","export-not-found",`Export '${TR(t)}' not found`)}function SR(e,t){let n=null;return Hr(e,{Expression(r){if(n||t.root.kind!=="expression"||!To(r.node,t.root.sourceRange))return;let o=Pt("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 m=r.get("init");if(!m.node)return;let g=Pt("value",m);if(!g)return;n=g,r.stop();return}if(t.root.kind!=="hook-state")return;let o=t.root,i=r.get("id"),s=r.get("init");if(!i.isArrayPattern()||!s.isCallExpression()||i.node.elements.findIndex(m=>m?.type==="Identifier"&&m.name===o.name)!==0)return;let l=s.node.callee;if((l.type==="Identifier"?l.name:l.type==="MemberExpression"&&l.property.type==="Identifier"?l.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=Pt("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=pd(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Pt("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Pt("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:Dt("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 IR(e,t){let n=dd(e);for(let o of t){if(n=dd(n),o.kind==="property"){if(!n.isObjectExpression())return Dt("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(c=>!c.isObjectProperty()))return Dt("value","unsupported-syntax","Spread properties are not supported");let l=a.find(c=>LR(c,o.name));if(!l||!l.isObjectProperty())return Dt("value","property-not-found",`Property '${o.name}' not found`);n=l.get("value");continue}if(!n.isArrayExpression())return Dt("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return Dt("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return Dt("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=dd(n);let r=Pt("value",n);return r?{ok:!0,match:r}:Dt("value","locator-miss","Resolved value has no source range")}function dd(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Pt(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 To(e,t){return Pr(e.loc,t)}function Pr(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 fd(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!gt(n)){let o=jh(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Lh(n,o)}`):t.unshift(`${o}#${Lh(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||CR(n.parentPath)&&!RR(n.parentPath))break;n=n.parentPath}return t.join("/")}function Lh(e,t){let n=Bh(e)??e.getFunctionParent();if(!n)return 0;let r=rc.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=rc.get(n.node)?.get(t);if(!i){let a=rc.get(n.node);a||(a=new Map,rc.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?us(n):vR(n);for(let a of s)if(jh(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function vR(e){let t=oc.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Bh(r)&&n.push(r)}}),oc.set(e.node,n),n}function Bh(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(gt(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function us(e){let t=oc.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(gt(o)){n.push(...us(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...us(o));continue}o.isJSXExpressionContainer()&&n.push(...Rr(o.get("expression")))}return oc.set(e.node,n),n}function Rr(e){if(e.isJSXElement())return gt(e)?us(e):[e];if(e.isJSXFragment())return us(e);if(e.isParenthesizedExpression())return Rr(e.get("expression"));if(e.isLogicalExpression()&&kR(e.node.operator))return Rr(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 l=a.get("init");(l.isJSXElement()||l.isJSXFragment())&&i.push(...Rr(l))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Rr(a));break}}return i}else if(o.node&&o.isExpression())return Rr(o)}}}}return e.isConditionalExpression()?[...Rr(e.get("consequent")),...Rr(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Rr(t)):[]}function kR(e){return e==="&&"||e==="||"||e==="??"}function jh(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?_R(e.name):null}function _R(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 ds(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 CR(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function RR(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 PR(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Fh(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 Dh(e,t){return e.base===t.base&&NR(e.path,t.path??[])}function NR(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 AR(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function TR(e){return e.exportKind==="named"?e.name:e.exportKind}function Dt(e,t,n,r){return{ok:!1,diagnostic:Co(t,n,e,r)}}function wR(e,t){return ds(e)!==t.component?!1:fd(e)===t.structuralPath}function OR(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function pd(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function LR(e,t){return e.isObjectProperty()?AR(e.node)===t:!1}import*as Uh from"@babel/parser";import{arrayExpression as jR,booleanLiteral as $R,identifier as UR,jsxAttribute as VR,jsxExpressionContainer as KR,jsxIdentifier as JR,nullLiteral as XR,numericLiteral as zR,objectExpression as HR,objectProperty as WR,stringLiteral as gd}from"@babel/types";import md from"@babel/generator";var FR=typeof md=="function"?md:md.default;function DR(e){let t=e.split(`
|
|
2
|
+
`),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let l=a[1];l.includes(" ")?r=!0:l.length>0&&n.push(l.length)}}if(r&&t.every(a=>{let l=a.match(/^(\s+)/);return!l||l[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 MR(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 BR(e,t){return e.split(`
|
|
3
|
+
`).map(r=>MR(r,t)).join(`
|
|
4
|
+
`)}function ic(e){let{ast:t,source:n}=e;try{let r=DR(n),i=FR(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=BR(i,r)),{ok:!0,source:i}}catch(r){return le(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function $h(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 fs(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:$h(e),afterSourceHash:$h(t),inverse:n.inverse}}}function et(e,t,n){let r=ic({ast:e,source:t});return r.ok?fs(t,r.source,n):r}function ft(e,t){let n=as(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function sc(e,t){return ic({ast:e,source:t})}function GR(e,t,n){let r=De(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function si(e,t,n){let r=GR(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:le(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function Wr(e){return typeof e=="string"?gd(e):typeof e=="number"?zR(e):typeof e=="boolean"?$R(e):e===null?XR():Array.isArray(e)?jR(e.map(t=>Wr(t))):HR(Object.entries(e).map(([t,n])=>{let r=WR(hd(t),Wr(n));return t==="__proto__"&&(r.computed=!0),r}))}function YR(e){return typeof e=="string"?gd(e):KR(Wr(e))}function ps(e,t){return VR(JR(e),YR(t))}function ac(e,t){try{let r=Uh.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:le(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:le(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function hd(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?UR(e):gd(e)}function cc(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=ft(t,"jsx-node");if(!i.ok)return i.result;let s=De(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let l=ZR(s.match.path)[r];if(!l)return le(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(l.kind){case"jsx-text":{let c=l.path.node.value;if(o.trim().length===0){let d=c.match(/^\s*/)?.[0]??"",f=c.match(/\s*$/)?.[0]??"";l.path.replaceWithMultiple([...d?[wo.jsxText(d)]:[],wo.jsxExpressionContainer(wo.stringLiteral("")),...f?[wo.jsxText(f)]:[]]);break}let u=qR(c,o);l.path.node.value=u,l.path.node.extra={rawValue:u,raw:u.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/{/g,"{").replace(/}/g,"}")};break}case"string-literal":l.path.node.value=o;break;case"template-literal":{let c=l.quasiIndex;l.path.node.quasis[c].value.raw=o.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${").replace(/\r/g,"\\r"),l.path.node.quasis[c].value.cooked=o;break}}return et(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function ZR(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=QR(r.get("expression"));o.length>0&&t.push(...o)}}return t}function qR(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function QR(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 yd}from"@babel/types";function Oo(e){let{source:t,locator:n}=e,r=ft(t,"jsx-node");if(!r.ok)return r.result;let o=De(r.ast,n);return o.ok?(eP(o.match.path),et(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function eP(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(yd());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(yd());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(yd());return}e.remove()}import{cloneNode as tP}from"@babel/types";function ai(e){let t=ft(e.source,"jsx-node");if(!t.ok)return t.result;let n=De(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=ac(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(tP(r.node,!0)),et(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as fP}from"@babel/types";import xd from"@babel/traverse";import*as _e from"@babel/types";function ms(e,t,n){return`${e}::${t}::${n}`}var G={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 nP=typeof xd=="function"?xd:xd.default;function Ln(e,t,n,r){if(!e.ok)return e;let o=On(n,t);if(!o)return e;let i=rP(t,o,r);return i?{...e,selectionRef:i}:e}function rP(e,t,n){let r=oP(e,t);if(!r)return;let o=n.sourceLocator?Vh(n.sourceLocator):void 0,i=n.targetParentLocator?Vh(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??sP(r)??i?.component??o?.component;if(!(!s||!a))return{key:ms(s,a,aP(r))}}function Vh(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function oP(e,t){let n=Wh(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Wh(e,t){let n=null;return nP(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function On(e,t){if(!e)return null;if(_e.isJSXElement(e))return dP(t,e)?Kh(e.children,t):e;if(_e.isJSXFragment(e))return Kh(e.children,t);if(_e.isJSXExpressionContainer(e)||_e.isParenthesizedExpression(e)||_e.isTSAsExpression(e)||_e.isTSSatisfiesExpression(e)||_e.isTSTypeAssertion(e)||_e.isTSNonNullExpression(e))return On(e.expression,t);if(_e.isLogicalExpression(e))return On(e.right,t);if(_e.isConditionalExpression(e))return On(e.consequent,t)??On(e.alternate,t);if(_e.isCallExpression(e)||_e.isOptionalCallExpression(e))return Gh(e)?iP(e.arguments[0],t):null;if(_e.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=On(n,t);if(r)return r}return null}function Kh(e,t){for(let n of e){let r=On(n,t);if(r)return r}return null}function iP(e,t){return!e||!_e.isArrowFunctionExpression(e)&&!_e.isFunctionExpression(e)?null:_e.isBlockStatement(e.body)?gs(e.body.body,t):On(e.body,t)}function gs(e,t){for(let n of e){if(_e.isReturnStatement(n)){let r=On(n.argument,t);if(r)return r;continue}if(_e.isBlockStatement(n)){let r=gs(n.body,t);if(r)return r;continue}if(_e.isIfStatement(n)){let r=Jh(n.consequent,t);if(r)return r;let o=n.alternate?Jh(n.alternate,t):null;if(o)return o;continue}if(_e.isSwitchStatement(n))for(let r of n.cases){let o=gs(r.consequent,t);if(o)return o}}return null}function Jh(e,t){return _e.isBlockStatement(e)?gs(e.body,t):gs([e],t)}function sP(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(_e.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&_e.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 Xh=new WeakMap,zh=new WeakMap,bd=new WeakMap;function aP(e){let t=Xh.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=cP(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Xh.set(e.node,o),o}function cP(e){let t=Yh(e.node.openingElement.name);return!t||gt(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Hh(e,t)}`:`${t}#${Hh(e,t)}`}function Hh(e,t){let n=lP(e);if(!n)return 0;let r=bd.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=bd.get(n.node);o||(o=new Map,bd.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Lo(n))if(Yh(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 lP(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(gt(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Lo(e){let t=zh.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(gt(o)){n.push(...Lo(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Lo(o));continue}o.isJSXExpressionContainer()&&n.push(...ar(o.get("expression")))}return zh.set(e.node,n),n}function ar(e){if(e.isJSXElement())return gt(e)?Lo(e):[e];if(e.isJSXFragment())return Lo(e);if(e.isParenthesizedExpression())return ar(e.get("expression"));if(e.isLogicalExpression())return ar(e.get("right"));if(e.isConditionalExpression())return[...ar(e.get("consequent")),...ar(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:ar(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Gh(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?uP(n):[]}return[]}function uP(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return gt(t)?Lo(t):[t];if(t.isJSXFragment())return Lo(t);if(t.isParenthesizedExpression())return ar(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return ar(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(...ar(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...ar(o)),n}return n}function Gh(e){let t=e.callee;return(_e.isMemberExpression(t)||_e.isOptionalMemberExpression(t))&&_e.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function dP(e,t){let n=Wh(e,t);return n?gt(n):!1}function Yh(e){return _e.isJSXIdentifier(e)?e.name:_e.isJSXMemberExpression(e)?Zh(e):_e.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Zh(e){return`${_e.isJSXIdentifier(e.object)?e.object.name:Zh(e.object)}.${e.property.name}`}function Gr(e,t){if(t.parentPath===e&&t.listKey==="children"&&Ed(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!Ed(n))return null;let r=n;for(;r&&r!==e;){if(!Ed(r)||!gt(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function Ed(e){return e.isJSXElement()||e.isJSXFragment()}function Fn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ft(t,"jsx-node");if(!a.ok)return a.result;let l=De(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return le(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let c=l.match.path;if(l.match.path.isJSXElement()){let E=l.match.path.node;if(!E.closingElement||E.openingElement.selfClosing)return le(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=ac(t,r.jsx);if(!u.ok)return u.result;let d=fP(u.node,!0),f=c.node.children,m={...s,targetParentLocator:n},g=E=>s?Ln(E,a.ast,d,m):E;if(o==="append")return f.push(d),g(et(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return f.unshift(d),g(et(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return le(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=De(a.ast,i);if(!p.ok)return{ok:!1,source:t,diagnostic:p.diagnostic};let h=Gr(l.match.path,p.match.path);if(!h)return le(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");c=h;let x=c.node.children,b=x.findIndex(E=>E===p.match.path.node);return b===-1?le(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?b:b+1,0,d),g(et(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as qh from"@babel/parser";import{cloneNode as pP}from"@babel/types";function lc(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ft(t,"jsx-node");if(!a.ok)return a.result;let l=mP(t,r);if(!l.ok)return l.result;let c=De(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return le(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(c.match.path.isJSXElement()){let x=c.match.path.node;if(!x.closingElement||x.openingElement.selfClosing)return le(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=c.match.path,d=null;if(i){let x=De(a.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let b=Gr(c.match.path,x.match.path);if(!b)return le(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=b,d=x.match.path.node}else if(o==="before"||o==="after")return le(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=pP(l.node,!0),m=u.node.children,g={...s,targetParentLocator:n},p=x=>s?Ln(x,a.ast,f,g):x;if(o==="append")return m.push(f),p(et(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(f),p(et(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let h=m.findIndex(x=>x===d);return h===-1?le(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(m.splice(o==="before"?h:h+1,0,f),p(et(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function mP(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:le(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:le(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as gP,nullLiteral as Sd}from"@babel/types";import*as Yr from"@babel/types";import*as Qh from"@babel/types";function hs(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!Qh.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function Fo(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ft(t,"jsx-node");if(!a.ok)return a.result;let l=De(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};let c=De(a.ast,r);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return le(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let u=c.match.path;if(c.match.path.isJSXElement()){let E=c.match.path.node;if(!E.closingElement||E.openingElement.selfClosing)return le(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let E=De(a.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let S=E.match.path.isJSXElement()?hs(E.match.path,c.match.path):E.match.path,v=Gr(c.match.path,S);if(!v)return le(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 le(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=d&&typeof d.key=="number"?d.key:-1;if(d&&f===-1)return le(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let m=l.match.path.isJSXElement()?hs(l.match.path,c.match.path):l.match.path,g=gP(m.node,!0);if(!Yr.isJSXElement(g)&&!Yr.isJSXExpressionContainer(g)&&!Yr.isJSXFragment(g)&&!Yr.isJSXText(g))return le(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let p=m.parentPath?.node===u.node&&typeof m.key=="number"?m.key:-1;if(d&&m.parentPath?.node===d.parentPath?.node&&m.key===d.key)return le(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");hP(m);let h=u.node.children,x={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return h.push(g),Ln(sc(a.ast,t),a.ast,g,x);if(o==="prepend")return h.unshift(g),Ln(sc(a.ast,t),a.ast,g,x);let b=f-(p!==-1&&p<f?1:0);return h.splice(o==="before"?b:b+1,0,g),Ln(sc(a.ast,t),a.ast,g,x)}function hP(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Sd());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Sd());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Sd());return}e.remove()}import*as ey from"@babel/parser";import{cloneNode as yP,nullLiteral as Id}from"@babel/types";function uc(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,l=ft(t,"jsx-node");if(!l.ok)return l.result;let c=xP(t,s);if(!c.ok)return c.result;let u=De(l.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=De(l.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return le(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let E=d.match.path.node;if(!E.closingElement||E.openingElement.selfClosing)return le(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let f=d.match.path,m=null;if(i){let E=De(l.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let S=Gr(d.match.path,E.match.path);if(!S)return le(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");f=S,m=E.match.path.node}else if(o==="before"||o==="after")return le(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return le(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=f.node,p=yP(c.node,!0);bP(u.match.path);let h={...a,sourceLocator:n,targetParentLocator:r},x=g.children;if(o==="append")return x.push(p),Ln(et(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,p,h);if(o==="prepend")return x.unshift(p),Ln(et(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,p,h);let b=x.findIndex(E=>E===m);return b===-1?le(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?b:b+1,0,p),Ln(et(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,p,h))}function xP(e,t){try{let r=ey.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:le(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:le(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function bP(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Id());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Id());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Id());return}e.remove()}import{SiteEditSetPropsParamsSchema as EP,classifySiteEditPropertyName as SP}from"@vcp-dev/contracts";import*as ci from"@babel/types";function dc(e){let t=EP.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return le(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=ft(e.source,"jsx-node");if(!n.ok)return n.result;let r=si(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let l=SP(a.name);if(l.owner!=="generic")return le(e.source,"unsupported-syntax",l.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(ci.isJSXAttribute),s=new Map;for(let a of i){let l=IP(a);if(!l)continue;let c=s.get(l)??[];c.push(a),s.set(l,c)}for(let a of t.data.changes)if((s.get(a.name)??[]).length>1)return le(e.source,"unsupported-syntax",`JSX attribute '${a.name}' has multiple sources`,"jsx-node");for(let a of t.data.changes){let l=s.get(a.name)?.[0];if(a.operation==="remove"){l&&(o.attributes=o.attributes.filter(u=>u!==l));continue}let c=ps(a.name,a.value).value;l?l.value=c:o.attributes.push(ps(a.name,a.value))}return et(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function IP(e){return ci.isJSXIdentifier(e.name)?e.name.name:ci.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as vP}from"@vcp-dev/contracts";import*as pe from"@babel/types";var ty=["prefetch","replace","scroll","locale","onNavigate"],kP=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function _P(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>pe.isJSXAttribute(n)&&pe.isJSXIdentifier(n.name)&&kP.test(n.name.name)))return!0;t=t.parentPath}return!1}function fc(e){let t=ft(e.source,"jsx-node");if(!t.ok)return t.result;let n=si(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=vP.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Nr(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=wP(s.name);if(!a)return Nr(e.source,"Unsupported JSX link tag");if(s.attributes.some(pe.isJSXSpreadAttribute))return Nr(e.source,"Link elements with spread props cannot be transformed safely");let l=new Map;for(let g of s.attributes){if(!pe.isJSXAttribute(g))continue;let p=kd(g);if(!p)return Nr(e.source,"Unsupported JSX attribute name");let h=l.get(p)??[];h.push(g),l.set(p,h)}if([...l.values()].some(g=>g.length>1))return Nr(e.source,"Duplicate JSX attributes cannot be transformed safely");let c=l.get("href")?.[0];if(c&&!TP(c))return Nr(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:PP(o,s.name);if(!u&&!d)return Nr(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&_P(o))return Nr(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 g=NP(t.ast,o);if(!g.ok)return Nr(e.source,g.reason);f=g.localName}if(d&&e.link.kind!=="internal-route"){let g=pe.jsxIdentifier("a");s.name=g,i.closingElement&&(i.closingElement.name=pe.jsxIdentifier("a")),AP(t.ast,d,o)}else f&&u&&(s.name=pe.jsxIdentifier(f),i.closingElement&&(i.closingElement.name=pe.jsxIdentifier(f)));let m=new Set;return e.link.kind==="none"?(m.add("href"),m.add("target"),m.add("rel"),ty.forEach(g=>m.add(g))):(m.add("href"),e.link.kind==="native-link"&&ty.forEach(g=>m.add(g))),s.attributes=s.attributes.filter(g=>{if(!pe.isJSXAttribute(g))return!0;let p=kd(g);return!p||!m.has(p)}),e.link.kind!=="none"&&s.attributes.push(pe.jsxAttribute(pe.jsxIdentifier("href"),pe.stringLiteral(e.link.href))),CP(s,e.changes),et(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function CP(e,t){for(let n of t){let r=e.attributes.find(s=>pe.isJSXAttribute(s)&&kd(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?pe.stringLiteral(n.value):pe.jsxExpressionContainer(vd(n.value)),i=pe.jsxAttribute(pe.jsxIdentifier(n.name),o);r&&pe.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function vd(e){return e===null?pe.nullLiteral():typeof e=="string"?pe.stringLiteral(e):typeof e=="number"?pe.numericLiteral(e):typeof e=="boolean"?pe.booleanLiteral(e):Array.isArray(e)?pe.arrayExpression(e.map(t=>vd(t))):typeof e=="object"?pe.objectExpression(Object.entries(e).map(([t,n])=>pe.objectProperty(pe.isValidIdentifier(t)?pe.identifier(t):pe.stringLiteral(t),vd(n)))):pe.nullLiteral()}function RP(e){return pe.isImportDefaultSpecifier(e)||pe.isImportSpecifier(e)&&e.importKind!=="type"&&(pe.isIdentifier(e.imported,{name:"default"})||pe.isStringLiteral(e.imported,{value:"default"}))}function ny(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(pe.isIdentifier(e.node.imported,{name:"default"})||pe.isStringLiteral(e.node.imported,{value:"default"}))}function PP(e,t){if(!pe.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!ny(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function NP(e,t){let n=e.program.body.filter(l=>pe.isImportDeclaration(l)&&l.source.value==="next/link"&&l.importKind!=="type"),r=n[0],o=n.flatMap(l=>l.specifiers).find(RP);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},(l,c)=>`NextLink${c+2}`)].find(l=>!i.hasBinding(l)&&!t.scope.hasBinding(l));if(!s)return{ok:!1,reason:"Cannot create an unshadowed runtime next/link import"};let a=pe.importDefaultSpecifier(pe.identifier(s));if(r)r.specifiers.unshift(a);else{let l=pe.importDeclaration([a],pe.stringLiteral("next/link")),c=0;for(;c<e.program.body.length&&pe.isImportDeclaration(e.program.body[c]);)c+=1;e.program.body.splice(c,0,l)}return{ok:!0,localName:s}}function AP(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!ny(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 TP(e){return!e.value||pe.isStringLiteral(e.value)}function wP(e){return pe.isJSXIdentifier(e)?e.name:null}function kd(e){return pe.isJSXIdentifier(e.name)?e.name.name:null}function Nr(e,t){return le(e,"unsupported-syntax",t,"jsx-node")}import*as Kt from"@babel/types";import{classifySiteEditPropertyName as ry}from"@vcp-dev/contracts";function pc(e){let t=ry(e.name),n=ry(e.property);if(t.owner!=="generic"||n.owner!=="generic")return le(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!oy(e.object))return le(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return le(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=ft(e.source,"jsx-node");if(!r.ok)return r.result;let o=si(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(c=>Kt.isJSXAttribute(c)&&LP(c)===e.name);if(s.length>1)return le(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=OP(e.object,e.property),l=s[0];if(l)l.value=Kt.jsxExpressionContainer(a);else{let c=ps(e.name,"");c.value=Kt.jsxExpressionContainer(a),i.attributes.push(c)}return et(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function OP(e,t){return oy(t)?Kt.memberExpression(Kt.identifier(e),Kt.identifier(t)):Kt.memberExpression(Kt.identifier(e),Kt.stringLiteral(t),!0)}function oy(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function LP(e){return Kt.isJSXIdentifier(e.name)?e.name.name:Kt.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as DP,identifier as ys,importDeclaration as MP,importDefaultSpecifier as BP,importNamespaceSpecifier as jP,importSpecifier as $P,isImportDefaultSpecifier as iy,isImportNamespaceSpecifier as sy,isImportSpecifier as ay,stringLiteral as UP}from"@babel/types";function Dn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(h=>!YP(h));if(o!==-1){let h=r[o],x=h&&typeof h=="object"&&"kind"in h?h.kind:void 0;return le(t,"unsupported-syntax",`Unsupported import spec kind: ${String(x)}`)}let i=HP(r);if(!i.ok)return le(t,"unsupported-syntax",i.message);let s=ft(t);if(!s.ok)return s.result;let{ast:a}=s,l=a.program,c=l.body.filter(h=>h.type==="ImportDeclaration"&&h.source.value===n),u=new Set(c.flatMap(h=>h.specifiers.flatMap(x=>{let b=ZP(h,x);return b?[b]:[]}))),d=i.imports.filter(h=>!u.has(py(h)));if(d.length===0)return fs(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let f=WP(l.body),m=d.find(h=>f.has(_d(h)));if(m)return le(t,"unsupported-syntax",`Import local binding already exists: ${_d(m)}`);let g=zP(d);if(g.reduce((h,x)=>h+x.length,0)!==d.length)return le(t,"unsupported-syntax","Unsupported import specifier grouping");for(let h of g){if(!dy(ly(h)))return le(t,"unsupported-syntax","Unsupported import specifier combination");let x=c.find(b=>VP(b,h));if(x)KP(x,h);else{let b=MP(cy(h),UP(n));GP(l.body,b),c.push(b)}}return et(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function VP(e,t){return e.importKind==="type"?!1:dy(XP(JP(e),ly(t)))}function KP(e,t){let n=!1,r=new Set(e.specifiers.map(o=>Cd(o)));for(let o of cy(t)){let i=Cd(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return fy(e.specifiers),{changed:n}}function cy(e){let t=e.map(n=>{switch(n.kind){case"named":return $P(n.local?ys(n.local):ys(n.imported),ys(n.imported));case"default":return BP(ys(n.local));case"namespace":return jP(ys(n.local));default:return n}});return fy(t),t}function ly(e){let t=uy();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 JP(e){let t=uy();for(let n of e.specifiers)iy(n)?t.defaultLocals.add(n.local.name):sy(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function uy(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function XP(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function dy(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function fy(e){let t=[...e.filter(n=>iy(n)),...e.filter(n=>sy(n)),...e.filter(n=>ay(n))];e.splice(0,e.length,...t)}function zP(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=[],l=t[s],c=n[s];l&&a.push(l),c&&a.push(c),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 HP(e){let t=new Map,n=new Map;for(let r of e){let o=py(r);if(t.has(o))continue;let i=_d(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 WP(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 GP(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 YP(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 py(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 _d(e){return e.kind==="named"?e.local??e.imported:e.local}function ZP(e,t){return e.importKind==="type"||ay(t)&&t.importKind==="type"?null:Cd(t)}function Cd(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 li(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!QP(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return le(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=ft(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,l=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(l===-1)return fs(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let c=a.body[l];return r.length===0?(a.body.splice(l,1),et(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(c.specifiers=c.specifiers.filter(u=>!r.some(d=>qP(u,d))),c.specifiers.length===0&&a.body.splice(l,1),et(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function qP(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 QP(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 xs(e){let{source:t,locator:n,next:r}=e,o=yc(t,n);return o.ok?(o.path.replaceWith(Wr(r)),et(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function mc(e){let{source:t,locator:n,index:r,value:o}=e,i=yc(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?le(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?le(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,Wr(o)),et(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):le(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function gc(e){let{source:t,locator:n,index:r}=e,o=yc(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?le(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?le(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"})):le(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function hc(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=yc(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return le(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(l=>l?.type==="SpreadElement"))return le(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 le(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 yc(e,t){let n=ft(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=De(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as zt from"@babel/types";function xc(e){let t=ft(e.source,"value");if(!t.ok)return t.result;let n=De(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return le(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>zt.isSpreadElement(a)||zt.isObjectProperty(a)&&a.computed))return le(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>zt.isObjectProperty(a)&&eN(a.key)===e.name);if(o.length>1)return le(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?zt.unaryExpression("void",zt.numericLiteral(0)):Wr(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=zt.objectProperty(hd(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 eN(e){return zt.isIdentifier(e)?e.name:zt.isStringLiteral(e)?e.value:zt.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as tN,isSiteEditRuntimeVoidElementTag as nN}from"@vcp-dev/contracts/site-edit-runtime-capability";function ui(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function rN(e,t,n){let r=ui(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,c=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,f=!d&&nN(u),m=d||tN(u),g=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&&!m&&!s.some(S=>S.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let h=p&&(!a||i.importedFrom==="next/link"),x=!i.isPublicUiComponent&&!f&&m&&(!a||g);return{composition:r,key:e,canUpdateText:h,canInsertChild:x,canMove:!c,canRemove:!c,constraints:s}}function bc(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,rN(r,e,t));return n}function Rd(e){let t=e.route.graph.elements.get(e.key);if(!t)return{key:e.key,composition:e.route.composition,filePath:"",componentName:"",sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:je(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=oN(e.route.source,t);if(!n)return{key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:je(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.node.openingElement,o=r.attributes.find(d=>d.type==="JSXAttribute"&&d.name.type==="JSXIdentifier"&&d.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:gy(r),version:{documentVersion:e.route.graph.version,contentHash:je(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression",l=n.get("openingElement").get("attributes").find(d=>d.node===o),c=l?.isJSXAttribute()?l.get("value"):null,u=c?.isJSXExpressionContainer()?iN(c.get("expression")):void 0;return{...i,sourceKind:a,attrRaw:my(e.route.source,o),valueRaw:s?my(e.route.source,s):null,...u===void 0?{}:{resolvedClassName:u},attrRange:gy(o),diagnostics:[]}}function hy(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,l=o?`${a<n.start?" ":""}${o}`:"";return t.slice(0,a)+l+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 oN(e,t){let n=or({source:e,profile:Ro({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=De(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:sN(t.sourceRange)});return!r.ok||!r.match.path.isJSXElement()?null:r.match.path}function iN(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 yy(e){let t=or({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 my(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function gy(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 sN(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function xy(){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 aN}from"node:crypto";import Ec from"node:fs/promises";import Pd from"node:path";import{setTimeout as cN}from"node:timers/promises";var lN={async mkdir(e,t){await Ec.mkdir(e,t)},async writeFile(e,t,n){await Ec.writeFile(e,t,n)},async rename(e,t){await Ec.rename(e,t)},async rm(e,t){await Ec.rm(e,t)}},uN=new Set(["EACCES","EBUSY","EPERM"]),dN=[10,20,40,80,160];async function fN(e,t,n){for(let r of dN)try{await e.rename(t,n);return}catch(o){if(!pN(o))throw o;await cN(r)}await e.rename(t,n)}function pN(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&uN.has(e.code)}async function Sc(e,t,n=lN){let r=Pd.dirname(e),o=Pd.basename(e),i=Pd.join(r,`.${o}.${process.pid}.${aN()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await fN(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import Nd from"@babel/traverse";import*as w from"@babel/types";import*as We from"@babel/types";function cr(e,t={}){if(We.isTSAsExpression(e)||We.isTSSatisfiesExpression(e)||We.isTSNonNullExpression(e)||We.isTypeCastExpression(e)||We.isParenthesizedExpression(e))return cr(e.expression,t);if(We.isStringLiteral(e))return{status:"resolved",value:e.value};if(We.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(We.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(We.isNullLiteral(e))return{status:"resolved",value:null};if(We.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(We.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(We.isUnaryExpression(e)&&e.operator==="void"&&We.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(We.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||We.isSpreadElement(r))return{status:"unresolved"};let o=cr(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(We.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!We.isObjectProperty(r)||r.computed||!We.isExpression(r.value))return{status:"unresolved"};let o=mN(r.key);if(o===null)return{status:"unresolved"};let i=cr(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 We.isMemberExpression(e)||We.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function mN(e){return We.isIdentifier(e)?e.name:We.isStringLiteral(e)?e.value:We.isNumericLiteral(e)?String(e.value):null}var gN=typeof Nd=="function"?Nd:Nd.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 hN(e){return/^[A-Z]/.test(e)}function Ld(e){let t=e.openingElement;return w.isJSXIdentifier(t.name)?t.name.name==="Fragment":w.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function fi(e){return w.isJSXFragment(e)}function Ey(e){return w.isJSXIdentifier(e.name)?e.name.name:w.isJSXMemberExpression(e.name)?Sy(e.name):w.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Sy(e){return w.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:w.isJSXMemberExpression(e.object)?`${Sy(e.object)}.${e.property.name}`:e.property.name}function yN(e){return e.split(".")[0]??e}function xN(e){let t=e;for(;t;){let n=t.node;if(w.isFunctionDeclaration(n)&&n.id||w.isVariableDeclarator(n)&&w.isIdentifier(n.id))return n.id.name;if(w.isExportDefaultDeclaration(n)){let r=n.declaration;if(w.isFunctionDeclaration(r)&&r.id)return r.id.name;if(w.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function bN(){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 EN(e){let t=new Map;for(let n of e.program.body){if(!w.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(w.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(w.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(w.isImportSpecifier(o)){let i=w.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Ar(e,t=[]){if(w.isIdentifier(e))return t.push(e.name),t;if(w.isObjectPattern(e)){for(let n of e.properties)w.isObjectProperty(n)?Ar(n.value,t):w.isRestElement(n)&&Ar(n.argument,t);return t}if(w.isArrayPattern(e)){for(let n of e.elements)n&&(w.isRestElement(n)?Ar(n.argument,t):Ar(n,t));return t}return w.isAssignmentPattern(e)?(Ar(e.left,t),t):(w.isRestElement(e)&&Ar(e.argument,t),t)}function Xn(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function bs(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 SN(e,t,n){e.set(t,{resolved:!0,value:n})}function Fd(e,t){e.set(t,{resolved:!1})}function Iy(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 jt(e,t,n){if(w.isTSAsExpression(e)||w.isTSSatisfiesExpression(e)||w.isTSNonNullExpression(e)||w.isTypeCastExpression(e)||w.isParenthesizedExpression(e))return jt(e.expression,t,n);if(w.isLogicalExpression(e))return Ic([jt(e.left,t,n),jt(e.right,t,n)]);if(w.isBinaryExpression(e))return Ic([w.isExpression(e.left)?jt(e.left,t,n):null,w.isExpression(e.right)?jt(e.right,t,n):null]);if(w.isConditionalExpression(e))return Ic([jt(e.consequent,t,n),jt(e.alternate,t,n)]);if(w.isTemplateLiteral(e))return Ic(e.expressions.filter(w.isExpression).map(i=>jt(i,t,n)));if(w.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!w.isMemberExpression(e)&&!w.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;w.isMemberExpression(o)||w.isOptionalMemberExpression(o);){if(o.computed)if(w.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(w.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&w.isExpression(o.property)){let i=Zr(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(!w.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return w.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:Xn(e,t),base:o.name,path:r}:null}function Ic(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 Dd(e,t,n){if(w.isArrayExpression(e)){let r=e.elements[0];return e.elements.length===1&&w.isExpression(r)?jt(r,t,n):null}return w.isCallExpression(e)&&w.isMemberExpression(e.callee)&&!e.callee.computed&&w.isIdentifier(e.callee.property)&&["filter","slice","sort","toSorted","reverse","toReversed"].includes(e.callee.property.name)&&w.isExpression(e.callee.object)?Dd(e.callee.object,t,n):jt(e,t,n)}function Zr(e,t){if(w.isStringLiteral(e)||w.isNumericLiteral(e)||w.isBooleanLiteral(e))return e.value;if(w.isNullLiteral(e))return null;if(w.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(w.isIdentifier(e)){let n=bs(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(w.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||w.isSpreadElement(r))return;let o=Zr(r,t);if(o===void 0)return;n.push(o)}return n}if(w.isObjectExpression(e)){let n={};for(let r of e.properties){if(!w.isObjectProperty(r)||r.computed||!w.isExpression(r.value))return;let o=null;if(w.isIdentifier(r.key)?o=r.key.name:w.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!w.isIdentifier(r.value))return;let s=bs(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Zr(r.value,t);if(i===void 0)return;n[o]=i}return n}if(w.isMemberExpression(e)){let n=jt(e,"",t);if(!n)return;let r=bs(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Iy(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(w.isCallExpression(e))return ky(e,t)??void 0}function vy(e,t,n){let r=jt(e,n,t);if(!r)return w.isMemberExpression(e)||w.isBinaryExpression(e)||w.isLogicalExpression(e)||w.isConditionalExpression(e)||w.isCallExpression(e)?{value:Xn(e,n),source:null}:null;let o=bs(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Iy(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 Ad(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:bN(),parentStack:[],valueScopes:i,importMap:o}}function wd(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Ar(o.id))Fd(n,s);if(!w.isIdentifier(o.id)||!o.init||!w.isExpression(o.init))continue;let i=Zr(o.init,t);i!==void 0&&SN(n,o.id.name,i)}}function IN(e){let t=[];for(let n of e){if(w.isVariableDeclaration(n)){t.push(n);continue}w.isExportNamedDeclaration(n)&&n.declaration&&w.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function vN(e,t,n){let r=[],o=0;for(let i of e)if(w.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Zt(i),editable:!0,source:null})}else if(w.isJSXExpressionContainer(i)&&w.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Zt(i),editable:!0,source:null});else if(w.isJSXExpressionContainer(i)&&w.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:Xn(s,n),sourceRange:Zt(i),editable:!0,source:jt(s,n,t)})}else if(w.isJSXExpressionContainer(i)&&w.isExpression(i.expression)){let s=vy(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Zt(i),editable:!0,source:s.source})}return r}function kN(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!w.isJSXAttribute(i))continue;let s=CN(i.name);if(!s)continue;let a=Xn(i,n);if(w.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(w.isJSXExpressionContainer(i.value)&&w.isExpression(i.value.expression)){let l=Zr(i.value.expression,t);if(s==="className"){let m=typeof l=="string"?l:l===void 0?ky(i.value.expression,t):null;if(m){r.push({name:s,value:m,sourceRange:Zt(i),source:null,resolvedValue:m,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:m}});continue}}let c=vy(i.value.expression,t,n);if(l!==void 0){r.push({name:s,value:ON(l),sourceRange:Zt(i),source:jt(i.value.expression,n,t),resolvedValue:l,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:l}});continue}let u=RN(i.value.expression,t),d=jt(i.value.expression,n,t),f=c?.value??Xn(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":f,sourceRange:Zt(i),source:c?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function _N(e,t,n){return e.attributes.flatMap((r,o)=>!w.isJSXSpreadAttribute(r)||!w.isExpression(r.argument)?[]:[{raw:Xn(r.argument,n),sourceRange:Zt(r),order:o,source:jt(r.argument,n,t)}])}function CN(e){return w.isJSXIdentifier(e)?e.name:w.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function RN(e,t){return cr(e,{resolveIdentifier(n){let r=bs(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=Zr(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function ky(e,t){let n=di(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function di(e,t){if(w.isStringLiteral(e))return[e.value];if(w.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(w.isNullLiteral(e))return[];if(w.isBooleanLiteral(e))return e.value?null:[];if(w.isIdentifier(e)||w.isMemberExpression(e)){if(w.isIdentifier(e)&&e.name==="undefined")return[];let n=Zr(e,t);return typeof n=="string"?[n]:null}if(w.isConditionalExpression(e)){let n=di(e.consequent,t),r=di(e.alternate,t);return!n||!r?null:[...n,...r]}if(w.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Zr(e.left,t);return n===!1||n===null?[]:di(e.right,t)}if(w.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||w.isSpreadElement(r))return null;let o=di(r,t);if(!o)return null;n.push(...o)}return n}if(w.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!w.isObjectProperty(r))return null;let o=NN(r.key);if(!o)return null;n.push(o)}return n}if(w.isCallExpression(e)){let n=PN(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!w.isExpression(o))return null;let i=di(o,t);if(!i)return null;r.push(...i)}return r}return null}function PN(e){return w.isIdentifier(e)?e.name:w.isMemberExpression(e)&&w.isIdentifier(e.property)?e.property.name:null}function NN(e){return w.isIdentifier(e)?e.name:w.isStringLiteral(e)?e.value:null}function AN(e,t){let n=e.attributes.find(r=>w.isJSXAttribute(r)&&w.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!w.isJSXAttribute(n)||!w.isJSXExpressionContainer(n.value)?null:n.value.expression}function TN(e,t){for(let n of t){let r=AN(e,n);if(r)return r}return null}function wN(e){return w.isJSXIdentifier(e.name)?e.name.name:null}function ON(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function LN(e){if(!w.isCallExpression(e)&&!w.isOptionalCallExpression(e))return null;let t=e.callee;return!w.isMemberExpression(t)&&!w.isOptionalMemberExpression(t)||!w.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!w.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Td(e){return w.isArrowFunctionExpression(e)||w.isFunctionExpression(e)}function FN(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 by(e,t,n,r){if(!e||!w.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:Xn(e,n),collectionSource:Dd(e,n,r)};if(t){let i=t.params[0],s=t.params[1];w.isIdentifier(i)&&(o.itemParamName=i.name),w.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Tr(e,t,n){if(!e)return[];if(w.isJSXElement(e)){if(Ld(e))return Rc(e.children,t,n);let r=_c(e,t,n);return r?[r]:[]}return fi(e)?Cc(e,t,n):w.isParenthesizedExpression(e)?Tr(e.expression,t,n):w.isExpression(e)?Pc(e,t,n):[]}function vc(e,t,n){let r=new Map;for(let o of e.params)for(let i of Ar(o))Fd(r,i);t.valueScopes.push(r);try{if(!w.isBlockStatement(e.body))return Tr(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return _y(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function _y(e,t,n){let r=[];for(let o of e){if(w.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){wd([o],t,i);for(let s of o.declarations)w.isIdentifier(s.id)&&(w.isJSXElement(s.init)||w.isJSXFragment(s.init))&&r.push(...Tr(s.init,t,n))}continue}r.push(...Od(o,t,n))}return r}function Od(e,t,n){if(w.isReturnStatement(e))return e.argument?Tr(e.argument,t,n):[];if(w.isBlockStatement(e))return Do(e.body,t,n);if(w.isIfStatement(e)){let r=w.isBlockStatement(e.consequent)?Do(e.consequent.body,t,n):Od(e.consequent,t,n),o=e.alternate?w.isBlockStatement(e.alternate)?Do(e.alternate.body,t,n):Od(e.alternate,t,n):[];return[...r,...o]}if(w.isSwitchStatement(e))return Do(e.cases.flatMap(r=>r.consequent),t,n);if(w.isTryStatement(e)){let r=Do(e.block.body,t,n);return e.handler&&r.push(...Do(e.handler.body.body,t,n)),e.finalizer&&r.push(...Do(e.finalizer.body,t,n)),r}return[]}function Do(e,t,n){let r=new Map;t.valueScopes.push(r);try{return _y(e,t,n)}finally{t.valueScopes.pop()}}function kc(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 MN(e,t,n,r){let o=TN(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Ey(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!w.isJSXAttribute(s))continue;let a=wN(s);if(!a||!w.isJSXExpressionContainer(s.value))continue;let l=s.value.expression;if(!w.isJSXEmptyExpression(l)){if(FN(a)&&Td(l)){let c=vc(l,n,r),u=by(o,l,r,n);kc(n,"repeat-region",t,s,c,u?[u]:void 0);continue}if(DN(a)){let c=Td(l)?vc(l,n,r):Tr(l,n,r);kc(n,"conditional-region",t,s,c)}}}if(o)for(let s of e.children){if(!w.isJSXExpressionContainer(s)||!Td(s.expression))continue;let a=vc(s.expression,n,r),l=by(o,s.expression,r,n);kc(n,"repeat-region",t,s,a,l?[l]:void 0)}}finally{n.parentStack.pop()}}function _c(e,t,n){let r=Ey(e.openingElement);if(r==="Fragment"||Ld(e))return Rc(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=hN(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 l=o?t.elements.get(o.key)?.identity.structuralPath:void 0,c=l?`${l}/${a}`:a,u=ms(t.file,t.componentName,c),d={file:t.file,component:t.componentName,structuralPath:c,key:u},f=s?"component-boundary":null,m=vN(e.children,t,n),g=kN(e.openingElement,t,n),p=_N(e.openingElement,t,n),h,x,b=!1;if(s){let S=t.importMap.get(r)??t.importMap.get(yN(r));S&&(h=S.specifier,x=S.exportName,b=Po(S.specifier,t.file))}let E={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Zt(e),parentKey:i,childKeys:[],textSegments:m,attributes:g.length>0?g:void 0,attributeSpreads:p.length>0?p:void 0,boundaryKind:f,isOpaque:s,...b?{isPublicUiComponent:!0}:{},importedFrom:h,exportName:x};return t.elements.set(u,E),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),MN(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),BN(e.children,t,n),t.parentStack.pop()),u}function Cc(e,t,n){return Rc(e.children,t,n)}function Rc(e,t,n){let r=[];for(let o of e)if(w.isJSXElement(o))if(Ld(o))r.push(...Rc(o.children,t,n));else{let i=_c(o,t,n);i&&r.push(i)}else fi(o)?r.push(...Cc(o,t,n)):w.isJSXExpressionContainer(o)&&r.push(...Pc(o.expression,t,n));return r}function BN(e,t,n){for(let r of e)w.isJSXElement(r)?_c(r,t,n):fi(r)?Cc(r,t,n):w.isJSXExpressionContainer(r)&&Pc(r.expression,t,n)}function jN(e){return e==="&&"||e==="||"||e==="??"}function Pc(e,t,n){if(w.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,l={kind:"repeat-template",collectionExpression:Xn(r.collection,n),collectionSource:Dd(r.collection,n,t)};if(w.isArrowFunctionExpression(a)||w.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];w.isIdentifier(u)&&(l.itemParamName=u.name),w.isIdentifier(d)&&(l.indexParamName=d.name)}s.push(l);let c={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Zt(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(c),(w.isArrowFunctionExpression(a)||w.isFunctionExpression(a))&&c.childKeys.push(...vc(a,t,n)),c.childKeys}if(w.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Xn(e.test,n),conditionSource:jt(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(...Tr(e.consequent,t,n)),s.childKeys.push(...Tr(e.alternate,t,n)),s.childKeys}if(w.isLogicalExpression(e)&&jN(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Xn(e.left,n),conditionSource:jt(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(...Tr(e.right,t,n)),s.childKeys}if(w.isParenthesizedExpression(e))return Pc(e.expression,t,n);if(w.isJSXElement(e)){let o=_c(e,t,n);return o?[o]:[]}return fi(e)?Cc(e,t,n):[]}function $N(e){let t=e.argument;return t&&(w.isExpression(t)||fi(t))?t:null}function Es(e,t){let n=[];for(let r of e){if(w.isReturnStatement(r)){let o=$N(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(w.isIfStatement(r)){let o=w.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Es(o,r.test)),r.alternate){let i=w.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Es(i,r.test))}continue}if(w.isSwitchStatement(r))for(let o of r.cases){let i=o.test?w.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Es(o.consequent,i))}}return n}function Nc(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function Cy(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier);if(!w.traverseFast(r,f=>{if(w.isJSXElement(f)||w.isJSXFragment(f))return w.traverseFast.stop}))return{graph:Nc(t),localImports:o};let s=new Map,a=[],l=[],c=new Map,u=EN(r);gN(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let m=xN(f);if(!m)return;let g=f.node,p=[];if(w.isArrowFunctionExpression(g))w.isExpression(g.body)||fi(g.body)?p=[{argument:g.body,statement:w.returnStatement(w.isExpression(g.body)?g.body:null)}]:w.isBlockStatement(g.body)&&(p=Es(g.body.body));else{let v=g.body;w.isBlockStatement(v)&&(p=Es(v.body))}if(p.length===0){f.skip();return}let h=new Map;wd(IN(r.program.body),Ad(t,m,s,a,u,[h]),h);let x=new Map;for(let v of g.params)for(let A of Ar(v))Fd(x,A);let b=w.isBlockStatement(g.body)?g.body.body:[],E=p[0]?.statement??null;for(let v of b){if(E&&v===E)break;w.isVariableDeclaration(v)&&wd([v],Ad(t,m,s,a,u,[h,x]),x)}let S=Ad(t,m,s,a,u,[h,x]);for(let v of p){let A=Tr(v.argument,S,n);for(let I of A)l.includes(I)||l.push(I);if(v.condition){let I={kind:"conditional-branch",conditionExpression:Xn(v.condition,n),conditionSource:jt(v.condition,n,S)};kc(S,"conditional-region","",v.statement,A,[I])}}f.skip()}});let d=[...s.keys()];return d.length>0&&c.set(t,d),{graph:{routeId:t,rootKeys:l,elements:s,regions:a,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function Md(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Ac(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Ry(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 pi(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Te,l=new Map,c=new Map,u=new Map,d=[],f=new Set,m=x=>{let b=`${x.path}\0${x.code}\0${x.message}\0${JSON.stringify(x.details??{})}`;f.has(b)||(f.add(b),d.push(x))},g=[{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:[]}))],p=new Set;for(;g.length>0;){let x=g.shift(),{file:b,source:E,depth:S,diagnosticEntryFile:v,importStack:A}=x;if(p.has(b))continue;p.add(b),l.set(b,E);let I=o.validationOnly&&S<i?o.validatedImports?.(b,E):void 0,_,k;if(I)_=Nc(b),k=I;else{let z=a(b,E);if(!z.ok){m(Ac(z.diagnostic,v,A));continue}u.set(b,z.module);let Z=o.validationOnly&&S<i?{graph:Nc(b),localImports:z.module.imports.map(W=>W.specifier)}:Cy(z.module);_=Z.graph,k=Z.localImports}let T=[...new Set([..._.elements.values()].map(z=>z.importedFrom).filter(z=>typeof z=="string"&&kt(z)))],L=T.length?await Ry(T,z=>Ja(b,z,r)):[],$=new Map(T.map((z,Z)=>[z,L[Z]]));for(let z of _.elements.values())if(z.importedFrom&&kt(z.importedFrom)){let Z=z.importedFrom,W=$.get(Z);W.ok?(z.importedFrom=W.path,Cr(W.path)&&(z.isPublicUiComponent=!0)):Po(Z,b)||m(Ac(W.diagnostic,v,Md(A,b,Z,W.diagnostic.path)))}if(c.set(b,_),S>=i)continue;let J=await Ry(k,async z=>{if(ah(z))return null;let Z=$.get(z)??await Ja(b,z,r);if(!Z.ok)return Po(z,b)?null:{diagnostic:Ac(Z.diagnostic,v,Md(A,b,z,Z.diagnostic.path))};let W=Z.path;if(p.has(W)||Cr(W))return null;let Ee=Md(A,b,z,W);try{let xe=await n(W);return{entry:{file:W,source:xe,depth:S+1,diagnosticEntryFile:v,importStack:Ee}}}catch(xe){return{diagnostic:Ac({path:W,code:"import-read-failed",message:`Failed to read imported file: ${W}`,details:{fromFile:b,specifier:z,reason:xe instanceof Error?xe.message:String(xe)}},v,Ee)}}});for(let z of J)z&&"entry"in z?g.push(z.entry):z&&m(z.diagnostic)}let h=UN(e,c,s,(o.additionalEntries??[]).map(x=>x.file));return h.diagnostics=d,{graph:h,allSources:l,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function UN(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[l,c]of t){for(let[u,d]of c.elements)o.set(u,d);for(let u of c.regions)i.push(u);for(let[u,d]of c.fileIndex){let f=s.get(u)??[];s.set(u,[...f,...d])}if(l===e){a=c.rootKeys;continue}r.includes(l)&&(a=[...a,...c.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}function Py(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 hA}from"@vcp-dev/contracts";import{createHash as VN,randomUUID as Hd}from"node:crypto";import It from"node:fs/promises";import Ct from"node:path";var By=new WeakMap;function mi(e){return By.get(e)?.()??e.readIndex()}var Mn=1,jd=1,KN=2,JN="index.json",XN="recovery.json",zN="transaction-journal.json",HN="document-version.json",Oc={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},Ne={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"},we=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function wr(){return{entries:new Map,blobSizes:new Map}}function Tc(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)jy(n,r,t);return n}function jy(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 l=e.blobs.get(s);e.blobs.set(s,{sizeBytes:a,references:(l?.references??0)+1}),l||(e.objectBytes+=a)}}function $y(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 Uy(e,t={}){let n=uA(e),r=mA(t.limits),o=Bd(n),i=dA(n),s=await ln(i),a=await ln(o)||s;a||(await nA(n),await rA(n)),a||await gA(n);let l=wr(),c=await Fc(n,l),u=new Set(a?(await $c(n)).map(b=>b.stageId):[]);a||await Oy(n,c.entryIds,l);let d=c.digest,f=Tc(c.entryIds,l),m=async b=>{let{index:E,sizeBytes:S}=await _s(n);if(Wy(E,b),E.digest!==d){let v=wr();await Xy(n,E.entryIds,v,S),f=Tc(E.entryIds,v),d=E.digest}return{...Uc(E),totalBytes:f.objectBytes+S}},g=async b=>{Wd(b),await m(),await Ty(n,f,[b.entryId],b.blobIds,b.stageId),await Lc(n,b.stageId)},p=async(b,E)=>{let S=await m(E);Ky(b,S.entryIds.length);let v=wr();for(let A of S.entryIds.slice(Math.min(S.cursor,b)+1,Math.max(S.cursor,b)+1))await Is(n,A,v);return S},h=async()=>{if(await ln(o)||s)throw new we(Ne.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},x={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Dy(n)},async writeDocumentVersion(b){if(await h(),!Number.isInteger(b)||b<0)throw new we(Ne.INVALID_SCHEMA,"document version must be a non-negative integer");let E=await Dy(n);b<=E||await Ss(qy(n),{schemaVersion:1,version:Math.max(E,b)})},async stageAppend(b,E={}){await h();let S=await YN(b,r),v={schemaVersion:jd,stageId:Hd(),entryId:S.entryId,blobIds:S.blobs.map(A=>A.digest)};try{await ZN(n,S),await QN(n,v,E.durableManifest!==!1)}catch(A){try{await g(v)}catch(I){throw new we(Ne.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:I})}throw A}return{stageId:v.stageId,entryId:v.entryId,blobIds:v.blobIds}},async discardStage(b){await h(),Vd(b);let E=await $d(n,b);E&&await g(E)},async previewStagedAppend(b,E){await h();let S=await m(E);return(await Ny(n,r,b,S,f)).transition},async previewCursor(b,E){await h();let S=await p(b,E);return Vy(S,S.entryIds,b)},async publishStagedAppend(b,E,S){if(await h(),Mc(b,"entryId"),S){Vd(S);let k=await $d(n,S);if(!k||k.entryId!==b)throw new we(Ne.INVALID_SCHEMA,"history stage does not match the published entry")}let v=await m(E),A=f,I=await Ny(n,r,b,v,A),_=await Fy({rootDir:n,previousDigest:I.current.digest,entryIds:I.entryIds,cursor:I.cursor,readback:async()=>Ly(n,I.usage),afterWrite:async()=>{S?await Lc(n,S):await tA(n,b),await Ty(n,I.usage,[...A.entries.keys()].filter(k=>!I.usage.entries.has(k)),[...A.blobs.keys()].filter(k=>!I.usage.blobs.has(k)))}});return f=I.usage,d=_.digest,_},async append(b){await h();let E=await m(),S=await x.stageAppend(b);try{return await x.publishStagedAppend(S.entryId,E.digest,S.stageId)}catch(v){throw await x.discardStage(S.stageId),v}},async readEntry(b){return Mc(b,"entryId"),Is(n,b)},async readBlob(b){Mc(b,"blobId");let E=await ex(n,b),S=await vs(E,Ne.NOT_FOUND,"blob");return Zy(S,b,E),S},async readIndex(){let b=wr(),E=await Fc(n,b);return f=Tc(E.entryIds,b),d=E.digest,E},async readStatus(){let b=await Dc(n);return{canUndo:b.undoIds.length>0,canRedo:b.redoIds.length>0,undoDepth:b.undoIds.length,redoDepth:b.redoIds.length,cursor:b.cursor,recoveryRequired:await ln(o)||await ln(i)}},async readUndoRedoIds(){let b=await Dc(n);return{undoIds:b.undoIds,redoIds:b.redoIds,currentId:b.currentId}},async setCursor(b,E){await h();let S=await p(b,E),v=await Fy({rootDir:n,previousDigest:S.digest,entryIds:S.entryIds,cursor:b,readback:async()=>Ly(n,f)});return d=v.digest,v},async markRecoveryRequired(b){await ln(o)||await Ss(Bd(n),{schemaVersion:Mn,reason:fA(b),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await It.rm(Bd(n),{force:!0})},async readTransactionJournal(){return await ln(i)?wc(i):null},async writeTransactionJournal(b){await h(),Qy(b);try{await Ss(i,b)}catch(S){let v=await wc(i).catch(()=>null);if(v&&Buffer.from(un(v)).equals(Buffer.from(un(b))))return;throw v?new we(Ne.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:S}):S}let E=await wc(i);if(!Buffer.from(un(E)).equals(Buffer.from(un(b))))throw new we(Ne.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(b){let E=await ln(i)?await wc(i):null;if(E&&E.transactionId!==b)throw new we(Ne.INVALID_SCHEMA,"transaction journal changed concurrently");try{await It.rm(i,{force:!0})}catch(S){if(!await ln(i))return;throw S}if(await ln(i))throw new we(Ne.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await h();for(let S of u)await Lc(n,S),u.delete(S);await oA(n);let b=wr(),E=await Fc(n,b);await Oy(n,E.entryIds,b),f=Tc(E.entryIds,b),d=E.digest}};return By.set(x,()=>Dc(n)),x}async function Ny(e,t,n,r,o){Mc(n,"entryId");let i=wr(),s=await Is(e,n,i),a={entries:new Map(o.entries),blobs:new Map(o.blobs),objectBytes:o.objectBytes},l=r.entryIds.slice(0,r.cursor+1);for(let u of r.entryIds.slice(r.cursor+1))$y(a,u);jy(a,s.id,i),l.push(s.id);let c=qN(l,t,a);return{current:r,entryIds:c.entryIds,cursor:c.cursor,usage:a,transition:Vy(r,c.entryIds,c.cursor)}}function Vy(e,t,n){return Ky(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:WN(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function WN(e,t){return qr(un({schemaVersion:Mn,entryIds:e,cursor:t}))}function Ky(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new we(Ne.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function GN(e){if(!zn(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!bn(e.expectedIndexDigest)||!bn(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!bn(n)?!1:t===-1?n===null:bn(n)}async function YN(e,t){if(!e.kind.trim())throw new we(Ne.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let l of e.blobs??[]){if(!l.name.trim())throw new we(Ne.INVALID_JSON,"history blob name must not be empty");let c=lA(l.data),u=qr(c);n.push({name:l.name,bytes:c,digest:u,sizeBytes:c.byteLength}),r.push({name:l.name,digest:u,sizeBytes:c.byteLength})}let o={schemaVersion:Mn,kind:e.kind,manifest:e.manifest,blobs:r},i=un({...o}),s=qr(i),a=i.byteLength+n.reduce((l,c)=>l+c.sizeBytes,0);if(a>t.maxEntryBytes)throw new we(Ne.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function ZN(e,t){let n=qd(e,t.entryId),r={id:t.entryId,...t.entryBody},o=new Map(t.blobs.map(l=>[l.digest,l])),i=[...Array.from(o.values(),l=>Ay(Qd(e,l.digest),l.bytes,{kind:"blob",digest:l.digest},tf(e,l.digest))),Ay(n,un(r),{kind:"entry",digest:t.entryId},ef(e,t.entryId))],a=(await Promise.allSettled(i)).find(l=>l.status==="rejected");if(a)throw a.reason}async function Ay(e,t,n,r){let o=await Xd(e)??(r?await Xd(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new we(n.kind==="blob"?Ne.BLOB_CORRUPT:Ne.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Gy(e,t)}function qN(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+un(Hy(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new we(Ne.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");$y(n,r.shift()),o-=1}}async function QN(e,t,n){Wd(t);let r=Zd(e,t.stageId);if(n){await Ss(r,t);return}await cA(r,t)}async function $d(e,t){let n=await Xd(Zd(e,t));if(n===null)return null;let r=Cs(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Wd(r);if(o.stageId!==t)throw new we(Ne.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function $c(e){let t=[];for(let n of await jc(Yd(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Vd(r);let o=await $d(e,r);o&&t.push(o)}return t}async function Ty(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 $c(e))if(a.stageId!==o){i.add(a.entryId);for(let l of a.blobIds)s.add(l)}for(let a of new Set(n))i.has(a)||await wy(qd(e,a),ef(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await wy(Qd(e,a),tf(e,a));await zd(Rs(e)),await zd(Ps(e))}async function Lc(e,t){await Ud(Zd(e,t)),await eA(e)}async function eA(e){try{await It.rmdir(Yd(e))}catch(t){if(Ns(t)||zn(t)&&t.code==="ENOTEMPTY")return;throw t}}async function tA(e,t){for(let n of await $c(e))n.entryId===t&&await Lc(e,n.stageId)}async function Ud(e){if(await It.rm(e,{force:!0}),await ln(e))throw new we(Ne.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function wy(e,t){await Ud(e),await Ud(t)}function Wd(e){if(!zn(e)||e.schemaVersion!==jd||typeof e.stageId!="string"||!Jy(e.stageId)||!bn(e.entryId))throw new we(Ne.INVALID_SCHEMA,"history stage schema is invalid");let t=Yy(e.blobIds,"history stage blobIds");return{schemaVersion:jd,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Vd(e){if(!Jy(e))throw new we(Ne.INVALID_PATH,"history stageId must be a UUID")}function Jy(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 Oy(e,t,n=wr()){let r=new Set(t),o=new Set;for(let c of t){let u=await Is(e,c,n);for(let d of u.blobs)o.add(d.digest)}for(let c of await $c(e)){r.add(c.entryId);for(let u of c.blobIds)o.add(u)}let i=Rs(e),s=await jc(i);for(let c of s){if(!c.endsWith(".json"))continue;let u=My(c.slice(0,-5));u&&!r.has(u)&&await Bc(Ct.join(i,c))}let a=Ps(e),l=await jc(a);for(let c of l){let u=My(c);u&&!o.has(u)&&await Bc(Ct.join(a,c))}}async function Fc(e,t=wr()){let{index:n,sizeBytes:r}=await _s(e),{totalBytes:o}=await Xy(e,n.entryIds,t,r);return{...Uc(n),totalBytes:o}}async function Ly(e,t){let{index:n,sizeBytes:r}=await _s(e);return{...Uc(n),totalBytes:t.objectBytes+r}}async function _s(e){let t=Gd(e),n=await vs(t,Ne.NOT_FOUND,"index"),r=Cs(Buffer.from(n).toString("utf8"),"index");return{index:iA(r),sizeBytes:n.byteLength}}async function Dc(e){return Uc((await _s(e)).index)}function Uc(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:Mn,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function Xy(e,t,n,r){let o=0,i=new Set;o+=r??(await _s(e)).sizeBytes;for(let s of new Set(t)){let a=await Is(e,s,n);o+=n.entries.get(s).sizeBytes;for(let l of a.blobs)i.has(l.digest)||(i.add(l.digest),o+=n.blobSizes.get(l.digest))}return{totalBytes:o}}async function Is(e,t,n=wr()){let r=n.entries.get(t);if(r)return r.entry;let o=await pA(e,t),i=await vs(o,Ne.NOT_FOUND,"entry"),s=Cs(Buffer.from(i).toString("utf8"),`entry ${t}`),a=sA(s);if(a.id!==t)throw new we(Ne.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(qr(un({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new we(Ne.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);let c=[...new Set(a.blobs.map(d=>d.digest))].filter(d=>!n.blobSizes.has(d)),u=async d=>{let f=await ex(e,d),m=await vs(f,Ne.NOT_FOUND,"blob");return Zy(m,d,f),m.byteLength};if(c.length===1)n.blobSizes.set(c[0],await u(c[0]));else if(c.length>1){let d=new Array(c.length),f=[],m=0,g=Array.from({length:Math.min(4,c.length)},async()=>{for(;m<c.length&&f.length===0;){let x=m++;try{d[x]=await u(c[x])}catch(b){f.push({index:x,error:b})}}}),p=await Promise.allSettled(g),h=f.sort((x,b)=>x.index-b.index)[0];if(h)throw h.error;for(let x of p)if(x.status==="rejected")throw x.reason;for(let x=0;x<c.length;x++)n.blobSizes.set(c[x],d[x])}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function zy(e,t,n){await Ss(Gd(e),Hy(t,n))}function Hy(e,t){return{schemaVersion:Mn,digest:qr(un({schemaVersion:Mn,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Wy(e,t){if(t!==void 0&&e.digest!==t)throw new we(Ne.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Fy(e){Wy(await Dc(e.rootDir),e.previousDigest);let t=qr(un({schemaVersion:Mn,entryIds:e.entryIds,cursor:e.cursor}));try{await zy(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new we(Ne.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Fc(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new we(Ne.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function nA(e){await It.mkdir(e,{recursive:!0}),await It.mkdir(Rs(e),{recursive:!0}),await It.mkdir(Ps(e),{recursive:!0}),await It.mkdir(ks(e),{recursive:!0})}async function rA(e){await It.rm(ks(e),{recursive:!0,force:!0}),await It.mkdir(ks(e),{recursive:!0})}async function oA(e){let t=ks(e);await It.mkdir(t,{recursive:!0});for(let n of await jc(t))n!=="stages"&&await It.rm(Ct.join(t,n),{recursive:!0,force:!0})}function iA(e){if(!zn(e))throw new we(Ne.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==Mn)throw new we(Ne.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Yy(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new we(Ne.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!bn(o))throw new we(Ne.INDEX_CORRUPT,"index digest is invalid");let i=qr(un({schemaVersion:Mn,entryIds:t,cursor:r}));if(o!==i)throw new we(Ne.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:Mn,digest:o,entryIds:t,cursor:r}}function sA(e){if(!zn(e))throw new we(Ne.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==Mn)throw new we(Ne.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!bn(t))throw new we(Ne.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new we(Ne.ENTRY_CORRUPT,"entry kind is invalid");let r=Jd(e.manifest,"entry.manifest"),o=aA(e.blobs);return{id:t,schemaVersion:Mn,kind:n,manifest:r,blobs:o}}function aA(e){if(!Array.isArray(e))throw new we(Ne.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!zn(t))throw new we(Ne.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new we(Ne.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!bn(o))throw new we(Ne.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new we(Ne.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Ss(e,t){await Gy(e,un(t))}async function cA(e,t){let n=Ct.dirname(e),r=Ct.basename(e),o=Ct.join(n,`.${r}.${process.pid}.${Hd()}.tmp`);await It.mkdir(n,{recursive:!0});try{await It.writeFile(o,un(t),{flag:"wx"}),await It.rename(o,e)}finally{await Bc(o)}}async function Gy(e,t){let n=Ct.dirname(e),r=Ct.basename(e),o=Ct.join(n,`.${r}.${process.pid}.${Hd()}.tmp`);await It.mkdir(n,{recursive:!0});try{let i=await It.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await It.rename(o,e),await zd(n)}finally{await Bc(o)}}function un(e){return Buffer.from(JSON.stringify(Kd(e)),"utf8")}function Kd(e){if(Array.isArray(e))return e.map(t=>Kd(t));if(zn(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Kd(e[n]);return t}return e}function Cs(e,t){try{return JSON.parse(e)}catch(n){throw new we(Ne.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Jd(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=>Jd(n,t));if(zn(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Jd(o,t);return n}break}throw new we(Ne.INVALID_JSON,`${t} must be JSON-serializable`)}function Yy(e,t){if(!Array.isArray(e))throw new we(Ne.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!bn(n))throw new we(Ne.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Mc(e,t){if(!bn(e))throw new we(Ne.INVALID_PATH,`${t} must be a sha256 digest`)}function bn(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function qr(e){return`sha256:${VN("sha256").update(e).digest("hex")}`}function lA(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function vs(e,t,n){try{return await It.readFile(e)}catch(r){throw new we(t,`${n} not found: ${e}`,{cause:r})}}async function Xd(e){try{return await It.readFile(e)}catch(t){if(Ns(t))return null;throw t}}function Zy(e,t,n){if(qr(e)!==t)throw new we(Ne.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function ln(e){try{return await It.access(e),!0}catch(t){if(Ns(t))return!1;throw t}}async function Bc(e){try{await It.rm(e,{force:!0,recursive:!0})}catch{}}async function zd(e){try{let t=await It.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function jc(e){try{return await It.readdir(e)}catch(t){if(Ns(t))return[];throw t}}function uA(e){if(typeof e!="string"||e.trim().length===0)throw new we(Ne.INVALID_ROOT,"history store rootDir must be a non-empty string");return Ct.resolve(e)}function Gd(e){return Ct.join(e,JN)}function Bd(e){return Ct.join(e,XN)}function dA(e){return Ct.join(e,zN)}function qy(e){return Ct.join(e,HN)}async function Dy(e){try{let t=await It.readFile(qy(e),"utf8"),n=Cs(t,"document version");if(!zn(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new we(Ne.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Ns(t))return 0;throw t}}async function wc(e){let t=await vs(e,Ne.RECOVERY_PENDING,"transaction journal"),n=Cs(Buffer.from(t).toString("utf8"),"transaction journal");return Qy(n),n}function Qy(e){if(!zn(e)||e.schemaVersion!==KN||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!GN(e.historyTransition)||!Array.isArray(e.files))throw new we(Ne.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!zn(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!bn(t.preDigest)||t.postDigest!==null&&!bn(t.postDigest))throw new we(Ne.INVALID_SCHEMA,"transaction journal file digest is invalid")}function fA(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Rs(e){return Ct.join(e,"entries")}function Ps(e){return Ct.join(e,"blobs")}function ks(e){return Ct.join(e,"tmp")}function Yd(e){return Ct.join(ks(e),"stages")}function Zd(e,t){return Ct.join(Yd(e),`${t}.json`)}function qd(e,t){return Ct.join(Rs(e),`${nx(t)}.json`)}function Qd(e,t){return Ct.join(Ps(e),nx(t))}function ef(e,t){return Ct.join(Rs(e),`${t}.json`)}function tf(e,t){return Ct.join(Ps(e),t)}async function pA(e,t){return tx(qd(e,t),ef(e,t))}async function ex(e,t){return tx(Qd(e,t),tf(e,t))}async function tx(e,t){return await ln(e)?e:await ln(t)?t:e}function nx(e){return e.slice(7)}function My(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return bn(t)?t:null}function zn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ns(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function mA(e){return{maxEntries:e?.maxEntries??Oc.maxEntries,maxSessionBytes:e?.maxSessionBytes??Oc.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Oc.maxEntryBytes}}async function gA(e){let t=Gd(e);await ln(t)||await zy(e,[],-1)}var yA={affectedCompositions:[]};function ax(e){let t=null,n=new WeakMap;async function r(){return t??=xA(e),t}async function o(i){if(!i)return null;let s=nf(i);return s?bA(e,s):i}return{async prepareAppend(i){let s=await mi(e),a=await e.stageAppend(ix(i),{durableManifest:!1}),l;try{l=await e.previewStagedAppend(a.entryId,s.digest)}catch(u){throw await e.discardStage(a.stageId),u}let c={kind:"append",entry:i,historyTransition:l};return n.set(c,{expectedDigest:s.digest,stageId:a.stageId,entryId:a.entryId}),c},async prepareUndo(){let i=await r(),s=await o(i.undo.at(-1));if(!s?.historyId)return null;let a=await mi(e),l=a.entryIds.indexOf(s.historyId);if(l<0)throw new Error("undo entry is missing from index");if(l!==a.cursor)throw new Error("undo state changed before prepare");let c=l-1,u=await e.previewCursor(c,a.digest),d={kind:"undo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:c}),d},async prepareRedo(){let i=await r(),s=await o(i.redo.at(-1));if(!s?.historyId)return null;let a=await mi(e),l=a.entryIds.indexOf(s.historyId);if(l<0)throw new Error("redo entry is missing from index");if(l!==a.cursor+1)throw new Error("redo state changed before prepare");let c=l,u=await e.previewCursor(c,a.digest),d={kind:"redo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:c}),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 l=await e.publishStagedAppend(s.entryId,s.expectedDigest,s.stageId);rx(l,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,gi(l))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let l=i.kind==="undo"?a.undo:a.redo;if(nf(l.at(-1))!==nf(i.entry))throw new Error("history state changed before publish");let c=await e.setCursor(s.cursor,s.expectedDigest);rx(c,i.historyTransition),Object.assign(a,gi(c))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let l=await mi(e);if(l.digest===a.publishedIndexDigest&&l.cursor===a.publishedCursor&&l.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,gi(d));return}catch(d){throw s.redo.push(i),d}}let l=await e.append(ix(i)),c=l.currentId;if(!c)throw new Error("history store did not publish an entry");i.historyId=c,Object.assign(s,gi(l))},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 l=s.entryIds.indexOf(a.historyId);if(l<0)throw s.undo.push(i),new Error("history entry is missing from the durable index");try{let c=await e.setCursor(l-1);Object.assign(s,gi(c))}catch(c){throw s.undo.push(i),c}},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 rx(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 nf(e){return typeof e=="string"?e:e?.historyId}async function xA(e){let t=await mi(e);return gi(t)}function gi(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function bA(e,t){let n=await e.readEntry(t),r=EA(n),o=r.provenance??yA;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 ox(e,n,r.preSnapshots),postSnapshots:await ox(e,n,r.postSnapshots)}}async function ox(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(vA(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function ix(e){let t=[],n=(i,s)=>i.map((a,l)=>{let c={file:a.file,exists:a.exists!==!1,version:a.version,...a.sha256?{sha256:a.sha256}:{}};if(c.exists){let u=`${s}-${l}`;c.blobName=u,t.push({name:u,data:a.content})}return c}),r=SA(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 EA(e){if(!lx(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:cx(t.provenance)}:{},preSnapshots:sx(t.preSnapshots,"preSnapshots"),postSnapshots:sx(t.postSnapshots,"postSnapshots")}}function SA(e){if(e.provenance!==void 0)return cx(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function cx(e){let t=hA.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 sx(e,t){return e.map((n,r)=>{if(!lx(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&&!IA(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 IA(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function vA(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function lx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{GeneratedSiteCapabilitiesSchema as kA}from"@vcp-dev/contracts";var ux={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 rf(){let e=kA.safeParse(ux);return e.success?e.data:null}import{randomBytes as _A}from"node:crypto";import Vc from"node:path";import{parse as yx}from"@babel/parser";import CA from"@babel/traverse";import*as xx from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as sf,PageResourceArtifactSchema as RA,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as PA,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as NA,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as AA,parseComponentI18nResourcesJson as TA}from"@vcp-dev/contracts";var af="{{$INSTANCE}}",wA=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,OA=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,cf="components/site/generated",LA=/\.(?:tsx?|json)$/,FA=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,DA=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],MA=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),of=CA,BA=typeof of=="function"?of:of.default;async function lf(e){let t=RA.safeParse(e.artifact);if(!t.success)return vt("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>_A(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=HA(r());if(!i)return vt("Random instance suffix must be 8 lowercase hex chars.");let s=`${WA(n.resource_id)}-${i}`,a=new Map,l=new Map,c=[];for(let E of n.pages){let S=E.final_route.slice(1);a.set(E.template_page_id,E.final_route),l.set(E.template_page_id,E.title),c.push({template_page_id:E.template_page_id,title:E.title,final_route:E.final_route,route_file_path:`app/${S}/page.tsx`})}let u=[],d=new Set,f=new Set,m=new Map,g=new Map,p=[],h=new Set(n.pages.flatMap(E=>E.components.map(S=>S.component_id)));for(let E of n.components){if(!h.has(E.component_id))continue;let S=dx({materialization:E.materialization,packageInstanceId:s,routeByPage:a,titleByPage:l});if(!S.ok)return S;for(let v of S.files){let A=px(v,d,u);if(A)return A}f.add(S.entry),g.set(S.entry,S.entryExport),m.set(E.component_id,S.entry)}for(let[E,S]of n.pages.entries()){let v=c[E],A=dx({materialization:S.materialization,packageInstanceId:s,routeByPage:a,titleByPage:l,pageEntryTarget:v.route_file_path,pageTitle:v.title});if(!A.ok)return A;for(let I of A.files){let _=px(I,d,u);if(_)return _}f.add(A.entry),g.set(A.entry,A.entryExport),p.push({entry:A.entry,declaredComponentIds:new Set(S.components.map(I=>I.component_id))})}let x=$A(u,f,s,m,p,g);if(!x.ok)return x;for(let E of u)if(await e.exists(E.file))return!E.file.startsWith("app/")&&o>1?lf({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${E.file}`,path:E.file};let b=UA(u);return b||(u.sort((E,S)=>E.file.localeCompare(S.file)),{ok:!0,packageInstanceId:s,pages:c,files:u})}function dx(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:fx(o.pathTemplate,e.packageInstanceId);if(!s)return vt("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=jA(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let l=i&&e.pageTitle!==void 0?KA(a.data,e.pageTitle,s):a;if(!l.ok)return l;n.push({operation:"create-only",file:s,content:l.data})}let r=e.pageEntryTarget??fx(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?vt("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function jA(e,t,n,r){let o,i=e.replace(wA,(l,c)=>{let u=n.get(c);return u||(o=c,l)});if(o)return vt(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(OA,(l,c)=>{let u=r.get(c);return u?JSON.stringify(u):(o=c,l)});if(o)return vt(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(af,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?vt("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function fx(e,t){let n=`${cf}/${t}`;if(e.split(af).length>2)return null;let o=e.replace(af,t),i=`${cf}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Vc.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!LA.test(a)||FA.test(a)?null:a}function px(e,t,n){return t.has(e.file)?vt(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function $A(e,t,n,r,o,i){let s=new Set(e.map(m=>m.file)),a=`${cf}/${n}`,l=new Map(e.map(m=>[m.file,new Set])),c=new Map;for(let m of e){if(m.file.endsWith(".json")){try{JSON.parse(m.content)}catch{return vt("Materialization JSON file must contain valid JSON.",m.file)}if(m.file.endsWith(sf)&&!TA(m.content).success)return vt("Materialization component i18n resources are invalid.",m.file);continue}try{let g=yx(m.content,{sourceType:"module",plugins:["jsx","typescript"]});c.set(m.file,g);for(let h of g.program.body)if((h.type==="ImportDeclaration"||h.type==="ExportAllDeclaration"||h.type==="ExportNamedDeclaration"&&h.source)&&h.source){let x=h.source.value,b=XA(m.file,x,s,a);if(!b.allowed)return vt(`Materialization import is outside the controlled package: ${x}`,m.file);b.internalPath&&l.get(m.file).add(b.internalPath)}let p;if(BA(g,{Identifier(h){h.isReferencedIdentifier()&&MA.has(h.node.name)&&(p??=h.node.name,h.stop())},JSXOpeningElement(h){h.node.name.type==="JSXIdentifier"&&h.node.name.name.toLowerCase()==="style"&&(p??="style element",h.stop())}}),p)return vt(`Materialization source uses forbidden capability: ${p}`,m.file)}catch{return vt("Materialization source must parse as TS/TSX.",m.file)}}if([...t].some(m=>!s.has(m)))return vt("Materialization entry is outside the controlled package.");for(let m of t)if(m.endsWith(".json"))return vt("Materialization JSON files cannot be package entries.");for(let[m,g]of i){let p=c.get(m);if(!p||!VA(p,g))return vt("Materialization entry does not declare its contracted export.",m)}let u=new Map([...r].map(([m,g])=>[g,m]));for(let m of o){let g=hx(m.entry,l);for(let p of m.declaredComponentIds){let h=r.get(p);if(!h||!g.has(h))return vt(`Page entry does not reach declared component: ${p}`,m.entry)}for(let p of g){let h=u.get(p);if(h&&!m.declaredComponentIds.has(h))return vt(`Page entry imports undeclared component: ${h}`,m.entry)}}let d=new Set;for(let m of t)for(let g of hx(m,l))d.add(g);if(d.size!==e.length)return vt("Every materialization file must be reachable from a package entry.");let f=zA(e,c,l);return f||{ok:!0}}function UA(e){if(e.length>PA)return vt("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>NA)return vt("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>AA?vt("Page resource exceeds the aggregate content byte limit."):null}function VA(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 KA(e,t,n){let r;try{r=yx(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return vt("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=mx(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let l=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&JA(u.key));if(!l||l.type!=="ObjectProperty")return{ok:!0,data:e};let c=mx(l.value);return c?c.type!=="StringLiteral"&&c.type!=="TemplateLiteral"||c.type==="TemplateLiteral"&&c.expressions.length>0||typeof c.start!="number"||typeof c.end!="number"?{ok:!0,data:e}:{ok:!0,data:e.slice(0,c.start)+JSON.stringify(t)+e.slice(c.end)}:{ok:!0,data:e}}}return{ok:!0,data:e}}function mx(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&xx.isExpression(t)?t:null}function JA(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function XA(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=gx(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=Vc.posix.normalize(Vc.posix.join(Vc.posix.dirname(e),t)),i=gx(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function gx(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 zA(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(sf))continue;let i=o.file.slice(0,-sf.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return vt("Component i18n resources require a same-name TS/TSX companion.",o.file);let l=t.get(s)?.program.directives.some(u=>u.value.value==="use client"),c=[...n].filter(([,u])=>u.has(o.file));if(!l||c.length!==1||c[0]?.[0]!==s)return vt("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function hx(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 HA(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function WA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function vt(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as ET}from"node:crypto";import Lr from"node:path";import{parse as ST}from"@babel/parser";import IT from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Jc,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as _x,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as vT,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as kT,SiteEditMaterializationSchema as _T,parseComponentI18nResourcesJson as CT}from"@vcp-dev/contracts";import{parse as uT}from"@babel/parser";import dT from"@babel/traverse";import{GeneratedSiteCapabilitiesSchema as fT,FormDefinitionIdSchema as pT}from"@vcp-dev/contracts";var Ex={colorMixPolicy:"always",includeExtendedColorFunctions:!0},Sx=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,Ix=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,GA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,YA=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,ZA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,qA=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,QA=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,eT=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,tT=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,nT=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,rT=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,oT=/\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,iT=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,sT=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function uf(e,t){let n=Kc([...Bn(e,GA),...Bn(e,YA),...Bn(e,ZA),...Bn(e,t.includeRgbBackgroundImage?qA:QA),...t.includeExtendedColorFunctions?[...Bn(e,eT),...Bn(e,tT)]:[]]),r=Kc([...Bn(e,nT),...Bn(e,rT)]).filter(o=>t.colorMixPolicy==="always"||Sx.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...Bn(e,oT).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...Bn(e,sT).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Kc(Bn(e,Ix)),hardCodedSurfaceOccurrences:lT(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?aT(e):[]}}function aT(e){return Kc(Bn(e,iT))}function Bn(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var bx=160,cT=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function lT(e){let t=new RegExp(Ix.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,l=n.length-1;for(;a<l;){let c=Math.ceil((a+l)/2);(n[c]??0)<=s?a=c:l=c-1}return a},o=[],i;for(;(i=t.exec(e))!==null;){let s=i[0],a=s.endsWith("/")?s.slice(0,-1):s,l=/^\/(\d+)/.exec(e.slice(i.index+a.length)),c=e.slice(Math.max(0,i.index-64),i.index),u=cT.exec(c),d=r(i.index),f=e.indexOf(`
|
|
6
|
+
`,i.index),m=e.slice(n[d]??0,f===-1?void 0:f).trim();o.push({token:a,variant:u?.[1]??"",alpha:l?Number(l[1]):null,line:d+1,snippet:m.length>bx?`${m.slice(0,bx-1)}\u2026`:m})}return o}function Kc(e){return[...new Set(e)]}var mT=["@/components/site/","@/lib/generated/","@/lib/cms","@/lib/cms/"],gT=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),vx=new Set(["require","module","exports","__dirname","__filename"]),df=dT,hT=typeof df=="function"?df:df.default;function pf(e,t={}){let n=[],r=yT(t.hostCapabilities),o=uf(e,t.style??Ex),i;try{i=uT(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"&&bT(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 hT(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){c(ff(u.node))},OptionalMemberExpression(u){c(ff(u.node))},Identifier(u){u.isReferencedIdentifier()&&c(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)&&pT.safeParse(/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(u)?.[1]).success)&&!(u.startsWith("./")||u.startsWith("../"))){if(t.allowSiteOwnedImports&&mT.some(d=>d.endsWith("/")?u.startsWith(d):u===d)){l(u);return}r?xT(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}),l(u)}}function l(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 c(u){if(!(!u||!gT.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:vx.has(u)?"commonjs-forbidden":"browser-global-forbidden",message:vx.has(u)?`Generated source cannot depend on the CommonJS global ${u}.`:`Generated source cannot depend on the restricted global ${u}.`,name:u})}}}function yT(e){if(e==null)return null;let t=fT.safeParse(e);return t.success?t.data:null}function xT(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)):kx(n)===kx(o)})}function kx(e){return e.replace(/\.(?:jsx?|tsx?|json)$/i,"")}function bT(e){return e.hardCodedSurfaceHits.length>0||e.rawColorHits.length>0||e.privateTokenHits.length>0}function ff(e){return e.type==="Identifier"?e.name:e.type==="MemberExpression"||e.type==="OptionalMemberExpression"?ff(e.object):null}var Tx="components/site/generated",Cx="{{$INSTANCE}}",Xc=5,RT=/^[a-z][a-z0-9-]{0,48}$/,PT=/^[a-f0-9]{8}$/,Rx=/\.tsx?$/,NT=/\.json$/,AT=/\.(?:tsx?|json)$/,TT=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,mf=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),gf=IT,wT=typeof gf=="function"?gf:gf.default;function OT(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>_x)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=WT(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=_T.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=XT(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Tx}.`,path:e.generatedRoot}};if(!wx(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=Nx(r.data.files),s=Nx(e.controlledFiles);if(!GT(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>_x)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[l,c]of r.data.files.entries()){let u=Buffer.byteLength(c.content,"utf8");if(u>vT)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file exceeds the per-file content limit.",file:c.pathTemplate,path:`files[${l}]`}};a+=u}return a>kT?{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=OT(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=wx(e.manifest.instanceBaseName),o=Math.max(1,Math.min(Xc,e.maxAttempts??Xc));for(let i=0;i<o;i+=1){let s=zT(e.instanceNameGenerator?.()??ET(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}`,l=Lx(n,a),c=FT({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:l,hostCapabilities:e.hostCapabilities??null,availableHostDependencies:e.availableHostDependencies});if(!c.ok)return c;if(!await MT(e.exists,l,c.data.files))return{ok:!0,data:c.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function hf(e){let t=Math.max(1,Math.min(Xc,e.maxAttempts??Xc));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 FT(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=As({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=As({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=yf({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 MT(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function As(e){if(e.pathTemplate.split(Cx).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(Cx,e.instanceName),n=HT(t);return n?Lx(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||!AT.test(n)||TT.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 yf(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(m=>m.path)),l=new Map,c=new Map(t.map(m=>[m.path,new Set])),u=new Map;for(let m of t){if(NT.test(m.path)){if(m.path.endsWith(Jc)){let x=CT(m.content);if(!x.success)return Or("MATERIALIZATION_DATA_UNSUPPORTED",x.error.message,m.path);u.set(m.path,new Set)}else try{JSON.parse(m.content)}catch{return Or("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",m.path)}continue}let g;try{g=ST(m.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:m.path}}}let p=pf(m.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}}),h=jT(p.violations,m.path);if(h)return{ok:!1,error:h};l.set(m.path,g)}for(let m of t){if(!Rx.test(m.path))continue;let g=l.get(m.path),p=null;if(wT(g,{ImportDeclaration(h){let x=Px({importer:m.path,source:h.node.source.value,instanceRoot:n,filePaths:a});if(!x.allowed)p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:m.path},h.stop();else if(!x.internalPath&&!$T(h.node.source.value,i,s))p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"External prefab imports must be declared and available in the target host.",file:m.path},h.stop();else if(x.internalPath&&(c.get(m.path).add(x.internalPath),x.internalPath.endsWith(Jc))){let b=VT({importer:m.path,imported:x.internalPath,source:h.node.source.value,ast:g});b.ok?u.get(x.internalPath).add(m.path):(p??=b.error,h.stop())}},ExportAllDeclaration(h){p??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:m.path},h.stop()},ExportNamedDeclaration(h){if(h.node.source){let x=Px({importer:m.path,source:h.node.source.value,instanceRoot:n,filePaths:a});!x.allowed||!x.internalPath&&!e.trustedManagedImports?.includes(h.node.source.value)?(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:m.path},h.stop()):x.internalPath&&c.get(m.path).add(x.internalPath)}},CallExpression(h){if(h.node.callee.type==="Import"){p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:m.path},h.stop();return}h.node.callee.type==="Identifier"&&h.node.callee.name==="require"&&(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:m.path},h.stop())},NewExpression(h){h.node.callee.type==="Identifier"&&h.node.callee.name==="Function"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:m.path},h.stop())},MetaProperty(h){h.node.meta.type==="Identifier"&&h.node.meta.name==="import"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:m.path},h.stop())},MemberExpression(h){let x=Ax(h.node);x&&mf.has(x)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:m.path},h.stop())},OptionalMemberExpression(h){let x=Ax(h.node);x&&mf.has(x)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:m.path},h.stop())},Identifier(h){h.isReferencedIdentifier()&&mf.has(h.node.name)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h.node.name}.`,file:m.path},h.stop())},JSXAttribute(h){!e.preserveCapturedStyles||h.node.name.type!=="JSXIdentifier"||h.node.name.name!=="style"||BT(h.node.value)||(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:m.path},h.stop())},JSXOpeningElement(h){h.node.name.type==="JSXIdentifier"&&h.node.name.name.toLowerCase()==="style"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:m.path},h.stop())},StringLiteral(h){e.preserveCapturedStyles&&zc(h.node.value)&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:m.path},h.stop())},TemplateElement(h){e.preserveCapturedStyles&&zc(h.node.value.cooked??h.node.value.raw)&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:m.path},h.stop())},JSXElement(h){let x=h.node.openingElement.name;e.preserveCapturedStyles&&x.type==="JSXIdentifier"&&["script","iframe","object","embed"].includes(x.name.toLowerCase())&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Captured components cannot embed executable external documents.",file:m.path},h.stop())}}),p)return{ok:!1,error:p}}if(r.length===0)return Or("MATERIALIZATION_ENTRY_INVALID","Static prefab requires at least one source entry.");let d=new Set;for(let m of r){if(d.has(m.path))return Or("MATERIALIZATION_PATH_INVALID",`Static prefab contains duplicate source entries: ${m.path}`,m.path);if(d.add(m.path),!Rx.test(m.path))return Or("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",m.path);let g=l.get(m.path);if(!g)return Or("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",m.path);if(!KT(g,m.export))return Or("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",m.path)}for(let[m,g]of u)if(g.size!==1)return Or("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",m);let f=new Set;for(let m of r)for(let g of JT(m.path,c))f.add(g);return f.size!==t.length?Or("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",r[0]?.path):{ok:!0}}function zc(e){return/(?:url|expression)\s*\(|@import|javascript:|-moz-binding|\\/iu.test(e)}function BT(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"||zc(n))return!1;let r=t.value;return r.type==="StringLiteral"&&!zc(r.value)||r.type==="NumericLiteral"||r.type==="NullLiteral"||r.type==="UnaryExpression"&&["-","+"].includes(r.operator)&&r.argument.type==="NumericLiteral"})}function jT(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 Px(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return{allowed:!0};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Lr.posix.normalize(Lr.posix.join(Lr.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 $T(e,t,n){if(n===null)return!0;let r=UT(e);return r===null||t.has(r)&&n.has(r)}function UT(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 VT(e){let t=Lr.posix.dirname(e.importer),n=Lr.posix.dirname(e.imported),r=Lr.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Lr.posix.basename(e.imported).slice(0,-Jc.length),i=`./${r}${Jc}`;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 KT(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 JT(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 Or(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function XT(e){let t=Ox(e);return t===Tx?t:null}function zT(e){let t=e.trim().toLowerCase();return PT.test(t)?t:null}function wx(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 RT.test(t)?t:null}function Ox(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Lr.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function HT(e){let t=Ox(e);return!t||t!==e?null:t}function Lx(...e){return Lr.posix.join(...e)}function Nx(e){return new Set(e.map(t=>t.pathTemplate))}function WT(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 GT(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Ax(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 Kf}from"node:crypto";import Df from"@babel/traverse";function xf(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 l=Object.freeze([...a]),c=l.find(u=>u.anchorSourceRange!==null&&u.members.length>0)??l.find(u=>u.members.length>0)??l[0];c&&(o.set(s,l),i.set(s,c),r.set(s,Object.freeze({placementUnitKey:s,placementKeys:Object.freeze(l.map(u=>u.placementKey)),sourcePlacementKey:c.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}function Hc(e){if(e.node.alternate||!YT(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,l=a.type==="Identifier"?a.name:a.value,c=s.path.parentPath;return!!(l==="notFound"&&c?.isImportDeclaration()&&c.node.importKind!=="type"&&c.node.source.value==="next/navigation")}function YT(e){let t=Fx(e);return e.traverse({enter(n){Fx(n)||(t=!1,n.stop())}}),t}function Fx(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 Ew}from"node:crypto";import zx from"node:path";import*as xi from"@babel/parser";import Rf from"@babel/traverse";import Pf from"@babel/generator";import*as Se from"@babel/types";import vf from"@babel/generator";import{parse as aw}from"@babel/parser";import kf from"@babel/traverse";import*as $e from"@babel/types";import{PortableInvocationBindingSchema as cw}from"@vcp-dev/contracts";import bf from"@babel/traverse";import*as Je from"@babel/types";var Dx=typeof bf=="function"?bf:bf.default;function En(e){let t=Bx(e.module,e.exportName,e.parsedModules??new Map([[e.module.file,e.module]]),new Set);return t?Mx(t,e.allowNonRenderingGuards):Qr("component-export-unresolved","The requested local component export is not a statically resolvable function.",e.module.file)}function lr(e){let t=ZT(e.module,e.componentName,e.callSourceRange);return t.kind==="local"?Mx(t.definition):t.kind==="imported"?!e.imported?.module&&!kt(t.specifier)?Qr("component-external-module-opaque","External package components are opaque to the local source graph.",t.specifier):e.imported?e.imported.module?En({module:e.imported.module,exportName:e.imported.exportName,parsedModules:e.imported.parsedModules}):Qr("component-module-unavailable","The component source module is unavailable in the parsed graph.",e.imported.file):Qr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file):Qr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file)}function Mx(e,t=!1){let n=nw(e.module.ast,e.node);if(!n)return Qr("component-function-unresolved","The component function has no source AST path.",e.module.file);let r=jx(n,t);if(!r){let s=ow(n);return s?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:!1,roots:[s[0]],returnAlternatives:s}:Qr("component-control-flow-unsupported","Component roots require an expression body or one direct return.",e.module.file)}let o=[],i=$x(r);return Gc(r,o)?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:i,roots:o}:Qr("component-root-dynamic","Component return contains an unsupported dynamic or spread root.",e.module.file)}function ZT(e,t,n){let r={kind:"unresolved"};return Dx(e.ast,{JSXElement(o){if(!ew(o.node.loc,n))return;let i=o.node.openingElement.name;if(!Je.isJSXIdentifier(i)||i.name!==t)return;let s=o.scope.getBinding(t);if(!s||s.constantViolations.length>0){o.stop();return}if(qT(s.path)){let l=s.path.parentPath;l?.isImportDeclaration()&&(r={kind:"imported",specifier:l.node.source.value}),o.stop();return}let a=QT(s.path);a&&(r={kind:"local",definition:{node:a,name:t,module:e}}),o.stop()}}),r}function qT(e){return e.isImportSpecifier()||e.isImportDefaultSpecifier()||e.isImportNamespaceSpecifier()}function QT(e){if(e.isFunctionDeclaration())return e.node;if(!e.isVariableDeclarator())return null;let t=e.get("init");return!Array.isArray(t)&&If(t.node)?t.node:null}function ew(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 Bx(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=Xr(e.file,u,n),m=f?n.get(f):void 0;return m?Bx(m,d,n,i):null},a=u=>{let d=tw(e,u);if(d)return{...d,module:e};for(let f of e.ast.program.body)if(!(!Je.isImportDeclaration(f)||f.importKind==="type")){for(let m of f.specifiers)if(m.local.name===u){if(Je.isImportDefaultSpecifier(m))return s(f.source.value,"default");if(Je.isImportSpecifier(m)&&m.importKind!=="type")return s(f.source.value,Wc(m.imported))}}return null};for(let u of e.ast.program.body){if(Je.isExportDefaultDeclaration(u)&&t==="default"){let d=u.declaration;if(If(d))return{node:d,name:sw(d)??"default",module:e};if(Je.isIdentifier(d))return a(d.name)}if(!(!Je.isExportNamedDeclaration(u)||u.exportKind==="type")){if(u.declaration){let d=iw(u.declaration,t);if(d)return a(d)}for(let d of u.specifiers)if(Je.isExportSpecifier(d)&&d.exportKind!=="type"&&Wc(d.exported)===t)return u.source?s(u.source.value,Wc(d.local)):a(Wc(d.local))}}let l=e.ast.program.body.flatMap(u=>{if(!Je.isExportAllDeclaration(u)||u.exportKind==="type"||t==="default")return[];let d=s(u.source.value,t);return d?[d]:[]}),c=l.filter((u,d)=>l.findIndex(f=>f.node===u.node&&f.module.file===u.module.file)===d);return c.length===1?c[0]:null}function tw(e,t){for(let n of e.ast.program.body){let r=Je.isExportNamedDeclaration(n)?n.declaration:n;if(Je.isFunctionDeclaration(r)&&r.id?.name===t)return{node:r,name:t};if(Je.isVariableDeclaration(r)){for(let o of r.declarations)if(Je.isIdentifier(o.id)&&o.id.name===t&&If(o.init))return{node:o.init,name:t}}}return null}function nw(e,t){let n=null;return Dx(e,{Function(r){r.node===t&&(n=r,r.stop())}}),n}function jx(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()||rw(i)||t&&i.isIfStatement()&&Hc(i))?null:o.get("argument")}function rw(e){if(!e.isExpressionStatement())return!1;let t=e.get("expression");if(!t.isCallExpression())return!1;let n=t.get("callee");if(!n.isIdentifier())return!1;let r=n.scope.getBinding(n.node.name);if(!r?.constant||!r.path.isImportSpecifier())return!1;let o=r.path.node.imported,i=r.path.parentPath;if(!Je.isIdentifier(o,{name:"useEffect"})||!i?.isImportDeclaration()||i.node.source.value!=="react"||i.node.importKind==="type"||r.path.node.importKind==="type")return!1;let s=t.get("arguments")[0];return!!(s&&(s.isArrowFunctionExpression()||s.isFunctionExpression()))}function ow(e){let t=e.get("body");if(!t.isBlockStatement())return null;let n=Ef(t.get("body"));if(!n||n.length<2)return null;let r=[],o=null;for(let i of n){if(!i.isJSXElement())return null;let s=i.node.openingElement.name;if(!Je.isJSXIdentifier(s)||!/^[A-Z]/.test(s.name))return null;let a=i.scope.getBinding(s.name);if(!a||a.constantViolations.length>0||o&&o!==a.path.node||(o=a.path.node,i.node.children.some(l=>!Je.isJSXText(l)||l.value.trim()!=="")||i.node.openingElement.attributes.some(l=>Je.isJSXSpreadAttribute(l)||Je.isJSXAttribute(l)&&Je.isJSXIdentifier(l.name,{name:"children"}))))return null;r.push(i)}return r}function Ef(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=>Ef(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:Ef(e.slice(t+1));return o&&s?[...o,...s]:null}return null}function Gc(e,t){if($x(e))return!0;if(e.isJSXFragment()||e.isJSXElement()&>(e)){let n=e.get("children");for(let r of Array.isArray(n)?n:[n])if(!r.isJSXText()&&(r.isJSXSpreadChild()||!Gc(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()||Gc(n,t)}return e.isParenthesizedExpression()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTypeCastExpression()?Gc(e.get("expression"),t):e.isNullLiteral()||e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()}function Sf(e){return["base","link","meta","script","style","title"].includes(e)}function $x(e){let t=!1,n=r=>{if(r.isJSXElement()){let o=r.node.openingElement.name;return Je.isJSXIdentifier(o)&&Sf(o.name)?(t=!0,!0):gt(r)?r.get("children").every(i=>n(i)):!1}if(r.isJSXFragment())return r.get("children").every(o=>n(o));if(r.isJSXText())return r.node.value.trim()==="";if(r.isNullLiteral()||r.isBooleanLiteral()||r.isJSXEmptyExpression())return!0;if(r.isJSXExpressionContainer()||r.isParenthesizedExpression()||r.isTSAsExpression()||r.isTSTypeAssertion()||r.isTSNonNullExpression())return n(r.get("expression"));if(r.isConditionalExpression())return n(r.get("consequent"))&&n(r.get("alternate"));if(r.isArrayExpression())return r.get("elements").every(o=>!o.node||n(o));if(r.isCallExpression()){let o=r.get("callee"),i=r.get("arguments");if(!o.isMemberExpression()||o.node.computed||!Je.isIdentifier(o.node.property,{name:"map"})||i.length!==1)return!1;let s=i[0];if(!s.isArrowFunctionExpression()&&!s.isFunctionExpression())return!1;let a=jx(s);return a!==null&&n(a)}return!1};return n(e)&&t}function iw(e,t){return Je.isFunctionDeclaration(e)?e.id?.name===t?t:null:Je.isVariableDeclaration(e)&&e.declarations.some(n=>Je.isIdentifier(n.id)&&n.id.name===t)?t:null}function If(e){return Je.isFunctionDeclaration(e)||Je.isFunctionExpression(e)||Je.isArrowFunctionExpression(e)}function sw(e){return"id"in e&&e.id&&Je.isIdentifier(e.id)?e.id.name:null}function Wc(e){return Je.isIdentifier(e)?e.name:e.value}function Qr(e,t,n){return{ok:!1,diagnostic:{code:e,message:t,file:n}}}var _f=typeof vf=="function"?vf:vf.default,Ux=typeof kf=="function"?kf:kf.default,Kx=new Set(["sourceBlockId","source_block_id","originalBlockId","original_block_id"]),lw=new Set(["sourceOrder","source_order","originalOrder","original_order"]),uw=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"]),dw=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,fw=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u;function to(e){if(!Xx(e)||!Array.isArray(e.bindings))return eo("INVOCATION_INPUT_INVALID","bindings must be an array in a portable invocation.","bindings");let t=hw(e);if(!t||!fw.test(t))return eo("INVOCATION_COMPONENT_INVALID","Portable invocation requires a safe JSX component local name.","component");let n=Jx(e.targetBlockId);if(!n.ok)return n;let r=yw(e.targetOrder);if(!r.ok)return r;let o=e.searchParamsIdentifier??"searchParams";if(!dw.test(o))return eo("INVOCATION_VALUE_UNRESOLVED","The route searchParams binding requires a safe local identifier.","searchParamsIdentifier");let i=[],s=[],a=new Set,l=!1,c=!1,u=0;for(let[f,m]of e.bindings.entries()){let g=cw.safeParse(m);if(!g.success)return eo("INVOCATION_VALUE_UNRESOLVED","Portable invocation values must use the closed JSON/server/identity contract.",`bindings.${f}`);let p=g.data;if(a.has(p.propName))return eo("INVOCATION_DUPLICATE_PROP",`Portable invocation contains duplicate prop ${p.propName}.`,`bindings.${f}.propName`);if(a.add(p.propName),lw.has(p.propName))return eo("INVOCATION_SOURCE_METADATA","Source block order cannot be copied or rebound as a component prop.",`bindings.${f}`);if(Kx.has(p.propName)&&p.value.kind!=="target-block-id")return eo("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 eo("INVOCATION_DUPLICATE_PROP","A portable invocation may bind the target block identity only once.",`bindings.${f}`);p.value.kind==="route-search-params"&&(l=!0),p.value.kind==="route-params"&&(c=!0),s.push(p),i.push($e.jsxAttribute($e.jsxIdentifier(p.propName),$e.jsxExpressionContainer(mw(p.value,n.value,o))))}let d=$e.jsxElement($e.jsxOpeningElement(gw(t),i,!0),null,[],!0);return{ok:!0,plan:{kind:"portable-invocation",component:t,jsx:_f(d,{jsescOption:{minimal:!0}}).code,bindings:s,targetBlockId:n.value,targetOrder:r.value,requiresRouteSearchParams:l,requiresRouteParams:c,searchParamsIdentifier:l?o:null}}}function pw(e){if(!Xx(e)||e.jsx===void 0==(e.source===void 0))return hi("BLOCK_METADATA_INPUT_INVALID","Provide exactly one JSX expression or full source module.","input");let t=Jx(e.targetBlockId);if(!t.ok)return hi("BLOCK_METADATA_TARGET_INVALID",t.error.message,"targetBlockId");if(!Number.isSafeInteger(e.targetOrder)||e.targetOrder<0)return hi("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 m=Te("portable-entry.tsx",e.source);if(!m.ok)throw new Error(m.diagnostic.message);o=m.module,r=o.ast}else r=aw(n?e.jsx:e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(m){return hi("BLOCK_METADATA_PARSE_FAILED",m instanceof Error?m.message:String(m),n?"jsx":"source")}let i=[],s;if(o&&e.entryExport){let m=En({module:o,exportName:e.entryExport.kind==="default"?"default":e.entryExport.name});m.ok&&m.roots.length===1&&(s=m.roots[0],i.push(s.node))}else Ux(r,{JSXElement(m){Vx(m)||i.push(m.node)},JSXFragment(m){Vx(m)||i.push(m.node)}});if(i.length!==1)return hi("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one JSX root.",n?"jsx":"source");let a=i[0],l=xw(a);if(!l)return hi("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one direct JSX element root.",n?"jsx":"source");let c=0,u=0,d=m=>{let g=bw(m.node.name);!g||!uw.has(g)||(g==="data-site-block-id"||g==="data-vcp-block-id"||Kx.has(g)?c+=1:u+=1,m.remove())};s?s.traverse({JSXAttribute:d}):Ux(r,{JSXAttribute:d}),l.openingElement.attributes.push($e.jsxAttribute($e.jsxIdentifier("data-site-block-id"),$e.stringLiteral(t.value)),$e.jsxAttribute($e.jsxIdentifier("data-site-block-order"),$e.jsxExpressionContainer($e.numericLiteral(e.targetOrder))));let f=n?_f(a,{jsescOption:{minimal:!0}}).code:_f(r,{jsescOption:{minimal:!0}}).code;return{ok:!0,plan:{kind:"portable-block-metadata",source:f,jsx:f,targetBlockId:t.value,targetOrder:e.targetOrder,removedSourceBlockIdCount:c,removedSourceOrderCount:u}}}function mw(e,t,n){return e.kind==="route-params"?$e.identifier("params"):e.kind==="route-search-params"?$e.identifier(n):e.kind==="target-block-id"?$e.stringLiteral(t):Cf(e.value)}function Cf(e){return e===null?$e.nullLiteral():typeof e=="string"?$e.stringLiteral(e):typeof e=="number"?$e.numericLiteral(e):typeof e=="boolean"?$e.booleanLiteral(e):Array.isArray(e)?$e.arrayExpression(e.map(t=>Cf(t))):$e.objectExpression(Object.entries(e).map(([t,n])=>$e.objectProperty($e.stringLiteral(t),Cf(n))))}function gw(e){let t=e.split("."),n=$e.jsxIdentifier(t[0]);for(let r of t.slice(1))n=$e.jsxMemberExpression(n,$e.jsxIdentifier(r));return n}function hw(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 Jx(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 yw(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 xw(e){if($e.isJSXElement(e))return e;let t=e.children.filter($e.isJSXElement),n=e.children.some(r=>$e.isJSXText(r)&&r.value.trim().length>0);return t.length===1&&!n?t[0]??null:null}function Vx(e){let t=e.parentPath;for(;t;){if(t.isJSXElement()||t.isJSXFragment())return!0;t=t.parentPath}return!1}function bw(e){return $e.isJSXIdentifier(e)?e.name:null}function Xx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eo(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}function hi(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}var Nf=typeof Pf=="function"?Pf:Pf.default,Sw=typeof Rf=="function"?Rf:Rf.default;function Ls(e){let t=qx(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Ff(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=kw(n,o),s=Lw(e);if(!s.ok)return s;let a={jsx:s.invocation?.jsx??`<${e.component.localName} />`},l=Iw(e);if(i){let g=Af(e);return g.ok?{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:l,...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:g.locator,sourceHash:g.sourceHash,node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:g.result}let c=o.containerSourceRange??n.container.sourceRange,u=o.containerSourceHash??(Zc(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!u)return Ts("Route page composition does not expose a verifiable container boundary.");let d=Os(c),f=Wx(e.source,d,u,"Route page composition container");if(!f.ok)return f.result;let m=o.anchorSourceRange?Os(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return Ts("Route page composition placement does not expose a verifiable anchor boundary.");let g=Wx(e.source,m,o.anchorSourceHash,"Route page composition anchor");if(!g.ok)return g.result}return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:l,...s.invocation?{invocation:s.invocation}:{},...s.serverParamsStep?{serverParamsStep:s.serverParamsStep}:{},insertStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...m?{anchorLocator:m}:{}},rewriteStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...m?{anchorLocator:m}:{}}}}}function Of(e){let t=Te(e.entryFile,e.source);if(!t.ok)return no("PORTABLE_ROUTE_SOURCE_INVALID",t.diagnostic.message);let n=Hn({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 no("PORTABLE_ROUTE_UNSUPPORTED","Portable route does not expose a supported page-composition boundary.",n.projection.diagnostics);let r=n.projection.placements.flatMap(c=>{if(c.relation!==e.anchor.relation)return[];if(e.anchor.sourceRange)return c.anchorSourceRange&&Zc(c.anchorSourceRange,e.anchor.sourceRange)?[{placement:c,matchCount:1}]:[];let u=c.members.reduce((d,f)=>d+Yx(f,e.anchor.componentName),0);return u===0?[]:[{placement:c,matchCount:u}]}),o=r.reduce((c,u)=>c+u.matchCount,0);if(o===0)return no("PORTABLE_ROUTE_ANCHOR_MISSING","Portable route anchor was not found in the canonical page composition.");if(o!==1||r.length!==1)return no("PORTABLE_ROUTE_ANCHOR_AMBIGUOUS","Portable route anchor does not identify exactly one page-composition gap.");let i=Ls({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 c=Fs({source:s,locator:a.locator,expectedSourceHash:a.sourceHash,action:{kind:"insert",jsx:a.node.jsx,placement:a.placement,replaceOriginal:a.replaceOriginal}});if(!c.ok)return no("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message);s=c.source}else{let c=Fn({source:s,locator:a.parentLocator,node:a.node,placement:a.placement,...a.anchorLocator?{anchorLocator:a.anchorLocator}:{}});if(!c.ok)return no("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message);s=c.source}if(i.plan.serverParamsStep){let c=Qx({source:s,step:i.plan.serverParamsStep});if(!c.ok)return no("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message);s=c.source}let l=Dn({source:s,moduleSpecifier:i.plan.importStep.moduleSpecifier,imports:i.plan.importStep.imports});return l.ok?{ok:!0,plan:i.plan,patch:{kind:"portable-route-composition-patch",path:e.entryFile,expectedSourceHash:t.module.sourceHash,source:l.source}}:no("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message)}function Yx(e,t){return(e.label===t?1:0)+e.children.reduce((n,r)=>n+Yx(r,t),0)}function no(e,t,n=[]){return{ok:!1,error:{code:e,message:t,diagnostics:n}}}function Iw(e){let t=Pw(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 Fs(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Mo(e.source,"Root expression rewrite requires an exact expression locator.");let t=as(e.source,"value");if(!t.ok)return Mo(e.source,t.diagnostic.message);let n=De(t.ast,e.locator);if(!n.ok)return Mo(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Mo(e.source,"Resolved value locator does not point to an expression.");let o=yi(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Mo(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(Se.nullLiteral()),{ok:!0,source:Nf(t.ast,{}).code};let i;try{i=xi.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Mo(e.source,s instanceof Error?s.message:String(s))}return!Se.isJSXElement(i)&&!Se.isJSXFragment(i)?Mo(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(vw(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Nf(t.ast,{}).code})}function vw(e,t,n,r){if(Se.isNullLiteral(e)||r)return t;let o=Se.isJSXFragment(e)?[...e.children]:[Se.isJSXElement(e)?e:Se.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return Se.jsxFragment(Se.jsxOpeningFragment(),Se.jsxClosingFragment(),s)}function Mo(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function Lf(e){let t=qx(e);if(t)return{ok:!1,error:t};let n=e.projection,r=ib(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(_w(n,o)){let p=Af(e);return p.ok?e.operation==="remove-node"&&!Hx(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=Os(o.sourceRange),a=sr(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?[]:[ws(a.diagnostic)]}};if(yi(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=Af(e);return p.ok?Hx(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||!Rw(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 c=Ff(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!c.ok)return{ok:!1,error:{code:c.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:c.diagnostic.message,diagnostics:[c.diagnostic]}};let u=c.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=Os(d),m=sr(e.source,f);if(!m.ok||!m.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:m.ok===!1?m.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:m.ok?[]:[ws(m.diagnostic)]}};if(yi(e.source,m.match.node.start??null,m.match.node.end??null)!==u.containerSourceHash)return Gx("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let p=u.anchorSourceRange,h=u.anchorSourceHash;if(!p||!h)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=Os(p),b=sr(e.source,x);return!b.ok||!b.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:b.ok===!1?b.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:b.ok?[]:[ws(b.diagnostic)]}}:yi(e.source,b.match.node.start??null,b.match.node.end??null)!==h?Gx("Route page composition target anchor hash no longer matches the current source."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:f,anchorLocator:x,placement:u.relation}}}}return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:f,placement:u.relation}}}}function Hx(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function kw(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&Zc(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 _w(e,t){return e.container.kind!=="jsx-container"&&Zc(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function Af(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=sr(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?[]:[ws(r.diagnostic)]}}}:yi(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Zx("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function Wx(e,t,n,r){let o=sr(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?[]:[ws(o.diagnostic)]}}}:yi(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Zx(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Zx(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 Gx(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function ws(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function qx(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&&!Cw(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 Cw(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Rw(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function Pw(e,t){let n=zx.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=zx.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Os(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function yi(e,t,n){return t==null||n==null?null:`sha256:${Ew("sha256").update(e.slice(t,n)).digest("hex")}`}function Zc(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 Qx(e){let t;try{t=xi.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=Nw(t,e.step);return n.ok?{ok:!0,source:Nf(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:n.message}}}function Nw(e,t){let n=rb(e);if(!n)return{ok:!1,message:"Route default function could not be resolved for searchParams wiring."};let r=wf(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."}:tb(r)!==t.identifier?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:{ok:!0};let o=eb(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?Tf():Aw()),{ok:!0};let i=n.node.params[0],s=wf(i);return s?(Tw(s,t.typescript),{ok:!0}):{ok:!1,message:"Route page parameter is not a supported object pattern."}}function Aw(){return Se.objectPattern([Se.objectProperty(Se.identifier("searchParams"),Se.identifier("searchParams"),!1,!0)])}function Tf(){let t=xi.parse("function __PortablePage({ searchParams }: { searchParams?: Promise<Record<string, string | string[] | undefined>> }) {}",{sourceType:"module",plugins:["typescript"]}).program.body[0];if(!Se.isFunctionDeclaration(t))throw new Error("Failed to construct the canonical searchParams type.");let n=t.params[0];if(!Se.isObjectPattern(n))throw new Error("Failed to construct the canonical searchParams pattern.");return Se.cloneNode(n,!0)}function Tw(e,t){let n=Se.objectProperty(Se.identifier("searchParams"),Se.identifier("searchParams"),!1,!0),r=e.properties.findIndex(Se.isRestElement);if(r<0?e.properties.push(n):e.properties.splice(r,0,n),!t)return;let o=nb(e);if(!o){e.typeAnnotation=Tf().typeAnnotation;return}if(!Se.isTSTypeLiteral(o.typeAnnotation))return;let i=Tf().typeAnnotation;if(!i||!Se.isTSTypeAnnotation(i)||!Se.isTSTypeLiteral(i.typeAnnotation))return;let s=i.typeAnnotation.members[0];s&&!ww(o.typeAnnotation)&&o.typeAnnotation.members.push(Se.cloneNode(s,!0))}function ww(e){return e.members.some(t=>!("key"in t)||!t.key?!1:ob(t.key)==="searchParams")}function Ow(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=to({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!t.ok)return Yc(t.error.message);if(t.plan.requiresRouteParams)return Yc("A captured native detail parameter has no independently proven target route binding.","UNSUPPORTED_ROUTE_PARAMS");let n;if(t.plan.requiresRouteSearchParams){let r=Fw(e.source,e.entryFile);if(!r.ok)return Yc(r.message,"UNSUPPORTED_ROUTE_PARAMS");if(n=r.step,r.step.identifier!==t.plan.searchParamsIdentifier&&(t=to({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder,searchParamsIdentifier:r.step.identifier}),!t.ok))return Yc(t.error.message)}return{ok:!0,invocation:t.plan,...n?{serverParamsStep:n}:{}}}function Yc(e,t="PORTABLE_INVOCATION_INVALID"){return{ok:!1,error:{code:t,message:e,diagnostics:[]}}}function Fw(e,t){let n;try{n=xi.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=rb(n);if(!r)return{ok:!1,message:"Portable route searchParams wiring requires a default server function."};let o=/\.(?:ts|tsx)$/iu.test(t),i=eb(r.node.params,o);return i.ok?{ok:!0,step:{kind:"ensure-search-params",action:i.action,identifier:i.identifier,typescript:o}}:i}function eb(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=wf(e[0]);if(!n)return{ok:!1,message:"Portable route searchParams wiring requires an object page parameter or an empty signature."};let r=tb(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 wf(e){return!e||Se.isTSParameterProperty(e)?null:Se.isObjectPattern(e)?e:Se.isAssignmentPattern(e)&&Se.isObjectPattern(e.left)?e.left:null}function tb(e){for(let t of e.properties)if(!(!Se.isObjectProperty(t)||t.computed||ob(t.key)!=="searchParams"))return Se.isIdentifier(t.value)?t.value.name:Se.isAssignmentPattern(t.value)&&Se.isIdentifier(t.value.left)?t.value.left.name:"unsupported";return null}function Dw(e){let t=nb(e);return t?Se.isTSTypeLiteral(t.typeAnnotation):e.properties.length===0}function nb(e){return e.typeAnnotation&&Se.isTSTypeAnnotation(e.typeAnnotation)?e.typeAnnotation:null}function rb(e){let t=null;return Sw(e,{ExportDefaultDeclaration(n){if(t)return;let r=Ow(n,n.get("declaration"));r&&(t=r)}}),t}function ob(e){return Se.isIdentifier(e)?e.name:Se.isStringLiteral(e)?e.value:null}var Mw=typeof Df=="function"?Df:Df.default;function Hn(e){if(!e.ast)return Wn(e,[$t("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=Xw(e.ast);if(!t)return Wn(e,[$t("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=Hw(t);if(!n.ok)return Wn(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=Gw(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return Wn(e,[$t("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(Zw(r,t))return Wn(e,[$t("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return Bf(e,t,"virtual-route-root",r);if(Yw(r)){let o=tO({input:e,source:e.source,expression:r});return Mf(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return Wn(e,[$t("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!gt(r)&&!Ms(r)){let o=Uf(r),i=cb({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return Mf(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=Qw(r);if(!o.ok)return Wn(e,[o.diagnostic]);let i=bi(o.path);if(i.unsupported)return Wn(e,[$t("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(qw(e.source,r,i.members))return Bf(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||gt(r);if(i.members.length===0&&s)return Bf(e,t,"virtual-route-root",r);let a=o.path===r&&s?"virtual-route-root":"jsx-container",l=o.path.isJSXFragment()?"jsx-fragment":"jsx-element",c=cb({input:e,containerKind:a,sourceKind:l,source:e.source,containerPath:o.path,members:i.members});return Mf(e,t,c,{kind:a,sourceKind:l},r)}return Wn(e,[$t("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function Ff(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:$t("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:$t("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function ib(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:$t("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:$t("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function lb(e){return e.ok?Bw(e.projection):jw(e.projection)}function Bw(e){let t=new Map,n=[];for(let c of e.placements)c.members.length===0&&e.placements.length>1||c.members.length>0&&!c.anchorSourceRange||t.has(c.placementUnitKey)||t.set(c.placementUnitKey,c);let r=new Map,o=new Map;for(let[c,u]of t){let d=u.members.flatMap((p,h)=>ub(e,u,p,h,e.container.placementKey)),f=d.filter(({member:p})=>p.isBusinessMember).map(({sourceMember:p})=>Uw(c,p,u.independent)),m=d.length>0?d:[{sourceMember:{key:`source:${c}: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(c,m.map(({sourceMember:p})=>p)),o.set(c,f);let g=m[0]?.sourceMember.key??c;n.push({key:c,containerKey:g,businessMemberKeys:f.map(p=>p.key),isMultiMember:u.memberCount>1})}let i=[...r.values()].flat(),s=[...o.values()].flat(),a=i[0]?.key??null,l=e.placements.map(c=>({kind:"page-composition",placementKey:c.placementKey,documentVersion:e.documentVersion,composition:e.composition,placementUnitKey:c.placementUnitKey,relation:c.relation}));return{status:"supported",version:e.version,composition:e.composition,container:$w(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:l}}function jw(e){let t=e.diagnostics.map(Vw);return{status:"unsupported",version:e.version,composition:e.composition,reason:Kw(e.diagnostics),diagnostics:t}}function $w(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 ub(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,l)=>ub(e,t,a,l,i))]}function Uw(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function Vw(e){return{code:Jw(e),message:e.message}}function Kw(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 Jw(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 Xw(e){let t=null;return Mw(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=zw(o.path);i&&(t=i,n.stop())}}),t}function zw(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 Hw(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Ds(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:$t("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:$t("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:$t("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(!Ww(s)&&!Hc(s))return{ok:!1,diagnostic:$t("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(db(s)||fb(s))return{ok:!1,diagnostic:$t("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=Ds(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:$t("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function Ww(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(db(o)||fb(o))return null;return r}function db(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function fb(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function Gw(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=Ds(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 Yw(e){return e.isConditionalExpression()?sb(Ds(e.get("consequent")))&&sb(Ds(e.get("alternate"))):!1}function sb(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Ds(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 Zw(e,t){if(e.isIdentifier())return ab(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return ab(n.node.name,t)}return!1}function ab(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 qw(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&$f(t)}function $f(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(!$f(t))return!1;continue}if(t.isJSXElement()&&!$f(t))return!1}return!0}function Qw(e){return{ok:!0,path:e}}function bi(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Vf(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:jn(r.node.loc),businessMemberCount:0,parentSourceRange:jn(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=bi(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=Ms(o)?bi(o):null;n||=i?.unsupported??!1,t.push({...Uf(o,i?.members),sourceRange:jn(r.node.loc),parentSourceRange:jn(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Vf(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:jn(r.node.loc),businessMemberCount:1,parentSourceRange:jn(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&>(r)){let o=bi(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=Ms(r)?bi(r):null;n||=o?.unsupported??!1,t.push({...Uf(r,o?.members),parentSourceRange:jn(e.node.loc)})}}return{members:t,unsupported:n}}function Uf(e,t){let n=e.isJSXElement()&&Ms(e)?t??bi(e).members:[],r=e.isJSXElement()&&!Ms(e)&&!gt(e);return{memberKey:Vf(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:jn(e.node.loc),businessMemberCount:r?1:pb(n),parentSourceRange:jn(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:eO(e)}}function Ms(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function eO(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 pb(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function qc(e){return e.length===0?0:Math.max(1,pb(e))}function cb(e){let t=jn(e.containerPath.node.loc),n=Jf(e.source,e.containerPath.node.start,e.containerPath.node.end),r=$n(e.input,e.containerKind,e.sourceKind,t),o=$n(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:qc(e.members)<=1,memberCount:qc(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function tO(e){let t=jn(e.expression.node.loc),n=Jf(e.source,e.expression.node.start,e.expression.node.end),r=$n(e.input,"virtual-route-root","atomic-expression",t),o=$n(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:$n(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 mb(e,t){let n=jn(t.node.loc),r=Jf(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function Mf(e,t,n,r,o){let i=mb(e,o);if(!i)return Wn(e,[$t("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=nO(e,n,s),l=xf(a),c={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:hb(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(c,{placementByKey:{value:l.placementByKey,enumerable:!1},unitByKey:{value:l.unitByKey,enumerable:!1},placementsByUnitKey:{value:l.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:l.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:c}}function nO(e,t,n){if(t.members.length===0)return[t];let r=[],o=(c,u,d,f,m,g,p=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:qc(g)<=1,memberCount:qc(g),sourceRange:f,sourceHash:f?jf(e.source,f):null,relation:c,containerSourceRange:p,containerSourceHash:p?jf(e.source,p):null,anchorSourceRange:m,anchorSourceHash:m?jf(e.source,m):null,members:g}),i=t.placementKey,s=t.members.map(c=>$n(e,i,"placement-unit",c.sourceRange)),a=s[0]??t.placementUnitKey,l=s.at(-1)??t.placementUnitKey;r.push(o("prepend",$n(e,i,"prepend",n),a,n,null,[]));for(let c of t.members){let u=c.parentSourceRange??n,d=$n(e,i,"placement-unit",c.sourceRange);r.push(o("before",$n(e,d,"before",c.sourceRange),d,c.sourceRange,c.sourceRange,[c],u)),r.push(o("after",$n(e,d,"after",c.sourceRange),d,c.sourceRange,c.sourceRange,[c],u))}return r.push(o("append",i,l,n,null,[])),r}function Bf(e,t,n,r){let o=mb(e,r);if(!o)return Wn(e,[$t("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=$n(e,n,"empty-container",void 0),s=$n(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:[]},l=xf([a]),c={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:hb(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(c,{placementByKey:{value:l.placementByKey,enumerable:!1},unitByKey:{value:l.unitByKey,enumerable:!1},placementsByUnitKey:{value:l.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:l.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:c}}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 $t(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function $n(e,t,n,r){return gb([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Vf(e,t,n){return gb(["member",e,String(t??-1),String(n??-1)])}function gb(e){return`pc_${Kf("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Jf(e,t,n){return t==null||n==null?null:`sha256:${Kf("sha256").update(e.slice(t,n)).digest("hex")}`}function jf(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:${Kf("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function jn(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function hb(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 mO}from"node:crypto";import*as Gn from"@babel/types";function yb(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 Xf from"@babel/traverse";import*as Ei from"@babel/types";var oO=typeof Xf=="function"?Xf:Xf.default,iO=32;function Bo(e,t,n,r=new Set){if(r.has(e.ast)||r.size>=iO)return null;let o=new Set(r).add(e.ast),i;if(oO(e.ast,{Program(d){i=d,d.stop()}}),!i)return null;let s=(d,f)=>{let m=Xr(e.file,d,n),g=m?n.get(m):void 0;return g?Bo(g,f,n,o):null},a=d=>{let f=i.scope.getBinding(d);if(!f||f.constantViolations.length)return null;let m=f.path.parentPath;return m?.isImportDeclaration()?m.node.importKind==="type"?null:f.path.isImportDefaultSpecifier()?s(m.node.source.value,"default"):f.path.isImportSpecifier()&&f.path.node.importKind!=="type"?s(m.node.source.value,Qc(f.path.node.imported)):null:f.path.isVariableDeclarator()?f.path.get("init"):f.path},l=[],c=[];for(let d of i.get("body"))if(d.isExportDefaultDeclaration()&&t==="default"){let f=d.get("declaration");l.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(Ei.getBindingIdentifiers(f.node),t)&&l.push(a(t));for(let m of d.node.specifiers)Ei.isExportSpecifier(m)&&m.exportKind!=="type"&&Qc(m.exported)===t&&l.push(d.node.source?s(d.node.source.value,Qc(m.local)):a(Qc(m.local)))}else d.isExportAllDeclaration()&&d.node.exportKind!=="type"&&t!=="default"&&c.push(d.node.source.value);if(l.length)return l.length===1?l[0]:null;let u=c.map(d=>s(d,t)).filter(d=>d!==null);return u.length===1?u[0]:null}function Qc(e){return Ei.isIdentifier(e)?e.name:e.value}import*as Oe from"@babel/types";var sO=32;function Sn(e,t=new Map,n=new Set){if(n.has(e.node)||n.size>=sO)return null;let r=new Set(n).add(e.node),o=t.get(e.node);if(o)return Bs(o,t,r);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTSSatisfiesExpression()||e.isParenthesizedExpression())return Sn(e.get("expression"),t,r);if(e.isIdentifier()){let i=e.scope.getBinding(e.node.name);return!i||i.constantViolations.length?null:Hf(i,t,r)}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let i=In(e.node.property,e.node.computed),s=e.get("object"),a=Sn(s,t,r);return i!==null&&a?nl(a,i,t,r):null}if(e.isConditionalExpression())return Bs([e.get("consequent"),e.get("alternate")],t,r);if(e.isLogicalExpression())return Bs([e.get("left"),e.get("right")],t,r);if(e.isSequenceExpression()){let i=e.get("expressions").at(-1);return i?Sn(i,t,r):null}if(e.isCallExpression()&&Oe.isIdentifier(e.node.callee)){let i=e.scope.getBinding(e.node.callee.name);if(!i||!Si(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,l=new Map(t),c=e.get("arguments");for(let[m,g]of a.get("params").entries()){if(!g.isIdentifier())return null;let p=c[m];if(!p?.isExpression())return null;let h=Sn(p,t,r);if(!h)return null;let x=g.scope.getBinding(g.node.name);if(!x)return null;l.set(x.identifier,h)}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?Sn(f,l,r):null}return[e]}function Hf(e,t=new Map,n=new Set){if(e.constantViolations.length)return null;let r=t.get(e.identifier);if(r)return Bs(r,t,n);if(!e.path.isVariableDeclarator())return null;let o=e.path.get("init");if(!o.node)return null;let i=Sn(o,t,n);if(!i)return null;let s=zf(e.path.node.id,e.identifier.name);return s?s.reduce((a,l)=>a&&nl(a,l,t,n),i):null}function el(e){if(!e.params.every(n=>Oe.isIdentifier(n)||Oe.isAssignmentPattern(n)&&Oe.isIdentifier(n.left)&&Fr(n.right)))return!1;if(!Oe.isBlockStatement(e.body))return Fr(e.body);if(e.body.body.length!==1)return!1;let t=e.body.body[0];return Oe.isReturnStatement(t)&&!!t.argument&&Fr(t.argument)}function Si(e){if(e.constantViolations.length>0)return!1;if(e.path.isFunctionDeclaration())return el(e.path.node);let t=e.path.isVariableDeclarator()?e.path:e.path.findParent(r=>r.isVariableDeclarator()),n=t?.isVariableDeclarator()?t.node.init:null;return Oe.isArrowFunctionExpression(n)||Oe.isFunctionExpression(n)?el(n):!1}function Fr(e){let t=!0;return Oe.traverseFast(e,n=>{(Oe.isCallExpression(n)&&!tl(n)||Oe.isOptionalCallExpression(n)||Oe.isNewExpression(n)||Oe.isAwaitExpression(n)||Oe.isAssignmentExpression(n)||Oe.isUpdateExpression(n)||Oe.isUnaryExpression(n,{operator:"delete"})||Oe.isYieldExpression(n)||Oe.isTaggedTemplateExpression(n))&&(t=!1)}),t}function tl(e){return Oe.isIdentifier(e.callee,{name:"useTranslations"})&&e.arguments.length===1&&Oe.isStringLiteral(e.arguments[0])}function Bs(e,t,n){let r=[];for(let o of e){let i=Sn(o,t,n);if(!i)return null;r.push(...i)}return r.length?r:null}function nl(e,t,n,r=new Set){let o=[];for(let i of e)if(i.isObjectExpression()){let s=i.get("properties");if(s.some(l=>!l.isObjectProperty()||l.node.computed))return null;let a=s.filter(l=>l.isObjectProperty()&&In(l.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=>Oe.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 Bs(o,n,r)}function Wf(e,t){let n=Sn(e,t);return!!(n?.length&&n.every(r=>Oe.isLiteral(r.node)&&!r.isRegExpLiteral()||r.isTemplateLiteral()||r.isBinaryExpression()||r.isUnaryExpression()))}function In(e,t){return!t&&Oe.isIdentifier(e)?e.name:Oe.isStringLiteral(e)||Oe.isNumericLiteral(e)?String(e.value):null}function zf(e,t){if(Oe.isIdentifier(e))return e.name===t?[]:null;if(Oe.isObjectPattern(e))for(let n of e.properties){if(!Oe.isObjectProperty(n)||n.computed)continue;let r=In(n.key,!1),o=zf(n.value,t);if(r!==null&&o)return[r,...o]}if(Oe.isArrayPattern(e))for(let[n,r]of e.elements.entries()){if(!r)continue;let o=zf(r,t);if(o)return[String(n),...o]}return null}function xb(e,t=new Set,n){return bb(e.get("callee"),t,n)}function bb(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 c=i.node.source.value;if(!(c.startsWith(".")||c.startsWith("@/")))return{kind:"unknown"};let u=r.path.scope.getProgramParent().path.node,d=[...n.values()].find(h=>h.ast.program===u),f=d&&Xr(d.file,c,n),m=f?n.get(f):void 0,g=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()&&r.path.node.importKind!=="type"?In(r.path.node.imported,!1):null,p=m&&g&&i.node.importKind!=="type"?Bo(m,g,n):null;return p?Ii(p,o,n):{kind:"guard"}}let s=r.path.isVariableDeclarator()?r.path.get("init"):r.path;if(!s.node)return{kind:"unknown"};let a=Ii(s,o,n);if(a.kind!=="sources")return a;let l=[...a.sources];for(let c of r.constantViolations){if(!c.isAssignmentExpression({operator:"="}))return{kind:"guard"};let u=Ii(c.get("right"),o,n);if(u.kind!=="sources")return{kind:"guard"};l.push(...u.sources)}return{kind:"sources",sources:l,aliases:a.aliases}}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let r=In(e.node.property,e.node.computed),o=e.get("object"),i=Sn(o);if(!i)return{kind:"unknown"};let s=[],a=new Set(t).add(e.node);for(let l of i){if(!l.isObjectExpression())return{kind:"unknown"};if(r===null||l.node.properties.some(d=>d.type!=="ObjectProperty"))return{kind:"guard"};let c=l.get("properties").filter(d=>d.isObjectProperty()&&In(d.node.key,d.node.computed)===r);if(c.length!==1||!c[0].isObjectProperty())return{kind:"guard"};let u=Ii(c[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 Ii(e,new Set(t).add(e.node),n)}function Ii(e,t,n){if(e.isIdentifier())return bb(e,t,n);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return Ii(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 ol(e,t){return JSON.stringify([t,e])}var cO=new Set;function kb(e,t){let n=new Map,r=[],o=new Map,i=(g,p)=>JSON.stringify([g,p.loc?.start.line,p.loc?.start.column,p.loc?.end.line,p.loc?.end.column]);for(let g of e.graph.elements.values()){let p=g.sourceRange;o.set(JSON.stringify([g.sourceFile,p.startLine,p.startColumn,p.endLine,p.endColumn]),g)}let s=g=>r.push({code:"render-occurrence-unproven",message:"A block render occurrence cannot be proven statically.",file:g}),a=(g,p)=>!vb(p)&&[...t].some(h=>e.graph.elements.get(h)?.sourceFile===g);function l(g,p,h,x,b,E=cO){if(g.isIdentifier())return x&&rl(g,x)?x.children.some(v=>l(v.path,v.file,h,v.substitution,b,E)):u({path:g,file:p,active:h,substitution:x,unknownIsRelevant:b,aliases:E});if(g.isCallExpression()||g.isOptionalCallExpression()){let v=g,A=xb(v,E,e.parsedModules);return A.kind==="guard"||A.kind==="sources"&&A.sources.some(I=>l(I,[...e.parsedModules.values()].find(_=>_.ast.program===I.scope.getProgramParent().path.node)?.file??p,h,x,b,A.aliases))?!0:v.get("arguments").some(I=>l(I,p,h,x,b,E))||A.kind==="unknown"&&b}if(g.isJSXElement()){if(gt(g))return g.get("children").some(L=>l(L,p,h,x,b,E));let v=o.get(i(p,g.node));if(v){if(t.has(v.identity.key))return!0;if(v.boundaryKind==="component-boundary"&&!v.isPublicUiComponent){let L=e.parsedModules.get(v.sourceFile);if(!L)return!1;let $=lr({module:L,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 $.ok?$.metadataOnly?!1:c($,g,v.sourceFile,h,x,E):$.diagnostic.code==="component-external-module-opaque"?js(g).some(J=>l(J,p,h,x,!1,E)):a(L.file,$.diagnostic.code)}return g.get("children").some(L=>l(L,p,h,x,b,E))}let A=g.node.openingElement.name;if(!Gn.isJSXIdentifier(A))return!1;if(/^[a-z]/.test(A.name))return g.get("children").some(L=>l(L,p,h,x,b,E));let I=e.parsedModules.get(p),_=g.node.loc;if(!I||!_)return!1;let k=pO({path:g,file:p,componentName:A.name,parsedModules:e.parsedModules}),T=lr({module:I,componentName:A.name,callSourceRange:{startLine:_.start.line,startColumn:_.start.column,endLine:_.end.line,endColumn:_.end.column},...k?{imported:k}:{}});return T.ok?T.metadataOnly?!1:c(T,g,p,h,x,E):T.diagnostic.code==="component-external-module-opaque"?js(g).some(L=>l(L,p,h,x,!1,E)):a(I.file,T.diagnostic.code)}if(g.isJSXFragment())return g.get("children").some(v=>l(v,p,h,x,b,E));if(g.isJSXExpressionContainer()||g.isParenthesizedExpression()||g.isTSAsExpression()||g.isTSNonNullExpression()||g.isTSTypeAssertion())return l(g.get("expression"),p,h,x,b,E);let S=!1;return g.traverse({"CallExpression|OptionalCallExpression"(v){l(v,p,h,x,b,E)&&(S=!0),v.skip(),S&&v.stop()},ReferencedIdentifier(v){l(v,p,h,x,b,E)&&(S=!0),S&&v.stop()},JSXElement(v){l(v,p,h,x,b,E)&&(S=!0),v.skip(),S&&v.stop()},JSXFragment(v){l(v,p,h,x,b,E)&&(S=!0),v.skip(),S&&v.stop()}}),S?!0:b&&!jo(g)}function c(g,p,h,x,b,E){let S=`${g.sourceFile}#${g.componentName}`;if(x.has(S))return!1;let v=new Set(x).add(S);return g.returnAlternatives?.some(A=>js(A).some(I=>l(I,g.sourceFile,v,null,!1,E)))||g.roots.some(A=>l(A,g.sourceFile,v,null,!1,E))?!0:Eb(g.roots).kind==="none"?!1:Ib(p).some(A=>l(A,h,v,b,!0,E))}function u(g){if(!g.path.isIdentifier())return g.unknownIsRelevant;let p=yb({path:g.path,aliases:g.aliases});return p.kind==="unbound"?g.unknownIsRelevant&&g.path.node.name!=="undefined":p.kind==="guard"||p.kind==="reassigned"?!0:p.kind==="not-alias"?g.unknownIsRelevant:l(p.initializer,g.file,g.active,g.substitution,g.unknownIsRelevant,p.aliases)?!0:Gf(p.initializer).isIdentifier()?!1:g.unknownIsRelevant&&!jo(p.initializer)}let d=(g,p,h,x,b,E)=>{if(g.isIdentifier()){l(g,p,x,E,!1)&&s(p);return}if(g.isJSXElement()){if(gt(g)){for(let A of g.get("children"))d(A,p,h,x,b,E);return}let S=o.get(i(p,g.node));if(!S)return;let v=S.identity.key;if(t.has(v)){b||s(p);let A=n.get(v)??[];A.push(ol(v,h)),n.set(v,A)}if(S.boundaryKind==="component-boundary"&&!S.isPublicUiComponent){let A=e.parsedModules.get(S.sourceFile);if(!A)return;let I=lr({module:A,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(!I.ok){if(I.diagnostic.code==="component-external-module-opaque"){js(g).some(J=>l(J,p,x,E,!1))&&s(p);return}[...t].some(J=>e.graph.elements.get(J)?.sourceFile===A.file)&&!vb(I.diagnostic.code)&&s(A.file);return}if(I.metadataOnly)return;let _=`${I.sourceFile}#${I.componentName}`;if(x.has(_)){s(A.file);return}let k=new Set(x).add(_);I.returnAlternatives?.some(J=>js(J).some(z=>l(z,I.sourceFile,k,E,!1)))&&s(I.sourceFile);let T=Eb(I.roots),L=fO(g);if(T.kind==="unproven"||T.kind==="supported"&&L){for(let J of Ib(g))if(l(J,p,k,E,!0)){s(p);break}}let $=T.kind==="supported"&&!L?{bindingNode:T.bindingNode,children:g.get("children").map(J=>({path:J,file:p,substitution:E}))}:null;for(let J of I.roots)d(J,I.sourceFile,[...h,v],k,b,$);return}for(let A of g.get("children"))d(A,p,h,x,b,E);return}if(g.isJSXFragment()){for(let S of g.get("children"))d(S,p,h,x,b,E);return}if(g.isJSXExpressionContainer()){let S=g.get("expression");if(E&&!S.isJSXEmptyExpression()){let v=Gf(S);if(rl(v,E)){for(let A of E.children)d(A.path,A.file,h,x,b,A.substitution);return}if(lO(S,E))for(let A of E.children)d(A.path,A.file,h,x,!1,A.substitution)}d(S,p,h,x,b,E);return}if(g.isParenthesizedExpression()||g.isTSAsExpression()||g.isTSNonNullExpression()||g.isTSTypeAssertion()){d(g.get("expression"),p,h,x,b,E);return}l(g,p,x,E,!1)&&s(p),g.traverse({JSXElement(S){d(S,p,h,x,!1,E),S.skip()}})},f=e.parsedModules.get(e.entryFile);if(!f)return{occurrences:n,diagnostics:r};let m=En({module:f,exportName:"default",allowNonRenderingGuards:!0});if(!m.ok)return s(e.entryFile),{occurrences:n,diagnostics:r};for(let g of m.roots)d(g,f.file,[],new Set,!0,null);return{occurrences:n,diagnostics:r}}function Gf(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();)t=t.get("expression");return t}function jo(e){let t=Gf(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||jo(n)):t.isConditionalExpression()?jo(t.get("consequent"))&&jo(t.get("alternate")):t.isLogicalExpression()?jo(t.get("left"))&&jo(t.get("right")):!1}function rl(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 lO(e,t){if(rl(e,t))return!0;let n=!1;return e.traverse({Identifier(r){rl(r,t)&&(n=!0,r.stop())}}),n}function Eb(e){let t=e[0]?.getFunctionParent();if(!t)return{kind:"none"};let n=t.get("params")[0];return n?n.isAssignmentPattern()?Sb(n.get("left"),!0):Sb(n,!1):{kind:"none"}}function Sb(e,t){if(e.isObjectPattern()){let n=[],r=!1;for(let i of e.get("properties")){if(i.isObjectProperty()){if(i.node.computed){ur(i.get("value"))&&(r=!0);continue}let s=i.node.key;(Gn.isIdentifier(s)?s.name:Gn.isStringLiteral(s)?s.value:null)==="children"&&n.push(i);continue}i.isRestElement()&&ur(i.get("argument"))&&(r=!0)}if(n.length>1)return r||n.some(i=>ur(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=>uO(s))?t?{kind:"unproven"}:{kind:"supported",bindingNode:o.node}:{kind:"unproven"}}return ur(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=>dO(r))?{kind:"none"}:{kind:"unproven"}}return ur(e)?{kind:"unproven"}:{kind:"none"}}function ur(e){if(e.isIdentifier()){let t=e.scope.getBinding(e.node.name);return!!(t&&t.referencePaths.length>0)}return e.isAssignmentPattern()?ur(e.get("left")):e.isRestElement()?ur(e.get("argument")):e.isObjectPattern()?e.get("properties").some(t=>t.isObjectProperty()?ur(t.get("value")):t.isRestElement()?ur(t.get("argument")):!0):e.isArrayPattern()?e.get("elements").some(t=>t.node?ur(t):!1):!0}function uO(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 dO(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?Gn.isStringLiteral(n)&&n.value!=="children":Gn.isIdentifier(n)&&n.name!=="children"}function fO(e){for(let t of e.get("openingElement").get("attributes")){if(t.isJSXAttribute()){let n=t.node.name;if(Gn.isJSXIdentifier(n)&&n.name==="children")return!0;continue}if(t.isJSXSpreadAttribute()&&_b(t.get("argument")))return!0}return!1}function Ib(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(!Gn.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");_b(r)&&t.push(r)}}return t}function js(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 _b(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 pO(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=Xr(e.file,r.node.source.value,e.parsedModules);if(!o)return;let i=n.isImportDefaultSpecifier()?"default":Gn.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 vb(e){return e==="component-export-unresolved"||e==="component-local-binding-unresolved"}function Pb(e){let t=[],n=[];return Nb(e.element,e,[],e.ownerNode,e.element,[],new Set,t,n),{roots:t,diagnostics:n}}function Nb(e,t,n,r,o,i,s,a,l,c=[]){if(c.length>1&&(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent)){l.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(Sf(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){l.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=lr({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){l.push({...d.diagnostic,structuralPath:e.identity.structuralPath});return}if(d.metadataOnly)return;let f=d.sourceFile,m=`${f}#${d.componentName}`;if(s.has(m)){l.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){l.push({code:"component-root-empty",message:"A component call has no statically addressable JSX root.",file:f,structuralPath:e.identity.structuralPath});return}let g=[...n,{sourceFile:e.sourceFile,component:e.tag,exportName:e.exportName??e.tag,callLocator:{key:e.identity.key,structuralPath:e.identity.structuralPath,sourceRange:e.sourceRange},...c.length>1?{alternativeLocators:c.map(b=>({key:b.identity.key,structuralPath:b.identity.structuralPath,sourceRange:b.sourceRange}))}:{}}],p=d.roots.length>1?{kind:"component-definition",key:m}:r,h=new Set(s);h.add(m);let x=[];for(let b of d.returnAlternatives??[]){let E=Rb(b),S=E?Cb(t.graph,f,E):[];if(S.length!==1){l.push({code:"conditional-component-root-unproven",message:"A conditional call site is absent or ambiguous in the source graph.",file:f});return}x.push(S[0])}for(let b of d.roots){let E=Rb(b),S=E?Cb(t.graph,f,E):[];if(S.length!==1){l.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}Nb(S[0],t,g,p,d.roots.length>1?S[0]:o,d.roots.length>1?g:i,h,a,l,x)}}function Cb(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 Rb(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 il(e){let t=[],n=[];if(e.projection.entryFile!==e.entryFile||!Tb(e.projection.composition,e.composition)||e.graph.composition&&!Tb(e.graph.composition,e.composition))return{roots:[],diagnostics:[$s("composition-mismatch",e.entryFile)]};if(!e.parsedModules.has(e.entryFile))return{roots:[],diagnostics:[$s("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($s("route-member-not-addressable",e.entryFile));continue}let s=hO(e.graph,e.entryFile,i.sourceRange);if(s.length!==1){t.push($s(s.length?"route-root-ambiguous":"route-root-unresolved",e.entryFile));continue}let a=s[0],l=Pb({element:a,graph:e.graph,parsedModules:e.parsedModules,ownerNode:{kind:"route-member",key:a.parentKey??`${e.entryFile}#${e.projection.container.placementKey}`}});t.push(...l.diagnostics);for(let c of l.roots){let u=c.ownerMember;n.push({...c,parentStructuralPath:u.parentKey?e.graph.elements.get(u.parentKey)?.identity.structuralPath??null:null})}}let o=kb(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=ol(s,i.callChain.map(l=>l.callLocator.key));o.occurrences.get(s)?.filter(l=>l===a).length!==1&&t.push($s("render-occurrence-unproven",i.element.sourceFile))}return{roots:gO(n,e.composition,o.occurrences),diagnostics:t}}function gO(e,t,n){let r=e.map(i=>{let s=i.element,a=n.get(s.identity.key)??[],l=i.callChain.map(c=>c.callLocator.key);return{rootKey:mO("sha256").update(JSON.stringify([t,l,s.identity.key])).digest("hex"),rootRef:{key:s.identity.key,...a.length>1?{instanceIndex:a.indexOf(ol(s.identity.key,l)),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(c=>c.callLocator.key),parentStructuralPath:i.parentStructuralPath,siblingRootKeys:[],siblingIndex:0}}),o=new Map;for(let i of r){let s=Ab(i);o.set(s,[...o.get(s)??[],i])}return r.map(i=>{let s=o.get(Ab(i))??[i];return{...i,siblingIndex:s.indexOf(i),siblingRootKeys:s.filter(a=>a!==i).map(a=>a.rootKey)}})}function Ab(e){return JSON.stringify([e.ownerNode.kind,e.ownerNode.key,e.parentStructuralPath,e.ownerCallKeys])}function hO(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 Tb(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function $s(e,t){return{code:e,message:"Page block roots could not be proven from the current source graph.",file:t}}import{SiteEditPageBlockDirectorySchema as yO,SiteEditPageBlockDescriptorSchema as xO,SiteEditSourcePathSchema as Ob}from"@vcp-dev/contracts";function sl(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 l={key:n,writeTarget:i,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,l)}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}),wb(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function wb(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(l=>l.kind===t)&&(a.constraints.push({kind:t,reason:n}),wb(s,t,n,r,o))}}function Us(e){let t=[],n={...e.graph,composition:e.composition},r=bc(sl(n),n),o=[],i=new Map;for(let a of e.roots){let l=e.graph.elements.get(a.rootRef.key),c=e.graph.elements.get(a.ownerMemberKey),u=e.parsedModules.get(a.sourceFile),d=SO(a,e.graph),f=d?e.parsedModules.get(d):void 0;if(!l||!c||c.sourceFile!==d||!u||!Ob.safeParse(a.sourceFile).success||!d||!f||!Ob.safeParse(d).success){t.push(Yf("root-source-unavailable",a.sourceFile));continue}if(i.has(a.rootKey)){t.push(Yf("block-key-ambiguous",a.sourceFile));continue}let m=je(u.source),g=xO.safeParse({blockKey:a.rootKey,rootRef:a.rootRef,definitionKey:a.rootRef.key,source:{file:a.sourceFile,structuralPath:a.structuralPath,contentHash:m},owner:a.ownerNode,siblingBlockKeys:a.siblingRootKeys,placementUnitKey:IO(a,e),capabilities:bO(l,r),...EO(l,r)});if(!g.success){t.push(Yf("page-block-descriptor-invalid",a.sourceFile));continue}let p=g.data;o.push(p),i.set(a.rootKey,{blockKey:a.rootKey,composition:e.composition,documentVersion:e.documentVersion,descriptor:p,root:a,ownerFile:d,ownerSourceHash:je(f.source),ownerSourceContent:f.source,sourceHash:m,sourceContent:u.source,ownerLocator:{kind:"jsx-element",file:c.sourceFile,sourceRange:c.sourceRange,structuralPath:c.identity.structuralPath,componentName:c.componentName},rootLocator:{kind:"jsx-element",file:l.sourceFile,sourceRange:l.sourceRange,structuralPath:l.identity.structuralPath,componentName:l.componentName}})}let s=yO.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 bO(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 EO(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 SO(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 IO(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 Yf(e,t){return{code:e,message:"The page block source binding could not be proven.",file:t}}import Zf from"@babel/traverse";import{BlockRenderRefSchema as vO,SiteEditPageBlockPositionSchema as kO,SiteEditPageBlockTargetSchema as _O}from"@vcp-dev/contracts";var CO=typeof Zf=="function"?Zf:Zf.default;function vi(e,t,n,r){if(!_O.safeParse(t).success)return dn("INVALID_PARAMS","Invalid page block target.");if(n!==e.documentVersion)return dn("VERSION_STALE","The page block index is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return dn("INVALID_TARGET","The target belongs to another composition.");let o=e.bindings.get(t.blockKey);return o?r&&(!vO.safeParse(r).success||r.key!==o.descriptor.rootRef.key||r.instanceIndex!==o.descriptor.rootRef.instanceIndex||r.instanceCount!==o.descriptor.rootRef.instanceCount)?dn("INVALID_TARGET","The render occurrence does not match the target."):{ok:!0,binding:o}:dn("INVALID_TARGET","The page block target was not found.")}function al(e,t){if(!kO.safeParse(t).success)return dn("INVALID_PARAMS","Invalid page block boundary.");if(t.documentVersion!==e.documentVersion)return dn("VERSION_STALE","The page block boundary is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return dn("INVALID_TARGET","The boundary belongs to another composition.");let n=e.bindings.get(t.anchorBlockKey);if(!n)return dn("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 dn("INVALID_TARGET","A verified sibling binding is unavailable.");let o=r.sort((u,d)=>u.root.siblingIndex-d.root.siblingIndex),i=Lb(n);if(!i)return dn("INVALID_TARGET","The operation owner call site is unavailable.");let s=Fb(n,i);if(s===void 0)return dn("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||!RO(Fb(u,Lb(u)),s))return dn("INVALID_TARGET","Siblings do not share one proven source boundary.");let a=o.findIndex(u=>u.blockKey===n.blockKey);if(a<0)return dn("INVALID_TARGET","Anchor order is ambiguous.");let l=t.placement==="before"?o[a-1]:n,c=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:l?.blockKey??null,afterBlockKey:c?.blockKey??null}}}function Lb(e){return e.ownerLocator.file===e.ownerFile?e.ownerLocator:null}function Fb(e,t){if(!t)return;let n=Te(t.file,e.ownerSourceContent);if(!n.ok)return;let r=[];if(CO(n.module.ast,{JSXElement(i){let s=qf(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=qf(o.node);return i?{kind:"jsx-fragment",file:t.file,sourceRange:i}:void 0}if(o.isJSXElement()){let i=qf(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 RO(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 qf(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 dn(e,t){return{ok:!1,code:e,message:t}}import Bb from"node:path";import{SiteEditSourcePathSchema as BO}from"@vcp-dev/contracts";import cl from"node:path";import Qf from"@babel/traverse";import*as ro from"@babel/types";import{SiteEditSourcePathSchema as Db,SiteEditPageBlockTargetSchema as PO}from"@vcp-dev/contracts";var NO=typeof Qf=="function"?Qf:Qf.default;function Mb(e){if(!e.operationId)return Nt("INVALID_PARAMS","An operationId is required.");if(!PO.safeParse(e.target).success)return Nt("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 Nt("INVALID_TARGET","The request target does not match its resolved block binding.");if(e.documentVersion!==e.binding.documentVersion)return Nt("VERSION_STALE","The resolved block belongs to a stale document version.");if(e.operation==="move-node"||e.operation==="remove-node")return Nt("UNSUPPORTED_OPERATION","Move and remove are planned by the structural operation task.");if(!e.node)return Nt("INVALID_PARAMS","An insert/replacement node is required.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!Db.safeParse(t).success)return Nt("INVALID_TARGET","The exact owner source file is unavailable.");let n=e.files.get(t);if(n===void 0)return Nt("INVALID_TARGET","The exact owner source is absent from the fixed file map.");if(je(n)!==e.binding.ownerSourceHash)return Nt("VERSION_STALE","The owner source hash changed after target resolution.");let r=e.files.get(e.binding.descriptor.source.file);if(r===void 0||je(r)!==e.binding.descriptor.source.contentHash)return Nt("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 Nt("INVALID_TARGET","The insertion boundary is not in the resolved source owner.");let c=o.placement==="before"?o.afterBlockKey:o.beforeBlockKey;if(c!==e.binding.blockKey&&!e.binding.descriptor.siblingBlockKeys.includes(c??""))return Nt("INVALID_TARGET","The boundary anchor is not a verified same-owner sibling.");if(!o.parentLocator)return Nt("UNSUPPORTED_OPERATION","A root without a source parent has no safe sibling insertion boundary.")}let i=TO(e.node,t,n,e.files);if(!i.ok)return i;let s=e.operation==="replace-node"?ai({source:n,locator:AO(e.binding),node:{jsx:i.value.jsx}}):Fn({source:n,locator:ep(o.parentLocator),anchorLocator:ep(o.anchorLocator),placement:o.placement,node:{jsx:i.value.jsx}});if(!s.ok)return Nt("UNSUPPORTED_OPERATION",s.diagnostic.message);let a=s.source;if(i.value.import){let c=Dn({source:a,moduleSpecifier:i.value.import.moduleSpecifier,imports:i.value.import.specifiers});if(!c.ok)return Nt("UNSUPPORTED_OPERATION",c.diagnostic.message);a=c.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 AO(e){return ep(e.ownerLocator)}function ep(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 TO(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}>`}}:Nt("INVALID_PARAMS","The native JSX tag is invalid.");if(!e.component)return Nt("UNSUPPORTED_OPERATION","A materialized component entry is resolved by the materialization task.");let o=wO(t,e.component.source,r);if(!o)return Nt("INVALID_TARGET","The component source is not in the safe fixed file map.");let i=Te(t,n);if(!i.ok)return Nt("UNSUPPORTED_OPERATION",i.diagnostic.message);let s=OO(i.module.ast.program.body,e.component.source,e.component.exportName),a=s??FO(DO(e.component.exportName,o),LO(i.module.ast)),l=MO(e.props??{});if(!l.ok)return l;let c=`<${a}${l.value?` ${l.value}`:""} />`;if(s)return{ok:!0,value:{jsx:c}};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:c,import:{moduleSpecifier:e.component.source,specifiers:[u]}}}}function wO(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?cl.posix.normalize(cl.posix.join(cl.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=>Db.safeParse(i).success&&n.has(i))??null:null}function OO(e,t,n){for(let r of e)if(!(!ro.isImportDeclaration(r)||r.source.value!==t)){for(let o of r.specifiers)if(n==="default"&&ro.isImportDefaultSpecifier(o)||n!=="default"&&ro.isImportSpecifier(o)&&(ro.isIdentifier(o.imported)?o.imported.name:o.imported.value)===n)return o.local.name}return null}function LO(e){let t=new Set;return NO(e,{Program(n){n.scope.crawl(),t=new Set(Object.keys(n.scope.bindings)),n.stop()}}),t}function FO(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"?cl.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 MO(e){let t=[];for(let[n,r]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_:.-]*$/.test(n))return Nt("INVALID_PARAMS","A component prop name is invalid.");let o;try{o=JSON.stringify(r)}catch{return Nt("INVALID_PARAMS","Component props must be JSON serializable.")}if(o===void 0)return Nt("INVALID_PARAMS","Component props must be JSON serializable.");t.push(`${n}={${o}}`)}return{ok:!0,value:t.join(" ")}}function Nt(e,t){return{ok:!1,code:e,message:t}}function jb(e){if(e.materialization.kind!=="static-prefab-materialization"||!e.materialization.files.some(i=>i.path===e.materialization.entry.path))return ll("MATERIALIZATION_ENTRY_INVALID","The materialization entry must identify one controlled create-only file.");if(!e.materialization.files.every(i=>i.kind==="create-only"&&BO.safeParse(i.path).success))return ll("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 ll("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 ll("INVALID_TARGET","The exact page-block owner source is missing from the fixed file map.");let n=$O(t,e.materialization.entry.path),r=Mb({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:jO(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 jO(e,t){let n=new Map(e);for(let r of t.files)n.set(r.path,r.content);return n}function $O(e,t){let n=Bb.posix.relative(Bb.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function ll(e,t){return{ok:!1,code:e,message:t}}import{PageTemplateIdSchema as ZO}from"@vcp-dev/contracts";import uH from"node:fs";import fH from"node:path";var UO=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Vs(e){let t=e.map(r=>YO(r.path)),n=VO(t);return n?t.filter(r=>JO(n,r)).map(r=>({routeId:XO(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function tp(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=GO(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function VO(e){return e.some(r=>r.startsWith("app/")&&!KO(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function KO(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function JO(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return UO.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function XO(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(HO).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function zO(e){return e.startsWith("(")&&e.endsWith(")")}function HO(e){return!e||e.startsWith("@")||e.startsWith("_")||zO(e)?null:WO(e)}function WO(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function GO(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function YO(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Ks=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function fn(e,t={}){throw new Ks("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function np(e){return ZO.safeParse(e).success||fn("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function $b(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||fn("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return fn("invalid-template-key",{path:e})}return np(t)!==e&&fn("noncanonical-template-key",{path:e}),t}function qO(e){let t=tp(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("(")||QO(r)&&!Ub(r)))&&fn("invalid-public-route",{routeId:e}),t}function QO(e){return e.includes("[")||e.includes("]")}function Ub(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function Vb(e){return e.some(Ub)}function Kb(e,t,n="app"){n!=="app"&&n!=="src/app"&&fn("invalid-app-root");let r=qO(e),o=np(t),i=Vb(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(l=>Buffer.byteLength(l,"utf8")>255))&&fn("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function Jb(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function Xb(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===".")&&fn("invalid-file-path",{path:i}),n.has(i)&&fn("duplicate-file-path",{path:i}),n.set(i,o)}return n}function dl(e){let t=Xb(e.files),n=Vs([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Ks("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(!Jb(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||fn("candidate-must-be-single-page",{path:i});let a=s[1],l=s[2].split("/"),c=Vb(l),u=c?l[0]:l.pop(),d=c?l.slice(1):l,f=$b(u),m=d.length?`/${d.join("/")}`:"/";Kb(m,f,a).templateEntryFile!==i&&fn("candidate-path-mismatch",{path:i,routeId:m});let p=r.get(m);(!p||!p.startsWith(`${a}/`))&&fn("canonical-entry-missing",{path:i,routeId:m}),o.push({routeId:m,templateId:f,entryFile:i,canonicalEntryFile:p,appRoot:a})}return o.sort((i,s)=>ul(i.routeId,s.routeId)||ul(i.templateId,s.templateId))}function fl(e){let t=Xb(e.files),n=dl({files:t}),r=Vs([...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)=>ul(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:ul(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function eL(e){let t=tp(e.selector.routeId),n=fl({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&fn("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||fn("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function ul(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as IL}from"@vcp-dev/contracts";import{parse as mL}from"@babel/parser";import{parse as PH}from"@babel/parser";import{FormBlockIdSchema as AH,FormSpecV1Schema as TH}from"@vcp-dev/contracts";import{posix as SH}from"node:path";import tL from"@babel/traverse";var rp=tL,vH=typeof rp=="function"?rp:rp.default,kH=Symbol("unknown-member");var Js="components/site/generated/forms",OH=`${Js}/vcp-form-runtime.tsx`,pl="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",LH=new RegExp(`^${Js}/form-(${pl})\\.spec\\.ts$`),FH=new RegExp(`^${Js}/form-(${pl})\\.tsx$`),DH=new RegExp(`^@/${Js}/form-(${pl})$`),MH=new RegExp(`(?:^|/)${Js}/form-(${pl})(?:\\.tsx?)?$`);var BH=Symbol("invalid-literal");import{createHash as UH}from"node:crypto";import{posix as KH}from"node:path";import{parse as XH}from"@babel/parser";import{FormSpecV1Schema as HH}from"@vcp-dev/contracts";var WH=Symbol("dynamic");import{parse as nL}from"@babel/parser";function ml(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var rL=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function zb(e){let t=rL.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 oL(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Hb(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function iL(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function op(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(op);if(t?.type==="ObjectExpression"){let n={};for(let r of ml(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=Hb(r.key);if(!o)throw new Error("unsupported object key");n[o]=op(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function ip(e,t){let n=[],r=zb(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=nL(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(c){return n.push({code:"page-seo.parse-failed",message:c instanceof Error?c.message:String(c)}),{found:!1,seo:null,diagnostics:n}}let i;for(let c of ml(o.program.body)){let u=c.type==="ExportNamedDeclaration"?c.declaration:c;if(u?.type==="VariableDeclaration")for(let d of ml(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=iL(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 c of ml(s.properties)){if(c.type!=="ObjectProperty"||c.computed)continue;let u=Hb(c.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=oL(c.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=op(c.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 l=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`}),l=a.path),{found:!0,seo:{path:l,...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 sL}from"@babel/parser";var Wb=["page","anchor","external","email","phone","group","file"],aL=["link","cta"],Yb=["description","badge","iconKey"],sp=["label","targetType","href","role","openInNewTab","nofollow","children",...Yb],cL=new Set(sp);function zs(e){return Array.isArray(e)?e:[]}function Xs(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function lL(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Gb(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function ap(e){let t=[],n;try{n=sL(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 zs(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of zs(s.declarations)){let l=a.id;l?.type==="Identifier"&&l.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 zs(r.elements).forEach((i,s)=>{let a=Zb(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function Zb(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 c of zs(e.properties)){if(c.type!=="ObjectProperty"||c.computed)continue;let u=lL(c.key);u&&(r[u]=c.value)}let o=Xs(r.label),i=Xs(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!Wb.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${Wb.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 c of Yb){if(r[c]===void 0)continue;let u=Xs(r[c]);u!==void 0?s[c]=u:n.push({severity:"warning",path:`${t}.${c}`,message:`${c} 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 c of Object.keys(r))cL.has(c)||c==="group"||c==="icon"||n.push({severity:"warning",code:"unknown-field",path:`${t}.${c}`,message:`unsupported field \`${c}\` ignored; NAV_ITEMS only carries ${sp.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 c=[];zs(r.children.elements).forEach((u,d)=>{let f=Zb(u,`${t}.children[${d}]`,n);f&&c.push(f)}),s.children=c}if(i==="group")return s.children?s:(n.push({severity:"fatal",path:`${t}.children`,message:"group item requires children"}),null);let a=Xs(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 l=Xs(r.role);if(l!==void 0&&(aL.includes(l)?s.role=l:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let c=Gb(r.openInNewTab);c!==void 0?s.openInNewTab=c:n.push({severity:"warning",path:`${t}.openInNewTab`,message:"openInNewTab ignored: not a static boolean"})}if(r.nofollow!==void 0){let c=Gb(r.nofollow);c!==void 0?s.nofollow=c:n.push({severity:"warning",path:`${t}.nofollow`,message:"nofollow ignored: not a static boolean"})}return s}import{parse as uL}from"@babel/parser";function Hs(e){return Array.isArray(e)?e:[]}function qb(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function dL(e){let t;try{t=uL(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of Hs(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of Hs(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=qb(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 cp(e,t){let n=Qb(t);if(!n)return{status:"unsupported",source:e};let r=dL(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(ap(e).diagnostics.some(({severity:c})=>c==="fatal"))return{status:"unsupported",source:e};let s=[],a=c=>{let u=Hs(c.elements);for(let[d,f]of u.entries()){if(pL(f,n)){let g=u[d+1],p=u[d-1],h=f.start,x=f.end;if(typeof h!="number"||typeof x!="number")continue;if(g&&typeof g.start=="number")s.push({start:h,end:g.start});else if(p&&typeof p.end=="number")s.push({start:p.end,end:x});else{let b=/^\s*,/.exec(e.slice(x));s.push({start:h,end:b?x+b[0].length:x})}continue}let m=fL(f);m&&a(m)}};if(a(o),s.length===0)return{status:"not_found",source:e};let l=e;for(let c of s.sort((u,d)=>d.start-u.start))l=l.slice(0,c.start)+l.slice(c.end);return{status:"removed",source:l,removedCount:s.length}}function fL(e){if(e.type==="ObjectExpression")for(let t of Hs(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return qb(t.value)}}function Qb(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function pL(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Hs(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"&&Qb(n??"")===t}import{estimateNavLabelWidth as oW}from"@vcp-dev/contracts";import{parse as aW}from"@babel/parser";function dr(e,t){let n;try{n=mL(e,{sourceType:"module",sourceFilename:t.filePath,plugins:["jsx","typescript"]})}catch(_){let k=_.loc;return{form_codes:[],components:[],uncertain_components:[],rendered_component_openings:[],renders_native_form:!1,diagnostics:[{code:"rendered-module.parse-failed",message:_ instanceof Error?_.message:"Rendered module failed Babel parsing.",file_path:t.filePath??"",line:k?.line??1}]}}let r=n.program,o=vn(r?.body),i=new Map,s=new Map,a=new Map,l=new Map,c=_=>{if(_?.type==="FunctionDeclaration"){let k=_.id;k?.type==="Identifier"&&typeof k.name=="string"&&s.set(k.name,_);return}if(_?.type==="VariableDeclaration")for(let k of vn(_.declarations)){let T=k.id,L=k.init;T?.type==="Identifier"&&typeof T.name=="string"&&L&&(oo(L)?s.set(T.name,L):L.type==="Identifier"&&typeof L.name=="string"&&a.set(T.name,L.name))}};for(let _ of o){if(_.type==="ImportDeclaration"){let k=_.source?.value;if(typeof k!="string")continue;for(let T of vn(_.specifiers)){let L=T.local;if(!(L?.type!=="Identifier"||typeof L.name!="string")){if(T.type==="ImportDefaultSpecifier")i.set(L.name,{source:k,exportName:"default"});else if(T.type==="ImportNamespaceSpecifier")i.set(L.name,{source:k,exportName:"*"});else if(T.type==="ImportSpecifier"){let $=T.imported,J=$?.type==="Identifier"&&typeof $.name=="string"?$.name:$?.type==="StringLiteral"&&typeof $.value=="string"?$.value:"";J&&i.set(L.name,{source:k,exportName:J})}}}continue}_.type==="ExportNamedDeclaration"?c(_.declaration):c(_)}for(let _ of o){if(_.type==="ExportDefaultDeclaration"){let L=_.declaration;L&&oo(L)?l.set("default",L):L?.type==="Identifier"&&typeof L.name=="string"&&l.set("default",L.name);continue}if(_.type!=="ExportNamedDeclaration")continue;let k=_.declaration;if(k?.type==="FunctionDeclaration"){let L=k.id;L?.type==="Identifier"&&typeof L.name=="string"&&l.set(L.name,L.name)}else if(k?.type==="VariableDeclaration")for(let L of vn(k.declarations)){let $=L.id;$?.type==="Identifier"&&typeof $.name=="string"&&l.set($.name,$.name)}let T=_.source?.value;for(let L of vn(_.specifiers)){let $=nE(L.local),J=nE(L.exported);if(!(!$||!J))if(typeof T=="string"){let z=`#re-export:${J}`;i.set(z,{source:T,exportName:$}),l.set(J,z)}else l.set(J,$)}}let u=new Set,d=[],f=new Set,m=[],g=new Set,p=[],h=new Map,x=!1,b=[],E=new Map,S=new Map,v=(_,k="rendered")=>{let T=tE(_,i);if(!T)return!1;let L=`${T.source}\0${T.exportName}`;if(k==="uncertain")return!f.has(L)&&!g.has(L)&&(g.add(L),m.push({source:T.source,export_name:T.exportName})),!0;if(!f.has(L)&&(f.add(L),d.push({source:T.source,export_name:T.exportName}),g.delete(L))){let $=m.findIndex(J=>J.source===T.source&&J.export_name===T.exportName);$>=0&&m.splice($,1)}return!0},A=(_,k="rendered",T=[])=>{let L=`${k}\0${up(T)}`,$=E.get(_)??new Set,J=S.get(_)??new Set;if($.has(L)||J.has(k))return;$.add(L),E.set(_,$),J.add(k),S.set(_,J);let z=new Map(s),Z=new Map,W=[],Ee=(Ie,ot=!1)=>{if(gl(Ie)){if(!ot&&oo(Ie)){if(Ie.type==="FunctionDeclaration"){let Ve=Ie.id;Ve?.type==="Identifier"&&typeof Ve.name=="string"&&z.set(Ve.name,Ie)}return}if(Ie.type==="VariableDeclarator"){let Ve=Ie.id,F=Ie.init;Ve?.type==="Identifier"&&typeof Ve.name=="string"&&F&&(oo(F)?z.set(Ve.name,F):Z.set(Ve.name,F))}else if(Ie.type==="ReturnStatement"){let Ve=Ie.argument;Ve&&W.push(Ve)}if(Ie.type==="CallExpression"){let Ve=Ie.callee;if(Ve?.type==="Import"&&b.push({code:"rendered-module.dynamic-import",message:"Rendered component graph must use static imports.",file_path:t.filePath??"",line:Ie.loc?.start.line??1}),Ws(Ve)==="cms.forms.getConfig"){let F=vn(Ie.arguments)[0];F?.type==="StringLiteral"&&typeof F.value=="string"&&F.value.trim()?k==="rendered"?u.add(F.value.trim()):b.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:Ie.loc?.start.line??1}):b.push({code:"rendered-module.dynamic-form-code",message:"Rendered cms.forms.getConfig() requires a non-empty string literal.",file_path:t.filePath??"",line:Ie.loc?.start.line??1})}}for(let[Ve,F]of Object.entries(Ie))if(Ve!=="loc")if(Array.isArray(F))for(let q of F)Ee(q);else Ee(F)}};Ee(_,!0);let xe=new Set,Ce=new Set,Me=(Ie,ot=k,Ve=T)=>{if(!(!gl(Ie)||oo(Ie))){if(Ie.type==="Identifier"&&typeof Ie.name=="string"){let F=Z.get(Ie.name),q=`${ot}\0${Ie.name}\0${up(Ve)}`;F&&!xe.has(q)&&!Ce.has(Ie.name)?(xe.add(q),Ce.add(Ie.name),Me(F,ot,Ve),Ce.delete(Ie.name)):v(Ie.name,ot);return}if(Ie.type==="CallExpression"){let F=Ie.callee,q=vn(Ie.arguments),ee=Ws(F),qe=F?.type==="Identifier"&&typeof F.name=="string"?i.get(F.name):void 0;if(ot==="rendered"&&(ee==="createElement"||ee.endsWith(".createElement")||qe?.source==="react"&&qe.exportName==="createElement")&&q[0]?.type==="StringLiteral"&&q[0].value==="form"&&(x=!0),F?.type==="Identifier"&&typeof F.name=="string"){let ht=z.get(F.name);if(ht){A(ht,ot,Ve);return}}if(F&&oo(F)){A(F,ot,Ve);return}if(yL(F)){for(let ht of q)if(oo(ht))A(ht,ot,Ve);else if(ht.type==="Identifier"&&typeof ht.name=="string"){let nn=z.get(ht.name);nn&&A(nn,ot,Ve)}return}for(let ht of q)xL(ht)&&b.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a JSX-producing call argument is rendered.",file_path:t.filePath??"",line:ht.loc?.start.line??1});return}if(Ie.type==="JSXElement"){let F=Ie.openingElement,q=F?eE(Ve,gL(F)):Ve;Me(F,ot,q);for(let ee of vn(Ie.children))Me(ee,ot,q);return}if(Ie.type==="JSXOpeningElement"){let F=hl(Ie.name);ot==="rendered"&&F==="form"&&(x=!0);let q=F?tE(F,i):void 0;if(ot==="rendered"&&q&&typeof Ie.start=="number"){let ee=`${q.source}\0${q.exportName}\0${Ie.start}`,qe=h.get(ee);if(!qe){let ht=bL(Ie).get("formBlockId");qe={source:q.source,export_name:q.exportName,start_offset:Ie.start,...typeof ht=="string"?{static_form_block_id:ht}:{}},h.set(ee,qe),p.push(qe)}Ve.length>0&&(qe.static_render_blockers=eE(qe.static_render_blockers??[],Ve))}if(F&&!v(F,ot)){let ee=z.get(F);ee?A(ee,ot,Ve):Z.has(F)?Me(Z.get(F),ot,Ve):hL(F)||/^[A-Z]/.test(F)&&b.push({code:"rendered-module.dynamic-import",message:`Unable to resolve rendered component ${F} from a static import.`,file_path:t.filePath??"",line:Ie.loc?.start.line??1})}for(let ee of vn(Ie.attributes))Me(ee,"uncertain",Ve);return}if(Ie.type==="JSXAttribute"){let F=Ie.value,q=F?.type==="JSXExpressionContainer"?F.expression:F;q&&oo(q)?A(q,"uncertain",Ve):Me(q,"uncertain",Ve);return}for(let[F,q]of Object.entries(Ie))if(!(F==="loc"||F==="closingElement"))if(Array.isArray(q))for(let ee of q)Me(ee,ot,Ve);else Me(q,ot,Ve)}},bt=_.body;bt&&bt.type!=="BlockStatement"&&W.push(bt);for(let Ie of W)Me(Ie);J.delete(k)},I=l.get(t.exportName);if(typeof I=="string"){let _=I,k=new Set;for(;a.has(_)&&!k.has(_);)k.add(_),_=a.get(_);if(!v(_)){let T=s.get(_);T?A(T):b.push(rE(t))}}else I?A(I):b.push(rE(t));return{form_codes:[...u],components:d,uncertain_components:m,rendered_component_openings:p,renders_native_form:x,diagnostics:b}}function up(e){return e.map(t=>`${t.start_offset}:${t.reason}`).join("|")}function eE(e,t){return[...new Map([...e,...t].map(r=>[up([r]),r])).values()]}function gL(e){let t=new Map;for(let a of vn(e.attributes)){if(a.type==="JSXSpreadAttribute"){t.clear();continue}let l=oE(a.name);if(!l)continue;let c=a.value;t.set(l,c?.type==="JSXExpressionContainer"?c.expression:c)}let n=hl(e.name)??"unknown",r=[],o=a=>{r.push({element_name:n,line:e.loc?.start.line??1,start_offset:SL(e.start),reason:a})};for(let a of["hidden","inert","aria-hidden","disabled"]){if(!t.has(a)||a==="disabled"&&n!=="fieldset")continue;let l=lp(t.get(a));(l===!0||(a==="aria-hidden"?l==="true":typeof l=="string"))&&o(a)}let i=t.get("style");if(i?.type==="ObjectExpression"){let a=new Map;for(let c of vn(i.properties)){let u=c.key,d=!c.computed&&u?.type==="Identifier"?u.name:u?.type==="StringLiteral"?u.value:void 0;c.type!=="ObjectProperty"||typeof d!="string"?a.clear():a.set(d,lp(c.value))}a.get("display")==="none"&&o("style.display=none"),a.get("visibility")==="hidden"&&o("style.visibility=hidden");let l=a.get("opacity");(l===0||typeof l=="string"&&l.trim()==="0")&&o("style.opacity=0")}let s=lp(t.get("className"));if(typeof s=="string"){let a=s.split(/\s+/).filter(Boolean),c={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(c))a.includes(u)&&!a.some(f=>d.has(f.split(":").at(-1)))&&o(`className=${u}`)}return r}function lp(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"&&vn(e.expressions).length===0)return vn(e.quasis)[0]?.value?.cooked}}function tE(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 hL(e){return e.endsWith(".Provider")||e.endsWith(".Consumer")}function oo(e){return e?.type==="FunctionDeclaration"||e?.type==="FunctionExpression"||e?.type==="ArrowFunctionExpression"}function yL(e){let t=Ws(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 xL(e){let t=!1;return dp(e,n=>{if(!t){if(n.type==="JSXOpeningElement"){t=!0;return}n.type==="CallExpression"&&Ws(n.callee)==="cms.forms.getConfig"&&(t=!0)}}),t}function nE(e){return e?.type==="Identifier"&&typeof e.name=="string"?e.name:e?.type==="StringLiteral"&&typeof e.value=="string"?e.value:""}function rE(e){return{code:"rendered-module.unresolved-export",message:`Unable to resolve rendered export ${e.exportName}.`,file_path:e.filePath??"",line:1}}function Ws(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=Ws(e.object),n=e.property;return!t||n?.type!=="Identifier"||typeof n.name!="string"?"":`${t}.${n.name}`}function bL(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=oE(o.name);i&&t.set(i,EL(o.value))}return t}function EL(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 oE(e){let t=e;if(t?.type==="JSXIdentifier")return typeof t.name=="string"?t.name:void 0}function SL(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function dp(e,t){if(gl(e)){t(e);for(let[n,r]of Object.entries(e))if(n!=="loc"){if(Array.isArray(r)){for(let o of r)dp(o,t);continue}dp(r,t)}}}function gl(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function hl(e){let t=e;if(!t)return"";if(t.type==="JSXIdentifier")return typeof t.name=="string"?t.name:"";if(t.type==="JSXMemberExpression"){let n=hl(t.object),r=hl(t.property);return n&&r?`${n}.${r}`:r||n}return""}function vn(e){return Array.isArray(e)?e.filter(t=>gl(t)):[]}var vL="components/site/generated/",Gs=[".tsx",".ts",".jsx",".js"];function iE(e){if(e.expectedUrlPath===IL)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Vs(Object.keys(e.files).map(p=>({path:p}))).map(p=>p.entryFile)),n=Object.entries(e.files).filter(([p,h])=>{let x=p.replace(/\\/g,"/");if(!t.has(x))return!1;let b=ip(h,x);return b.found&&b.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=dl({files:new Map(Object.entries(e.files))});for(let h of p)h.canonicalEntryFile===r&&o.add(h.entryFile)}catch(p){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:p instanceof Error?p.message:"Invalid page template source."}}let i=kL(e.files);if(!i.ok)return i.error;let s=i.graph,a=PL(o,s),l=NL(o,a,s),c=[...a].filter(p=>!l.has(p)).sort((p,h)=>p.localeCompare(h)),u=[...o,...[...l].sort((p,h)=>p.localeCompare(h))],d=new Set(u),f=u.map(p=>({operation:"delete",file:p})),m=[],g=[];for(let[p,h]of Object.entries(e.files))if(!d.has(p)){if(h.includes("NAV_ITEMS")){let x=cp(h,e.expectedUrlPath);x.status==="removed"?(f.push({operation:"upsert",file:p,content:x.source}),m.push(p)):x.status==="unsupported"&&g.push(`unsupported_navigation:${p}`)}h.includes(e.expectedUrlPath)&&!h.includes("NAV_ITEMS")&&g.push(`preserved_link:${p}`)}return{ok:!0,edits:f,deletedFiles:u,updatedFiles:m,preservedSharedFiles:c,warnings:g}}function kL(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")||!_L(r))continue;let s=Te(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:l}of s.module.imports){if(CL(l))continue;let c=rr(r,l),u=RL(c,t);if(!u)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${l} (import-not-found).`}};a.add(u)}n.set(r,a)}return{ok:!0,graph:n}}function _L(e){let t=e.toLowerCase();return Gs.some(n=>t.endsWith(n))}function CL(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!Gs.some(n=>e.endsWith(n)))}function RL(e,t){let n=e.replace(/\\/g,"/");return(Gs.some(o=>n.endsWith(o))?[n]:[...Gs.map(o=>`${n}${o}`),...Gs.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function PL(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(vL)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function NL(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,l])=>!e.has(a)&&!r.has(a)&&l.has(i))&&(r.delete(i),o=!0)}return r}import*as sS from"@babel/parser";import*as Ge from"@babel/types";import*as Ll from"node:path";import*as st from"@babel/types";function sE(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 fr(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return $o(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(st.isObjectPattern(n)||st.isArrayPattern(n))return $o(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(TL(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function $o(e,t,n=!1){return st.isIdentifier(e)?e.name===t&&n:st.isObjectPattern(e)?e.properties.some(r=>st.isObjectProperty(r)?$o(r.value,t,n):$o(r.argument,t,n)):st.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=st.isRestElement(r)?r.argument:r;return $o(o,t,n)}):st.isAssignmentPattern(e)?$o(e.left,t,!0):st.isRestElement(e)?$o(e.argument,t,n):!1}function ki(e,t){if(e.path.isObjectPattern()){if(t){let r=Yn(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:fr(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:fr(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=aE(r),i=!1,s=o?o.initBinding&&fp(o.initBinding)?(i=fr(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let l=ki(o.initBinding,{kind:"identifier",expression:o.initBinding.identifier.name,base:o.initBinding.identifier.name,path:[]});return i=l?.hasDefault??!1,l?[{kind:"property",name:l.propName},...l.remainingPath,...o.initPathPrefix]:null})():null:null,a=Yn(e.path.node.id,e.identifier.name);if(s&&a){let l=[...s,...a],[c,...u]=l;return!c||c.kind!=="property"?null:{propName:c.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||fr(e)}}}}let n=LL(e);if(n){let r=AL(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||fr(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=wL(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:fr(e)}}let i=Ys(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:fr(e)}:null}if(fp(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:fr(e)}}return null}function AL(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=aE(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,l=fp(i)?(a=fr(i),[...s]):(()=>{let u=ki(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(!l)return null;let c=Yn(n.node.id,t.identifier.name);return c?{path:[...l,...c],hasDefault:a||fr(t)}:null}function aE(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=FL(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function fp(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function TL(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function wL(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=Yn(i.node,t);if(a)return a}return null}function cE(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let l=yl(a,e.identifier.name);if(l&&(!n||l.propName===n))return{propName:l.propName,componentName:t,expressionPath:l.expressionPath,displayPath:`${t}.${l.propName}.default`}}}if(e.path.isObjectPattern())for(let a of e.path.get("properties")){if(!a.isObjectProperty())continue;let l=Ys(a.node);if(!l||n&&l!==n)continue;let c=a.get("value");if(!c.isAssignmentPattern())continue;let u=c.get("right");if(u.isExpression())return{propName:l,componentName:t,expressionPath:u,displayPath:`${t}.${l}.default`}}let r=OL(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=Ys(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 yl(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=Ys(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&Yn(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=yl(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=yl(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=yl(r,t);if(o)return o}}return null}function Yn(e,t,n=[]){if(st.isIdentifier(e))return e.name===t?n:null;if(st.isObjectPattern(e)){for(let r of e.properties)if(st.isObjectProperty(r)){let o=Ys(r);if(!o)continue;let i=Yn(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(st.isRestElement(r)){let o=Yn(r.argument,t,n);if(o)return o}}if(st.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=st.isRestElement(o)?o.argument:o,s=Yn(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return st.isAssignmentPattern(e)?Yn(e.left,t,n):null}function OL(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function LL(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 Ys(e){return e.computed?null:st.isIdentifier(e.key)?e.key.name:st.isStringLiteral(e.key)?e.key.value:null}function FL(e){let t=[],n=e;for(;st.isMemberExpression(n);){if(n.computed)if(st.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(st.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(st.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return st.isIdentifier(n)?{base:n.name,path:t}:null}import*as mE from"@babel/parser";import gp from"@babel/traverse";import*as _i from"@babel/types";import*as Ue from"@babel/types";var lE=new WeakMap;function El(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?xl(n,t):null}if(e.isMemberExpression()){let n=UL(e.node),r=DL(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?xl(o,[...r,...t]):null}return e.isAwaitExpression()||mp(e.node)?io(KL(e.node),t,"awaited or fetched expression"):null}function DL(e){let t=[],n=e;for(;Ue.isMemberExpression(n);){if(n.computed)if(Ue.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ue.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ue.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ue.isIdentifier(n)?t:null}function xl(e,t=[],n){let r=ML(e,t);if(r)return r;let o=BL(e,t,n);if(o)return o;let i=jL(e,t,n);return i||null}function qs(e){return e?.kind==="api-source"}function ML(e,t){if(e.path.isVariableDeclarator()&&Ue.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&pp(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return io(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&Ue.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(l=>Ue.isObjectProperty(l)&&fE(l)==="data"&&Zs(l.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&pp(a.node))return io(e.identifier.name,t,"query hook data binding")}let n=$L(e);if(!n||fE(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()||!pp(i.node)?null:io(e.identifier.name,t,"query hook data binding")}function BL(e,t,n){if(e.path.isVariableDeclarator()&&Ue.isArrayPattern(e.path.node.id)){let l=e.path.get("init");if(!l?.isCallExpression()||!dE(l.node))return null;let[c,u]=e.path.node.id.elements;return!Ue.isIdentifier(c)||c.name!==e.identifier.name||!Ue.isIdentifier(u)?null:uE(e,u.name,n)?io(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()||!dE(i.node)||r.node.elements.findIndex(l=>l===e.path.node)!==0)return null;let a=r.node.elements[1];return Ue.isIdentifier(a)&&uE(e,a.name,n)?io(e.identifier.name,t,"state setter is updated by API data"):null}function jL(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()?io(e.identifier.name,t,"awaited binding result"):mp(o.node,n)?io(e.identifier.name,t,"fetch-backed binding result"):null:null}function $L(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 Zs(e,t){return Ue.isIdentifier(e)?e.name===t:Ue.isAssignmentPattern(e)?Zs(e.left,t):Ue.isObjectPattern(e)?e.properties.some(n=>Ue.isObjectProperty(n)?Zs(n.value,t):Zs(n.argument,t)):Ue.isArrayPattern(e)?e.elements.some(n=>!!n&&Zs(Ue.isRestElement(n)?n.argument:n,t)):!1}function uE(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let l=lE.get(n);l||(l=new WeakMap,lE.set(n,l)),s=l.get(i.node),s||(s=new Map,l.set(i.node,s));let c=s.get(t);if(c!==void 0)return c}i.traverse({CallExpression(l){mp(l.node)&&(r=!0),(VL(l.node.callee,t)||l.node.arguments.some(c=>Ue.isIdentifier(c)&&c.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function pp(e){let t=Sl(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function dE(e){return Sl(e.callee)==="useState"}function mp(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=bl(e,o=>Ue.isCallExpression(o)&&Sl(o.callee)==="fetch");return t?.set(e,r),r}function UL(e){let t=e;for(;Ue.isMemberExpression(t);)t=t.object;return Ue.isIdentifier(t)?t.name:null}function fE(e){return e.computed?null:Ue.isIdentifier(e.key)?e.key.name:Ue.isStringLiteral(e.key)?e.key.value:null}function Sl(e){return Ue.isIdentifier(e)?e.name:Ue.isMemberExpression(e)&&Ue.isIdentifier(e.property)?e.property.name:null}function VL(e,t){return bl(e,n=>Ue.isIdentifier(n)&&n.name===t)}function bl(e,t){if(t(e))return!0;let n=Ue.VISITOR_KEYS[e.type];if(!n)return!1;for(let r of n){let o=e[r];if(Array.isArray(o)){for(let i of o)if(Ue.isNode(i)&&bl(i,t))return!0;continue}if(Ue.isNode(o)&&bl(o,t))return!0}return!1}function KL(e){return Ue.isIdentifier(e)?e.name:Ue.isCallExpression(e)?Sl(e.callee)??"api":Ue.isAwaitExpression(e)?"awaited-api":"api"}function io(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:JL(e,t),reason:n}}function JL(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var gE=typeof gp=="function"?gp:gp.default;function hE(e,t){let n=xE(e);if(!n)return{allowed:!0};let r=!1;return gE(n,{CallExpression(o){if(!bE(o.node,t.sourceRange)||!XL(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||qs(El(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function yE(e,t){let n=xE(e);if(!n)return{allowed:!0};let r=!1;return gE(n,{JSXExpressionContainer(o){bE(o.node,t.sourceRange)&&(_i.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 xE(e){try{return mE.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function XL(e){let t=e.callee;return _i.isMemberExpression(t)&&_i.isIdentifier(t.property)&&t.property.name==="map"}function bE(e,t){let n=e.loc;return n?pE({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&pE({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function pE(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 de from"@babel/types";import*as EE from"@babel/parser";import hp from"@babel/traverse";import*as Et from"@babel/types";import*as Ci from"node:path";var Zn=typeof hp=="function"?hp:hp.default;function Jt(e){try{return EE.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function yp(e){return e.computed?Et.isStringLiteral(e.key)||Et.isNumericLiteral(e.key)?String(e.key.value):null:zL(e.key)}function zL(e){return Et.isIdentifier(e)?e.name:Et.isStringLiteral(e)||Et.isNumericLiteral(e)?String(e.value):null}function Uo(e){return Et.isParenthesizedExpression(e)||Et.isTSAsExpression(e)||Et.isTSSatisfiesExpression(e)||Et.isTSNonNullExpression(e)||Et.isTSTypeAssertion(e)?Uo(e.expression):Et.isExpression(e)?e:null}function xp(e){if(Et.isIdentifier(e))return[e.name];if((Et.isMemberExpression(e)||Et.isOptionalMemberExpression(e))&&!e.computed&&Et.isIdentifier(e.property)){let t=Uo(e.object),n=t?xp(t):null;return n?[...n,e.property.name]:null}return null}function Vo(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?Ci.normalize(Ci.join(Ci.dirname(e),t)).replace(/\\/g,"/"):t}function kn(e,t){return Il(e)===Il(t)}function Il(e){let t=Ri(e);return t.endsWith("/index")?t.slice(0,-6):t}function Ri(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function vE(e,t,n){let r=RE(e,t);if(PE(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 Zn(e,{JSXElement(s){OE(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:vl(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 kE(e,t){let n=new Map,r=i=>{let s=Pi(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 HL(i,n))o=r(s)||o}return[...n.values()]}function HL(e,t){let n=[],r=WL(e,t);for(let o of e.ast.program.body){if(de.isExportDefaultDeclaration(o)&&de.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=Qs(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(de.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Vo(e.file,o.source.value);for(let s of o.specifiers){if(de.isExportNamespaceSpecifier(s)){let c=so(s.exported);for(let u of t.values())kn(u.file,i)&&n.push({file:e.file,namespace:bp(c,u.namespace),exportName:u.exportName});continue}if(!de.isExportSpecifier(s))continue;let a=so(s.local),l=[...t.values()].filter(c=>kn(c.file,i)&&Ko(c.namespace,a));if(l.length>0){let c=so(s.exported);for(let u of l){let d=Qs(u.namespace,a,c);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Pi({file:i,exportName:a}))&&n.push({file:e.file,exportName:so(s.exported)})}continue}if(de.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!de.isExportSpecifier(i))continue;let s=so(i.local),a=r.get(s)??[];if(a.length>0){let l=so(i.exported);n.push({file:e.file,exportName:l});for(let c of a){let u=Qs(c.namespace,s,l);u&&n.push({file:e.file,namespace:u,exportName:c.exportName})}}}continue}if(de.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Vo(e.file,o.source.value),s=o.exported;if(s){let a=so(s);for(let l of t.values())kn(l.file,i)&&n.push({file:e.file,namespace:bp(a,l.namespace),exportName:l.exportName});continue}for(let a of t.values())kn(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function bp(e,t){return t?`${e}.${t}`:e}function Ko(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Qs(e,t,n){return!Ko(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function WL(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(!de.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Vo(e.file,i.source.value);for(let a of i.specifiers){if(de.isImportDefaultSpecifier(a)){let l=t.get(Pi({file:s,exportName:"default"}));l&&r(a.local.name,l);let c=[...t.values()].filter(u=>kn(u.file,s)&&Ko(u.namespace,"default"));for(let u of c){let d=Qs(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(de.isImportSpecifier(a)){let l=so(a.imported),c=[...t.values()].filter(d=>kn(d.file,s)&&Ko(d.namespace,l));for(let d of c)r(a.local.name,d);let u=t.get(Pi({file:s,exportName:l}));u&&r(a.local.name,u);continue}if(de.isImportNamespaceSpecifier(a))for(let l of t.values())kn(l.file,s)&&r(a.local.name,{...l,namespace:bp(a.local.name,l.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(de.isVariableDeclaration(i))for(let s of i.declarations){if(!de.isIdentifier(s.id)||!s.init)continue;let a=Uo(s.init);if(!a||!de.isIdentifier(a))continue;let l=n.get(a.name)??[];if(l.length===0)continue;let c=n.get(s.id.name)??[],u=new Set(c.map(Pi));for(let d of l){let f=Qs(d.namespace,a.name,s.id.name),m=f?{...d,namespace:f}:d,g=Pi(m);u.has(g)||(r(s.id.name,m),u.add(g),o=!0)}}}return n}function Pi(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Il(e.file)}#${t}`}function so(e){return de.isIdentifier(e)?e.name:e.value}function _E(e,t){for(let n of e.program.body){if(de.isExportDefaultDeclaration(n)){let o=n.declaration;if((de.isFunctionDeclaration(o)||de.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(de.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!de.isExportNamedDeclaration(n))continue;let r=n.declaration;if((de.isFunctionDeclaration(r)||de.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(de.isVariableDeclaration(r)){for(let o of r.declarations)if(de.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!de.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:de.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Sp(e){let t=GL(e),n=[],r=NE(e.ast,t);return Zn(e.ast,{JSXElement(o){kn(e.file,e.sourceFile)&&vl(o)===e.sourceComponent||OE(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function CE(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function RE(e,t){let n=CE();return Zn(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function GL(e){let t=CE();return kn(e.file,e.sourceFile)&&YL(t,RE(e.ast,e.sourceComponent)),Zn(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Vo(e.file,o),s=e.componentIdentities.filter(a=>kn(a.file,i));if(s.length!==0)for(let a of r.specifiers){let l=n.scope.getBinding(a.local.name);if(l){if(de.isImportDefaultSpecifier(a)&&s.some(c=>c.exportName==="default")&&t.localBindings.add(l),de.isImportDefaultSpecifier(a)){let c=s.filter(u=>Ko(u.namespace,"default"));if(c.length>0){let u=t.namespaceMembers.get(l)??new Set;for(let d of c){let f=IE(d,"default");f&&u.add(f)}t.namespaceMembers.set(l,u)}continue}if(de.isImportSpecifier(a)){let c=de.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>Ko(d.namespace,c));if(u.length>0){let d=t.namespaceMembers.get(l)??new Set;for(let f of u){let m=IE(f,c);m&&d.add(m)}t.namespaceMembers.set(l,d);continue}s.some(d=>!d.namespace&&d.exportName===c)&&t.localBindings.add(l);continue}if(de.isImportNamespaceSpecifier(a))for(let c of s){let u=c.namespace?`${c.namespace}.${c.exportName}`:c.exportName,d=t.namespaceMembers.get(l)??new Set;d.add(u),t.namespaceMembers.set(l,d)}}}}}),PE(e.ast,t),t}function YL(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 PE(e,t){Zn(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Uo(n.node.init);if(r){if(de.isIdentifier(n.node.id)){let o=Jo(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Ep(t,i,o);return}if(de.isObjectPattern(n.node.id)){let o=Jo(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&wE(n.node.id,o.namespaceMembers,t,n)}}}})}function NE(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Zn(e,{ReferencedIdentifier(r){if(n){r.stop();return}ZL(r)||!r.isIdentifier()||!AE(r,t)||qL(r,t)||QL(r)||(n=!0,r.stop())}}),n}function ZL(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 AE(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)&&Jo(r.node,t,r)?r:null}function qL(e,t){let n=e.findParent(l=>l.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!SE(e,r))return!1;let o=AE(e,t);if(!o)return!1;if(Uo(r.node)===o.node)return!!Jo(r.node,t,r);let s=e.findParent(l=>l.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&SE(e,a)&&!!Jo(a.node,t,a)}function QL(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function SE(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Jo(e,t,n){let r=Uo(e);if(!r)return null;if(de.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let l=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:l?{local:!1,namespaceMembers:new Set(l),unsupported:!1}:null}if(de.isObjectExpression(r))return eF(r,t,n);let o=xp(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?TE(s,o.slice(1).join(".")):null}function eF(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!de.isObjectProperty(i))continue;let s=yp(i);if(!s||!de.isExpression(i.value)){de.isExpression(i.value)&&(o||=Jo(i.value,t,n)!==null);continue}let a=Jo(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let l of a.namespaceMembers)r.add(`${s}.${l}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function TE(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 Ep(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 wE(e,t,n,r){for(let o of e.properties){if(de.isRestElement(o)){if(de.isIdentifier(o.argument)){let l=r.scope.getBinding(o.argument.name);l&&Ep(n,l,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!de.isObjectProperty(o))continue;let i=yp(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=TE(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=de.isAssignmentPattern(o.value)?o.value.left:o.value;if(de.isIdentifier(a)){let l=r.scope.getBinding(a.name);l&&Ep(n,l,s);continue}if(de.isObjectPattern(a)&&s.namespaceMembers.size>0){wE(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function IE(e,t){if(!Ko(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 OE(e,t){let n=e.node.openingElement.name;if(de.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=LE(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 LE(e){if(de.isJSXIdentifier(e))return[e.name];if(de.isJSXMemberExpression(e)){let t=LE(e.object);return t?[...t,e.property.name]:null}return null}function vl(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()&&de.isIdentifier(n.node.id))return n.node.id.name}return null}function FE(e,t){let n=Jt(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Sp({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 pr(e,t){let n=tt(e);return!!(n&&_n(t,n))}function _n(e,t){return t.start>=e.start&&t.end<=e.end}function Un(e,t){let n=De(e,rt(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:kl(e,t)}function Ni(e,t){let n=tt(t);return n?e.slice(n.start,n.end):""}function DE(e,t){return e.start===t.start&&e.end===t.end}function kl(e,t){let n=null;return Zn(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 _l(e,t){return Ip(e,t).length>0}function Cl(e,t){let n=tt(e.node),r=tt(t.node);if(!n||!r)return!1;let o=e.parentPath;for(;o;){if((o.isIfStatement()||o.isSwitchCase())&&(!!!t.findParent(s=>s.node===o?.node)||o.isIfStatement()&&!tF(o,n,r)))return!0;o=o.parentPath}return!1}function tF(e,t,n){let r=tt(e.node.consequent);if(r&&_n(r,t)&&!_n(r,n))return!1;let o=e.node.alternate?tt(e.node.alternate):null;return!(o&&_n(o,t)&&!_n(o,n))}function Ip(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()&&vp(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 vp(e){return e==="&&"||e==="||"||e==="??"}function ME(e,t){let n=tt(e.consequent);if(n&&_n(n,t))return n;let r=tt(e.alternate);return r&&_n(r,t)?r:null}function BE(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=>Ri(a.file)));if(!t.has(Ri(e.sourceFile))||!t.has(Ri(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(Ri(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=_E(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 l=Jt(a.content);if(!l)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:l})}let o=kE(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let l=Sp({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(l.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(...l.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!kn(s.file,e.targetFile)||vl(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 aF}from"@vcp-dev/contracts";function Rl(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 ea();let a=s.target,l=a.locator;if(a.sourceKind==="repeat-template"){let c=o?.instanceIndex;if(c===void 0)return ea();let u=nF(a,c,o?.instanceCount);if(!u)return ea();l=u}return{ok:!0,target:{kind:"value-binding",file:a.file,locator:l}}}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"?ea():{ok:!0,target:{kind:"jsx-attribute"}}}function ea(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function nF(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(l=>l.kind==="index");if(s<0)return null;let a=i.map((l,c)=>c===s&&l.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:l);return{...e.locator,path:a}}import*as mr from"@babel/types";import{SiteEditSetPropsParamsSchema as rF}from"@vcp-dev/contracts";function jE(e){let t=e.changes??(e.change?[e.change]:[]);if(!rF.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return ta("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return ta("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=ft(e.source,"value");if(!o.ok)return ta("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 l=De(o.ast,a);if(!l.ok||!l.match.path.isObjectExpression())return ta("unsupported-object",`Repeat item ${s} is not a writable object expression`);let c=s===e.target.sourceItemIndex?oF(r):iF(l.match.path.node,r.name);if(!c)return ta("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:c})}return{ok:!0,steps:i}}function oF(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function iF(e,t){let n=e.properties.filter(i=>mr.isObjectProperty(i)&&sF(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!mr.isExpression(r.value))return null;let o=cr(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function sF(e){return mr.isIdentifier(e)?e.name:mr.isStringLiteral(e)?e.value:mr.isNumericLiteral(e)?String(e.value):null}function ta(e,t){return{ok:!1,errorCode:e,reason:t}}function $E(e){if(e.change.name!=="className"&&e.change.name!=="class")return na("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return na("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return na("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return na("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 na("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 na(e,t){return{ok:!1,errorCode:e,reason:t}}async function VE(e){let t=aF.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return ao("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 ao("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 cF(e,r);if(o){if(!o.ok)return ao("owner-plan-failed",o.reason);UE(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return ao("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return ao("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(dF(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=Rl({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return ao(a.code,a.reason);let l=a.target;if(l.kind==="value-binding"&&r.operation==="set"){kp(n,{type:"update-value",order:n.length,file:l.file,locator:l.locator,value:r.value});continue}if(l.kind==="repeat-property"){let c=jE({source:e.getFileContent(l.target.sourceFile),target:l.target,changes:[r]});if(!c.ok)return ao("repeat-target-failed",c.reason);UE(n,c.steps);continue}kp(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:lF(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),uF(n)?ao("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function cF(e,t){return t.name!=="className"&&t.name!=="class"?null:$E({node:e.node,change:t,classNameSource:e.classNameSource})}function lF(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 uF(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 UE(e,t){for(let n of t)kp(e,{...n,order:e.length})}function kp(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 dF(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?_p(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function _p(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)=>_p(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=>_p(n[i],r[i]))}return!1}function ao(e,t){return{ok:!1,errorCode:e,reason:t}}import*as Ti from"@babel/types";import*as he from"@babel/types";function Cp(e,t,n){let r=Un(t,n);return r?gr(e,r):null}function gr(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 l=a.node,c=l.property;if(!he.isIdentifier(c)||c.name!=="map"||l.computed)return null;let u=a.get("object"),d=Ni(e,u.node),f=r.node.params.map(p=>Ni(e,p)),m=tt(i.node),g=tt(r.node);return!d||f.some(p=>p.length===0)||!m||!g?null:{callStart:m.start,callEnd:m.end,callbackStart:g.start,callbackEnd:g.end,collectionExpression:d,callbackParams:f,mapOperator:he.isOptionalMemberExpression(l)&&l.optional?"?.map":".map",collectionNeedsParens:Pl(u.node),callbackPath:r,collectionPath:u}}function ra(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function fF(e,t){let n=tt(e.node);return n?pF(t).some(r=>{let o=tt(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function pF(e){let t=e.callbackPath.node.body;return he.isBlockStatement(t)?co(t.body):lo(t)}function co(e){let t=[];for(let n of e){if(he.isReturnStatement(n)){n.argument&&t.push(...lo(n.argument));continue}if(he.isBlockStatement(n)){t.push(...co(n.body));continue}if(he.isIfStatement(n)){let r=he.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...co(r)),n.alternate){let o=he.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...co(o))}continue}if(he.isSwitchStatement(n)){for(let r of n.cases)t.push(...co(r.consequent));continue}he.isTryStatement(n)&&(t.push(...co(n.block.body)),n.handler&&t.push(...co(n.handler.body.body)),n.finalizer&&t.push(...co(n.finalizer.body)))}return t}function lo(e){return he.isJSXElement(e)?mF(e)?KE(e.children):[e]:he.isJSXFragment(e)?KE(e.children):he.isParenthesizedExpression(e)||he.isTSAsExpression(e)||he.isTSSatisfiesExpression(e)||he.isTSNonNullExpression(e)||he.isTSTypeAssertion(e)?lo(e.expression):he.isConditionalExpression(e)?[...lo(e.consequent),...lo(e.alternate)]:he.isLogicalExpression(e)&&vp(e.operator)?lo(e.right):[]}function KE(e){return e.flatMap(t=>he.isJSXElement(t)||he.isJSXFragment(t)?lo(t):he.isJSXExpressionContainer(t)&&(he.isJSXElement(t.expression)||he.isJSXFragment(t.expression)||he.isConditionalExpression(t.expression)||he.isLogicalExpression(t.expression))?lo(t.expression):[])}function mF(e){let t=e.openingElement.name;return he.isJSXIdentifier(t)?t.name==="Fragment":he.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function JE(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Pl(e){return!(he.isIdentifier(e)||he.isThisExpression(e)||he.isMemberExpression(e)||he.isOptionalMemberExpression(e)||he.isCallExpression(e)||he.isOptionalCallExpression(e))}function XE(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(he.isMemberExpression(n)||he.isOptionalMemberExpression(n))&&he.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function Ai(e,t){let n=Jt(e);if(!n)return t.isRepeatItemRoot===!0;let r=De(n,rt(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:kl(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=gr(e,o);return i?fF(o,i):t.isRepeatItemRoot===!0}function zE(e,t){let n=Jt(e);if(!n)return!1;let r=De(n,rt(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:kl(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(he.isMemberExpression(s)||he.isOptionalMemberExpression(s))&&he.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as lt from"@babel/types";function Rp(e){if(lt.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(lt.isJSXMemberExpression(e)){let t=e;for(;lt.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function gF(e,t){let n=tt(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||pr(a.path.node,n)||uo(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Rp(i.node.name);s&&o(s,i)}}),[...r].sort()}function Pp(e,t,n){let r=Jt(e);if(!r)return{ok:!0};let o=De(r,rt(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=De(r,rt(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=hs(o.match.path,i.match.path);if(_l(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=gF(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function WE(e){let t=e;for(;lt.isTSQualifiedName(t);)t=t.left;return lt.isIdentifier(t)?t.name:null}function oa(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Nl(e){let t=[],n=r=>{if(r){if(lt.isIdentifier(r)){t.push(r.name);return}if(lt.isObjectPattern(r)){for(let o of r.properties){if(lt.isRestElement(o)){n(o.argument);continue}lt.isObjectProperty(o)&&n(o.value)}return}if(lt.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(lt.isAssignmentPattern(r)){n(r.left);return}if(lt.isRestElement(r)){n(r.argument);return}lt.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Np(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=HE(e),i=HE(t);if(!o||!i||!DE(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=ME(s.node,n);if(a&&!_n(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&&_n(a,n)&&!_n(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())&&XE(s)){let a=tt(s.node.body)??tt(s.node);if(a&&!_n(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 HE(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?tt(t.node.argument):null;if(t.isArrowFunctionExpression()&&(lt.isJSXElement(t.node.body)||lt.isJSXFragment(t.node.body)||lt.isConditionalExpression(t.node.body)||lt.isLogicalExpression(t.node.body)))return tt(t.node.body);t=t.parentPath}return null}function uo(e,t,n){return n.scope.getBinding(t)===e}function Ap(e,t,n,r={}){if(!r.preserveConditionalBoundary&&_l(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(l=>Nl(l)).map(l=>n.callbackPath.scope.getBinding(l)?.path.node).filter(Boolean)),s=new Set,a=(l,c)=>{let u=c.scope.getBinding(l);!u||pr(u.path.node,o)||i.has(u.path.node)||uo(u,l,t)||s.add(l)};return e.traverse({ReferencedIdentifier(l){a(l.node.name,l)},JSXOpeningElement(l){let c=Rp(l.node.name);c&&a(c,l)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Tp(e,t,n){let r=tt(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Nl(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return oa(e,s=>{let a=s.scope.getBinding(s.node.name);!a||pr(a.path.node,r)||o.has(a.path.node)||uo(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function GE(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Nl(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,l)=>{let c=l.scope.getBinding(a);!c||n.has(c.path.node)||uo(c,a,t)||r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(l){o(l.node.name,l)},TSTypeReference(l){let c=l.node.typeName;if(Ti.isIdentifier(c))o(c.name,l);else{let u=WE(c);u&&o(u,l)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function wp(e,t){let n=tt(e.node),r=new Set;return oa(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&pr(i.path.node,n)||uo(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 YE(e){let t=[];for(let n of e.callbackPath.node.params){if(Ti.isIdentifier(n)){t.push(n.name);continue}if(Ti.isRestElement(n)&&Ti.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 ZE(e,t){return{...e,callbackParams:t}}function Op(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function ia(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 qE(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 Xo(e){return{file:e.file,component:e.component}}function hF(e){return e.target.kind==="node"?e.target.key:null}function yF(e){return"kind"in e&&e.kind==="page-composition"}function wl(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="block-boundary"}function Al(e){return!yF(e)&&!wl(e)}function Bp(e,t){let n=Ll.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Ll.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Lp(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=sr(n,rt(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function $p(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 xF(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function bF(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 Fp(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function EF(e){let t=vE(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Np(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=SF({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=aS(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?Pl(o):!0}}}function SF(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||pr(a.path.node,t))return;let l=kF(s,a,t);if(l){if(l.hasDefault){o="Cannot move prop-backed repeat child because the collection prop has a default value that cannot be preserved safely";return}let c=CF(e.callSitePath,l.propName,e.source);if(!c.ok){o=c.reason;return}let u=IF(c.expression,l.remainingPath);if(!u){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let d=wp(c.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(`${l.range.start}:${l.range.end}`,{...l.range,text:u});return}uo(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:RF(e.source,t,[...n.values()])}}function IF(e,t){if(t.length===0)return e;let n=aS(e);if(!n)return null;let r=Pl(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=vF(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function vF(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function kF(e,t,n){let r=_F(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=ki(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 _F(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!pr(n.node,t)||n.node.computed||!Ge.isIdentifier(n.node.property))return null;let r=tt(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function CF(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(l=>l.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let o=r.find(l=>l.isJSXAttribute()&&Ge.isJSXIdentifier(l.node.name)&&l.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=Ni(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 RF(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 aS(e){try{let n=sS.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=Ge.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&Ge.isExpression(r)?r:null}catch{return null}}function PF(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||pr(s.path.node,t))return;let a=QE(s,e.sourceFile,e.targetFile);if(a){let l=e.targetParentPath.scope.getBinding(a.localName);if(l){let u=QE(l,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!NF(u.importSpec,a.importSpec))&&r.add(a.localName);return}let c=n.get(a.moduleSpecifier)??[];c.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||c.push(a.importSpec),n.set(a.moduleSpecifier,c);return}r.add(i.node.name)};return oa(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 NF(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 QE(e,t,n){let r=AF(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Vo(t,i),a=i.startsWith(".")?Bp(n,s):i;if(r.isImportDefaultSpecifier()){let l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:l}}}if(r.isImportNamespaceSpecifier()){let l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:l}}}if(r.isImportSpecifier()){let l=Ge.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:l,local:c===l?void 0:c}}}return null}function AF(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function eS(e,t,n,r){let o=Ip(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let l=Ni(e,a.conditionPath.node);if(!l)return{sourceJsx:r,conditionPaths:[]};let c=TF(a.conditionPath,l);if(s.push(a.conditionPath),a.kind==="logical"){i=`${c} ${a.operator} ${OF(i)}`;continue}i=a.branch==="consequent"?`${c} ? ${i} : null`:`${c} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function TF(e,t){return wF(e.node)?t:`(${t})`}function wF(e){return Ge.isIdentifier(e)||Ge.isThisExpression(e)||Ge.isSuper(e)||Ge.isMemberExpression(e)||Ge.isOptionalMemberExpression(e)||Ge.isCallExpression(e)||Ge.isOptionalCallExpression(e)||Ge.isBooleanLiteral(e)||Ge.isNumericLiteral(e)||Ge.isStringLiteral(e)||Ge.isNullLiteral(e)||Ge.isUnaryExpression(e)}function OF(e){return e.trim().startsWith("<")?e:`(${e})`}var LF={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 Tl(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=LF[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 FF(e,t){for(let n of e.program.body){if(!Ge.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>Ge.isImportDefaultSpecifier(o));if(r&&Ge.isImportDefaultSpecifier(r))return r.local.name}return null}function DF(e,t,n){for(let r of e.program.body){if(!Ge.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>Ge.isImportSpecifier(i)&&(Ge.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&Ge.isImportSpecifier(o))return o.local.name}return null}function tS(e){let t=new Set;return Zn(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function nS(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function MF(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=$p(e),o=Jt(t);if(n.exportName!=="default"){let a=o?DF(o,n.source,n.exportName):null;if(a)return{localName:a};let l=o?nS(r,tS(o)):r;return{localName:l,importStep:Dp(e,l)}}if(!o)return{localName:r,importStep:Dp(e,r)};let i=FF(o,n.source);if(i)return{localName:i};let s=nS(r,tS(o));return{localName:s,importStep:Dp(e,s)}}function BF(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??$p(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 jF(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?$F(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function $F(e){return Object.fromEntries(Object.entries(e).filter(t=>jp(t[1])))}function jp(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(jp):typeof e=="object"?Object.values(e).every(jp):!1}function Dp(e,t=$p(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 rS(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 UF(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function wi(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function Up(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function sa(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:Up(e,t.slice(0,n)),index:r.index}}return null}function Mp(e,t){return e.locator?e.collectionPathMap?.[t]?Up(e.locator,e.collectionPathMap[t]):sa(e.locator)?KF(e.locator,JF(t,e.collectionIndexMap)):null:null}function VF(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:cS(o,t)}function cS(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=cS(r,t);return o===void 0?void 0:{[n.name]:o}}function KF(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},Up(e,i)}return null}function JF(e,t){return t?.[e]??e}function oS(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 XF(e,t){return zF(e.root,t.root)&&WF(e.path??[],t.path??[])}function zF(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&&HF(e.sourceRange,t.sourceRange)}}function HF(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function WF(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 Ol=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:wi(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:wi(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:wi(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:wi(t.kind,t.params.kind)};let r=t;if(wl(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if(!Al(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=rS(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:wi(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:wi(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=hF(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):iS(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 iS(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?VE({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[l,c]of Object.entries(o)){if(c===void 0)continue;let u=await this.graph.getElementPropertyWriteTarget?.(r.key,l),d=r.attributes?.find(m=>m.name===l);if((await this.graph.getPropertyState?.(r.key,l,i))?.status==="blocked"||!u&&d?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${l}'`};if(!(typeof d?.resolvedValue=="string"&&d.resolvedValue===c||d?.source===null&&d.value===c)){if(u?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${l}'`};if(u?.kind==="value-binding"&&u.locator){let m=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let g=Mp(u,i.instanceIndex);if(!g)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};m=g}s.push({order:n+s.length,file:u.file,type:"update-value",locator:m,value:c});continue}a.push({operation:"set",name:l,value:c})}}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=Mp(o,i.instanceIndex);if(!a)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(o.file,a,r);return l.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-array-item",locator:a,value:l.value}]}:l}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=Jt(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=De(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!xF(a.match.path))return{ok:!0,value:r};let l=bF(r);return l===null?{ok:!1,errorCode:"invalid-params",reason:`${o} value must be a valid number for numeric source`}:{ok:!0,value:l}}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 l=Mp(o,i);if(!l)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item could not resolve the selected repeat item"};let c=this.coerceTextValueForValueTarget(o.file,l,s,"update-array-item");return c.ok?this.isValueTargetUnchanged(o.file,l,c.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:l,value:c.value}],r):c}isValueTargetUnchanged(t,n,r){let o=Jt(this.graph.getFileContent(t));if(!o)return!1;let i=De(o,n);if(!i.ok)return!1;let s=i.match.path;if(s.isStringLiteral())return typeof r=="string"&&s.node.value===r;if(s.isNumericLiteral())return typeof r=="number"&&Object.is(s.node.value,r);if(s.isBooleanLiteral())return typeof r=="boolean"&&s.node.value===r;if(s.isNullLiteral())return r===null;if(s.isUnaryExpression({operator:"-"})){let a=s.get("argument");return typeof r=="number"&&!Array.isArray(a)&&a.isNumericLiteral()&&Object.is(-a.node.value,r)}return!1}planUpdateText(t,n,r,o,i){let s=this.graph.getTextProvenance?.(r.key,n.params.segmentIndex);if(s&&(s.editMode==="readonly"||s.editMode==="unsupported"))return{ok:!1,errorCode:"unsupported-operation",reason:"Text has no identity-preserving write target"};if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let a=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return a.ok?this.buildPlan(t,n,a.steps,o):a}async planRemoveNode(t,n,r,o){if(!o.canRemove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot remove this node"};let i=await this.graph.getTextWriteTarget(r.key,0);if(i?.kind==="external-entry")return this.buildPlan(t,n,[{order:0,file:`external:${i.sourceId}`,type:"invoke-external-adapter",sourceType:i.sourceType,sourceId:i.sourceId,adapterId:i.adapterId,capability:"remove-node",value:{operation:"remove-node"}}],o);if(r.isRepeatItemRoot){let d=i;if(d?.kind==="value-binding"&&d.locator){let f=sa(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=ia(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 l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let c=[{order:0,file:r.file,type:"remove-node",locator:rt(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&c.push({...u,order:c.length}),this.buildPlan(t,n,c,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||FE(n,t)>1)return null;let r=Bp(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(!Al(n.params.position))return wl(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,l=ia(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};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 m=hE(this.graph.getFileContent(r.file),r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot insert child into this node"};let g=Tl(r,n.params.node);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let p=[],h=0,x=n.params.node.kind==="component-call"?MF(n.params.node,this.graph.getFileContent(r.file)):void 0,b=x?.importStep;return b&&p.push({order:h++,file:r.file,type:"add-import",moduleSpecifier:b.moduleSpecifier,imports:b.imports}),p.push({order:h++,file:r.file,type:"insert-child",parentLocator:rt(r),node:{jsx:BF(n.params.node,x?.localName)},placement:n.params.position.relation,anchorLocator:i?rt(i):void 0}),this.buildPlan(t,n,p,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Al(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 l=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:l?.kind==="external-entry"?l.sourceId:null,node:jF(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(!Al(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 l=sa(a.locator);if(!l)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let c=VF(a.locator,i.text);if(c===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"?oS(0,a.collectionIndexMap):oS(a.collectionIndexMap?.length??l.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:l.locator,index:u,value:c}],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=ia(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:")||zE(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 l=this.graph.getFileContent(r.file),c=Jt(l);if(!c)return null;let u=Un(c,r),d=Un(c,o);if(!u||!d)return null;let f=gr(l,u),m=gr(l,d);if(!ra(f,m))return null;if(a&&(s==="before"||s==="after")){let p=Un(c,a),h=p?gr(l,p):null;if(!ra(f,h))return null}if(Cl(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=Pp(l,r,o);return g.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:Xo(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:g.reason??`Cannot move node because it depends on bindings outside the target scope: ${g.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&Ai(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let l=this.graph.getFileContent(r.file),c=Jt(l);if(!c)return null;let u=Un(c,r),d=Un(c,o);if(!u||!d)return null;let f=gr(l,u);if(!f)return null;let m=gr(l,d);if(ra(f,m))return null;if(m&&!JE(m,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 E=Cp(l,c,a);if(m&&!ra(m,E)||!m&&E)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 E=Tl(o,{kind:"native-tag",tag:r.tag});if(E)return{ok:!1,errorCode:"unsupported-operation",reason:E}}let g=Lp(this.graph,r);if(!g)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Cl(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let p=eS(l,u,d,g);for(let E of p.conditionPaths){let S=Tp(E,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 h=Ap(u,d,f,{preserveConditionalBoundary:p.conditionPaths.length>0});if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${h.bindingNames.join(", ")}`};let x=GE(f,d);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let b=f;if(r.component!==o.component){let E=EF({source:l,ast:c,sourceContext:f,sourceNode:r,targetParent:o,targetParentPath:d});if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason};b=E.context}else{let E=wp(f.collectionPath,d);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${E.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:Op(b,p.sourceJsx),selectionContext:Xo(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 l=this.graph.getFileContent(r.file),c=this.graph.getFileContent(o.file),u=Jt(l),d=Jt(c);if(!u||!d)return null;let f=BE({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 m=Un(u,r),g=Un(d,o);if(!m||!g)return null;let p=Np(f.callSitePath,g);if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let h=gr(l,m);if(!h)return null;if(gr(c,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Cp(c,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 k=Tl(o,{kind:"native-tag",tag:r.tag});if(k)return{ok:!1,errorCode:"unsupported-operation",reason:k}}let b=Lp(this.graph,r);if(!b)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Cl(m,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let E=eS(l,m,g,b);for(let k of E.conditionPaths){let T=Tp(k,g,h);if(!T.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${T.bindingNames.join(", ")}`}}let S=Ap(m,g,h,{preserveConditionalBoundary:E.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=PF({sourceFile:r.file,targetFile:o.file,sourceContext:h,targetParentPath:g});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason};let A=YE(h);if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason};let I=ZE(h,A.callbackParams),_=[{order:0,file:r.file,type:"remove-node",locator:rt(r),removeWhitespace:!0}];for(let k of v.imports)_.push({order:_.length,file:o.file,type:"add-import",moduleSpecifier:k.moduleSpecifier,imports:k.imports});return _.push({order:_.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:rt(o),expression:Op(I,E.sourceJsx),placement:s,anchorLocator:a?rt(a):void 0,selectionContext:Xo(o)}),this.buildPlan(t,n,_,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if(wl(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 E=n.params.target,S=this.graph.getNode(E.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 A=this.graph.getFileContent(r.file),I=Jt(A),_=I?Un(I,r):null,k=I?Un(I,S):null,T=_?.parentPath,L=k?.parentPath;if(!_||!k||!T||!L||T.node!==L.node||!T.isJSXFragment()&&!(T.isJSXElement()&>(T)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let $=T.node.loc;return $?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:rt(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:$.start.line,startColumn:$.start.column,endLine:$.end.line,endColumn:$.end.column}},placement:E.relation,anchorLocator:rt(S),selectionContext:Xo(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=rS(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(UF(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 l=await this.graph.getTextWriteTarget(r.key,0);if(l?.kind==="external-entry"){let E=n.params.target.relation,S=i.anchorNode&&(E==="before"||E==="after")?await this.graph.getTextWriteTarget(i.anchorNode.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${l.sourceId}`,type:"invoke-external-adapter",sourceType:l.sourceType,sourceId:l.sourceId,adapterId:l.adapterId,capability:"move-node",value:{operation:"move-node",relation:E,anchorSourceId:S?.kind==="external-entry"?S.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let c=r.file!==s.file,u=n.params.target.relation,d=i.anchorNode,f=this.graph.getTextProvenance?.(r.key,0)??null,m=ia(r,l,f);if(m&&!Fp(m)&&!qE(r,s,l,f))return{ok:!1,errorCode:"unsupported-operation",reason:m};if(r.isRepeatItemRoot&&d?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===d.repeatOwnerKey&&(u==="before"||u==="after")){let E=l,S=await this.graph.getTextWriteTarget(d.key,0);if(E?.kind==="value-binding"&&S?.kind==="value-binding"&&E.locator&&S.locator){let v=sa(E.locator),A=sa(S.locator);if(v&&A&&E.file===S.file&&XF(v.locator,A.locator)){let I=v.index,_=A.index,k=u==="before"?_-(I<_?1:0):_+(I<_?0:1);return this.buildPlan(t,n,[{order:0,file:E.file,type:"move-array-item",locator:v.locator,fromIndex:I,toIndex:k}],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 g=this.getRepeatBackedTemplateStructureReason(r),p=Fp(m)?m:g;if(p&&Fp(p)){let E=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(E)return E;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(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let h=await this.getUpstreamBackedDescendantReason(r);if(h)return{ok:!1,errorCode:"unsupported-operation",reason:h};if(r.tag&&r.tag.toLowerCase()===r.tag){let E=Tl(s,{kind:"native-tag",tag:r.tag});if(E)return{ok:!1,errorCode:"unsupported-operation",reason:E}}if(c)return this.planCrossFileMove(t,n,r,s,o,u,d);let x=Pp(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 b=[{order:0,file:r.file,type:"move-node",locator:rt(r),targetParentLocator:rt(s),placement:u,anchorLocator:d?rt(d):void 0,selectionContext:Xo(s)}];return this.buildPlan(t,n,b,o)}planCrossFileMove(t,n,r,o,i,s,a){let l=[],c=0,u=this.graph.getFileContent(r.file),d=Lp(this.graph,r)??`<${r.component} />`,f=yE(u,r);if(!f.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason??"Cannot move subtree across files"};if(l.push({order:c++,file:r.file,type:"remove-node",locator:rt(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,h={moduleSpecifier:Bp(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:g}]:[{kind:"named",imported:r.exportName,local:g===r.exportName?void 0:g}]};l.push({order:c++,file:o.file,type:"add-import",moduleSpecifier:h.moduleSpecifier,imports:h.imports}),l.push({order:c++,file:o.file,type:"insert-child",parentLocator:rt(o),node:{jsx:d},placement:s,anchorLocator:a?rt(a):void 0,selectionContext:Xo(o)})}else l.push({order:c++,file:o.file,type:"insert-child",parentLocator:rt(o),node:{jsx:d},placement:s,anchorLocator:a?rt(a):void 0,selectionContext:Xo(o)});let m=this.buildRemoveComponentImportStep(r,u);return m&&l.push({...m,order:c++}),this.buildPlan(t,n,l,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:je(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};function iS(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 Wp from"@babel/generator";import{parse as cD,parseExpression as lD}from"@babel/parser";import*as R from"@babel/types";import*as hr from"@babel/types";import Vp from"@babel/generator";import*as at from"@babel/types";var GF=typeof Vp=="function"?Vp:Vp.default,YF=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,ZF=/^((?:https?:)?\/\/)[^/@\s]+@/i,qF=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function uS(e,t){let n=Cn(e.callee);if(!n)return null;if(n==="fetch")return Kp(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(lS(r))return Kp(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(lS(r))return Kp(e.arguments[0],r,t,["ky client contract"])}return null}function Kp(e,t,n,r){if(!e||at.isSpreadElement(e)||at.isJSXNamespacedName(e))return nD(t,n,r,"missing url argument");let o=aa(e);return{sourceKind:tD(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 aa(e){if(at.isStringLiteral(e))return zo(e.value);if(at.isTemplateLiteral(e))return zo(QF(e));if(at.isBinaryExpression(e)&&e.operator==="+"){let t=aa(e.left),n=aa(e.right);return!t&&!n?void 0:zo(`${t??Jp(e.left)}${n??Jp(e.right)}`)}if(at.isMemberExpression(e)){let t=dS(e);if(t)return`env:${t}`}if(!(at.isCallExpression(e)&&Cn(e.callee)==="new URL")){if(at.isNewExpression(e)&&at.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!at.isSpreadElement(t)?aa(t):void 0,o=n&&!at.isSpreadElement(n)?aa(n):void 0;return o&&r?zo(`${o} + ${r}`):r??o}if(at.isIdentifier(e))return`:${e.name}`}}function QF(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+=Jp(r))}return t}function Jp(e){if(at.isIdentifier(e))return`:${e.name}`;if(at.isMemberExpression(e)){let t=dS(e);if(t)return`env:${t}`}return`:${eD(e)}`}function eD(e){return GF(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function zo(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(ZF,"$1<redacted>@").replace(qF,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?YF.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function tD(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 nD(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function lS(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function dS(e){return!at.isMemberExpression(e.object)||!at.isIdentifier(e.object.object,{name:"process"})||!rD(e.object.property,"env")?null:at.isIdentifier(e.property)?e.property.name:at.isStringLiteral(e.property)?e.property.value:null}function rD(e,t){return at.isIdentifier(e)&&e.name===t}function Cn(e){if(at.isIdentifier(e))return e.name;if(at.isMemberExpression(e)){let t=Cn(e.object),n=at.isIdentifier(e.property)?e.property.name:at.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var oD=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),iD=new Set(["getConfig","submit"]);function Dr(e,t){let n=fS(Cn(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!oD.has(i))return null;let s=Xp(e,0),a=i==="getByUrl"||i==="getByUrlStrict",l=a?void 0:s,c=a?s??"/:record-url":l?`/collections/${l}`:"/collections/:collection";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:i,...l?{collection:l}:{},endpointPattern:c,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(!iD.has(i))return null;let s=Xp(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=Xp(e,0)??sD(e,0,"path")??"/cms/:path",s=aD(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 fS(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 pS(e,t){let n=Cn(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 Fl(e,t){let n=Cn(e.callee),r=t?fS(n,t):n;return typeof r=="string"&&r.startsWith("cms.field.")}function Xp(e,t){let n=e.arguments[t];return hr.isStringLiteral(n)?n.value:null}function sD(e,t,n){let r=e.arguments[t];if(!hr.isObjectExpression(r))return null;for(let o of r.properties)if(hr.isObjectProperty(o)&&!o.computed&&(hr.isIdentifier(o.key)&&o.key.name===n||hr.isStringLiteral(o.key)&&o.key.value===n)&&hr.isStringLiteral(o.value))return o.value.value;return null}function aD(e){let t=/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1];return t&&/^[a-z0-9][a-z0-9_-]*$/i.test(t)?t:null}function Dl(e){return e.match(/^\/([a-z0-9][a-z0-9_-]*)\/[^/?#]+(?:[?#].*)?$/i)?.[1]??null}import*as Mt from"@babel/types";var zp=new WeakMap;function yr(e,t){let n=zp.get(e)?.get(t);if(n!==void 0)return n;let r=new Set([t]),o=c=>{let u=c;for(;Mt.isMemberExpression(u)||Mt.isOptionalMemberExpression(u);)u=u.object;return Mt.isIdentifier(u)?u.name:null},i=!0;for(;i;)i=!1,Mt.traverseFast(e,c=>{if(!Mt.isVariableDeclarator(c)||!c.init)return;let u=o(c.init);if(!(!u||!r.has(u)))for(let d of Object.keys(Mt.getBindingIdentifiers(c.id)))r.has(d)||(r.add(d),i=!0)});let s=c=>{let u=o(c);return u?r.has(u):Object.keys(Mt.getBindingIdentifiers(c)).some(d=>r.has(d))},a=!1;Mt.traverseFast(e,c=>{(Mt.isAssignmentExpression(c)&&s(c.left)||Mt.isUpdateExpression(c)&&s(c.argument)||Mt.isUnaryExpression(c,{operator:"delete"})&&s(c.argument))&&(a=!0)});let l=zp.get(e)??new Map;return l.set(t,a),zp.set(e,l),a}function mS(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:l,maxImportDepth:c}=o,u=t.get(s)?.get(a)?.get(l)?.get(c);if(u)return u.pending;let d=i();n.size>=e&&r(n.values().next().value);let f={fromFile:s,exportName:a,targetFile:l,maxImportDepth:c,pending:d},m=t.get(s)??new Map,g=m.get(a)??new Map,p=g.get(l)??new Map;return p.set(c,f),g.set(l,p),m.set(a,g),t.set(s,m),n.add(f),d.catch(()=>{r(f)}),d}}}import*as qt from"@babel/types";import{posix as Hp}from"node:path";function Oi(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 c=Oi(e.argument,t,r);return c===void 0?void 0:!c}if(qt.isLogicalExpression(e)){let c=Oi(e.left,t,r),u=Oi(e.right,t,r);if(e.operator==="&&")return c===!1||u===!1?!1:c===!0?u:void 0;if(e.operator==="||")return c===!0||u===!0?!0:c===!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?Hp.normalize(Hp.join(Hp.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 l=s.params.flatMap(c=>qt.isIdentifier(c)?[c.name]:[]);return Oi(a,{file:t.file,imports:new Map([...t.imports].filter(([c])=>!l.includes(c))),functions:new Map([...t.functions].filter(([c])=>!l.includes(c)))},r.add(s))}var fG=typeof Wp=="function"?Wp:Wp.default,kS=new WeakMap;function _S(e){let t=new Map;return kS.set(t,new Map([...e].map(n=>[n.file,n]))),t}var uD={maxFunctionDepth:8,maxImportDepth:6},dD=new Set(["src","href","alt","poster","content","title","aria-label"]),gS=new WeakMap;function fD(e,t,n){let r=gS.get(t.fileCache);r||(r=new WeakMap,gS.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 m=o.local.get(d.sourceFile);m||(m=new Map,o.local.set(d.sourceFile,m));let g=m.get(d.tag)??[];g.push(f),m.set(d.tag,g)}r.set(e,o)}let i=o.local.get(t.file)?.get(n)??[],s=o.imported,a=[],l=0,c=0;for(;l<s.length||c<i.length;){let u=s[l],d=i[c];u&&(!d||u.order<d.order)?(a.push(u.element),l++):d&&(!u||d.order<u.order)?(a.push(d.element),c++):(a.push(u.element),l++,c++)}return a}async function zl(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")&&yS(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=em(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...uD,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,paramArguments:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:$S(n,e.element.componentName),scopeFunction:tm(n,e.element.componentName)};await CS(e.element.componentName,e.graph,r);let o=[];o.push(...await hD(e.element,e.graph,r),...await yD(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await xD(s,e.element,e.graph,r);a&&o.push(Jl(a,"text","children"))}for(let s of e.element.attributes??[]){let a=yS(s,e.element);if(!a)continue;let l=await NS(s.source,e.element,e.graph,r);if(!l&&s.syntaxKind==="expression"&&!(s.source&&Wo(s.source.base,e.element,e.graph))){let u=n.jsxElementsByRange.get(Hl(e.element.sourceRange))?.openingElement.attributes.find(d=>R.isJSXAttribute(d)&&R.isJSXIdentifier(d.name,{name:s.name}));R.isJSXExpressionContainer(u?.value)&&R.isExpression(u.value.expression)&&!TS(u.value.expression,e.element,e.graph)&&(l=await yt(u.value.expression,r))}l&&o.push(Jl(l,a,s.name))}let i=AD(o).sort(BS);return{hasDynamicData:i.length>0,bindings:i}}async function CS(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 c of fD(t,n,e)){if(c.sourceFile===n.file&&c.tag===e){s.push(c);continue}!c.importedFrom||!c.exportName||c.importedFrom===n.file&&c.exportName!==i||(c.importedFrom===n.file||await pD(c.importedFrom,c.exportName,n.file,n))&&s.push(c)}if(s.length===0)return;let a=new Map;for(let c of s){let u=`${n.file}#${e}<-${c.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let d=await PS(c.sourceFile,n);if(!d)continue;let f=go(d,n,{importDepth:n.importDepth+1});f.paramSources.clear(),f.scopeVariables=$S(d,c.componentName),f.scopeFunction=tm(d,c.componentName),f.lexicalContext=void 0,await CS(c.componentName,t,f);let m=await mD(c,t,f);for(let[g,p]of m){if(!p)continue;let h=a.get(g)??[];h.push(p),a.set(g,h)}}finally{n.resolvingComponentProps.delete(u)}}}let l=new Map;for(let[c,u]of a){let d=Qp(u);d.length===1&&l.set(c,d[0])}gD(o,l,n)}var hS=new WeakMap;function pD(e,t,n,r){let o=hS.get(r.fileCache);return o||(o=mS(),hS.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>RS(e,t,n,r))}async function RS(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 PS(e,r))?.imports.get(t);if(!s||!kt(s.source))return!1;let a=await rm(e,s.source,r.exists);return a?a===n?!0:RS(a,s.importedName,n,r,o):!1}async function mD(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(Hl(e.sourceRange));if(o)for(let s of o.openingElement.attributes)!R.isJSXAttribute(s)||!R.isJSXIdentifier(s.name)||!R.isJSXExpressionContainer(s.value)||!R.isExpression(s.value.expression)||r.set(s.name.name,s.value.expression);let i=new Map;for(let[s,a]of r){let l=e.attributes?.find(d=>d.name===s)?.source??null,u=(l?Wo(l.base,e,t):null)?await Wl(l,e,t,n):TS(a,e,t)?null:await yt(a,n);u&&i.set(s,u)}return i}function Hl(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function PS(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 em(e,r,t.fileCache)}function gD(e,t,n){if(R.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Kl(Object.fromEntries(t),n.file));return}if(R.isObjectPattern(e))for(let r of e.properties){if(!R.isObjectProperty(r)||r.computed||!R.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=R.isAssignmentPattern(r.value)?r.value.left:r.value;R.isIdentifier(i)&&n.paramSources.set(i.name,Ht(o))}}function yS(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":dD.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function hD(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 Gl(i.collectionSource,n);s&&r.push(Jl(fo(s),"repeat-region",i.collectionExpression))}return r}async function yD(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 Gl(i.conditionSource,n);s&&r.push(Jl(fo(s),"conditional-region",i.conditionExpression))}return r}async function xD(e,t,n,r){if(!e.source){let i=r.analysis.jsxElementsByRange.get(Hl(t.sourceRange))?.children.find(s=>R.isJSXExpressionContainer(s)&&s.loc?.start.line===e.sourceRange.startLine&&s.loc.start.column===e.sourceRange.startColumn&&s.loc.end.line===e.sourceRange.endLine&&s.loc.end.column===e.sourceRange.endColumn);return R.isJSXExpressionContainer(i)&&R.isCallExpression(i.expression)&&Fl(i.expression)?AS(i.expression,t,n,r):null}return NS(e.source,t,n,r)}async function NS(e,t,n,r){return e&&Wo(e.base,t,n)?Wl(e,t,n,r):Gl(e,r)}async function Wl(e,t,n,r,o){if(!e)return null;let i=Wo(e.base,t,n,o);if(!i||i.candidate.itemParamName!==e.base)return null;let s=i.candidate.collectionSource,l=(s?Wo(s.base,t,n,i.region):null)?await Wl(s,t,n,r,i.region):s?await Gl(s,r):await bD(i.candidate.collectionExpression,t,n,r,i.region);return l?ca(l,e.path,!0):null}async function bD(e,t,n,r,o){let i;try{i=lD(e,{plugins:["typescript","jsx"]})}catch{return null}return AS(i,t,n,r,o)}async function AS(e,t,n,r,o){let i=go(r.analysis,r),s=new Set;R.traverseFast(e,a=>{R.isIdentifier(a)&&s.add(a.name)});for(let a of s){let l=Wo(a,t,n,o);if(!l)continue;if(l.candidate.itemParamName!==a)return null;let c=await Wl({kind:"identifier",expression:a,base:a,path:[]},t,n,r,o);if(!c)return null;i.paramSources.set(a,c)}return yt(e,i)}function Wo(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&&!xS(s.sourceRange,r.sourceRange))continue;let a=s.sourceCandidates?.find(l=>l.kind==="repeat-template"&&(l.itemParamName===e||l.indexParamName===e));a&&(!i||xS(i.region.sourceRange,s.sourceRange))&&(i={candidate:a,region:s})}o=n.elements.get(o)?.parentKey??null}return i}function xS(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 TS(e,t,n){let r=!1;return R.traverseFast(e,o=>{!r&&R.isIdentifier(o)&&Wo(o.name,t,n)&&(r=!0)}),r}async function Gl(e,t){if(!e)return null;let n=await Zp(e.base,t);return n?ca(n,e.path,!1):null}async function Zp(e,t){let n=t.paramSources.get(e);if(n)return Ht(n);if(t.variableCache.has(e))return TD(t.variableCache.get(e)??null);let r=mo(e,t);if(r&&r!==t)return Zp(e,r);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let o=await SD(e,t);if(o)return t.variableCache.set(e,Ht(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 l=R.isArrayExpression(s)&&s.elements.length===0?await ED(e,t):await yt(s,t);return t.variableCache.set(e,l?Ht(l):null),t.resolvingVariables.delete(e),l}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 l=await nm(a,t);if(l){let c=go(l,t,{importDepth:t.importDepth+1}),u=US(a,l);if(u){let m=(await Ho(u,[],c)).returnSource;return t.variableCache.set(e,m?Ht(m):null),t.resolvingVariables.delete(e),m}let d=l.variables.get(a.importedName);if(d){let f=await yt(d,c);return t.variableCache.set(e,f?Ht(f):null),t.resolvingVariables.delete(e),f}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function mo(e,t){return t.scopeVariables?.has(e)||t.scopeFunction?.params.some(n=>po(n).includes(e))?t:t.lexicalContext?mo(e,t.lexicalContext):void 0}function Ml(e,t,n=new Set){if(R.isIdentifier(e)){let s=mo(e.name,t);if(s&&s!==t)return Ml(e,s,n)}if(n.has(e))return null;if(n.add(e),R.isStringLiteral(e))return e.value;if(!R.isIdentifier(e))return null;let r=mo(e.name,t),o=t.paramArguments.get(e.name);if(o)return Ml(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?Ml(i,t,n):null}function xr(e,t,n=new Set){if(n.has(e))return null;let r=new Set(n).add(e);if(R.isStringLiteral(e))return e.value;if(R.isNumericLiteral(e))return String(e.value);if(R.isIdentifier(e)){if(/token|secret|password|authorization|cookie|credential/i.test(e.name))return":redacted";let o=mo(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?xr(s.expression,s.context,r):a?xr(a,i,r):null)??`:${e.name}`}if(R.isBinaryExpression(e,{operator:"+"})){let o=xr(e.left,t,r),i=xr(e.right,t,r);return o!==null&&i!==null?o+i:null}if(R.isTemplateLiteral(e)){let o=e.quasis[0]?.value.cooked??"";for(let[i,s]of e.expressions.entries()){if(!R.isExpression(s))return null;o+=(xr(s,t,r)??":param")+(e.quasis[i+1]?.value.cooked??"")}return o}if(R.isCallExpression(e)&&R.isIdentifier(e.callee)&&["encodeURIComponent","decodeURIComponent"].includes(e.callee.name)&&R.isExpression(e.arguments[0])){let o=xr(e.arguments[0],t,r);if(o===null||o.startsWith(":"))return o;try{return e.callee.name==="encodeURIComponent"?encodeURIComponent(o):decodeURIComponent(o)}catch{return null}}return R.isTSAsExpression(e)||R.isTSNonNullExpression(e)||R.isParenthesizedExpression(e)?xr(e.expression,t,r):null}async function ED(e,t){let n=t.scopeFunction;if(!n)return null;let r=[],o=!1,i=0,s=u=>{let d=!1;return R.traverseFast(u,f=>{R.isIdentifier(f,{name:e})&&(d=!0)}),d},a=u=>{let d=u;for(;R.isMemberExpression(d);)d=d.object;return R.isIdentifier(d,{name:e})},l=async(u,d)=>{if(!o){if(R.isFunction(u)){s(u)&&(o=!0);return}if(R.isVariableDeclarator(u)&&(po(u.id).includes(e)&&i++,u.init&&s(u.init)&&(o=!0)),(R.isAssignmentExpression(u)||R.isUpdateExpression(u))&&a(R.isAssignmentExpression(u)?u.left:u.argument)){o=!0;return}if(R.isUnaryExpression(u,{operator:"delete"})&&a(u.argument)){o=!0;return}if(R.isCallExpression(u)){if(R.isMemberExpression(u.callee)&&R.isIdentifier(u.callee.object,{name:e})){if(!R.isIdentifier(u.callee.property,{name:"push"})||u.callee.computed||!u.arguments.length){o=!0;return}for(let f of u.arguments){let m=R.isSpreadElement(f)?f.argument:f,g=R.isExpression(m)?await yt(m,d):null;g?r.push(Yp(g)):o=!0}return}if(u.arguments.some(f=>s(f))){o=!0;return}}if(R.isForOfStatement(u)){let f=await yt(u.right,d),m=go(d.analysis,d),g=R.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;f&&g&&Ul(g,Yp(f),m),await l(u.body,m);return}for(let f of R.VISITOR_KEYS[u.type]??[]){let m=u[f];for(let g of Array.isArray(m)?m:[m])R.isNode(g)&&await l(g,d)}}};await l(n.body,t);let c=Qp(r);return!o&&i===1&&c.length===1?fo(c[0]):null}async function SD(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 yt(o,t);if(i)return i}return null}async function yt(e,t){if(R.isIdentifier(e))return Zp(e.name,t);if(R.isMemberExpression(e)||R.isOptionalMemberExpression(e)){let n=R.isMemberExpression(e)?pS(e,{file:t.file}):null;if(n)return DS(n);let r=await ID(e,t);if(!r)return null;let o=ND(e);return ca(r,o,!1)}if(R.isAwaitExpression(e))return R.isExpression(e.argument)?yt(e.argument,t):null;if((R.isCallExpression(e)||R.isOptionalCallExpression(e))&&(R.isMemberExpression(e.callee)||R.isOptionalMemberExpression(e.callee))&&!e.callee.computed&&R.isIdentifier(e.callee.property)&&["trim","trimStart","trimEnd"].includes(e.callee.property.name)&&e.arguments.length===0&&R.isExpression(e.callee.object))return Fi(await yt(e.callee.object,t));if(R.isCallExpression(e))return OS(e,t);if(R.isObjectExpression(e)){let n=await FS(e,t);return Object.keys(n).length>0?Kl(n,t.file):null}if(R.isArrayExpression(e)){let n={};for(let[r,o]of e.elements.entries()){if(!R.isExpression(o))continue;let i=await yt(o,t);i&&(n[String(r)]=i)}return Object.keys(n).length?Kl(n,t.file):null}if(R.isConditionalExpression(e)){let n=await yt(e.consequent,t),r=await yt(e.alternate,t);return Fi(SS(n,r))}if(R.isLogicalExpression(e)){let n=await yt(e.left,t),r=await yt(e.right,t);return Fi(SS(n,r))}return R.isTSAsExpression(e)||R.isTSSatisfiesExpression(e)||R.isTSNonNullExpression(e)||R.isTypeCastExpression(e)||R.isParenthesizedExpression(e)?yt(e.expression,t):null}async function ID(e,t){let n=e;for(;R.isMemberExpression(n)||R.isOptionalMemberExpression(n);)n=n.object;return R.isExpression(n)?yt(n,t):null}async function wS(e,t,n=0){if(n>=t.options.maxFunctionDepth)return null;let r=mo(e,t);if(r){if(r.scopeFunction&&yr(r.scopeFunction,e))return null;let s=r.paramArguments.get(e);return s&&R.isIdentifier(s.expression)?wS(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)||yr(t.analysis.ast,e))return null;let i=await rm(t.file,o.source,t.exists);return i?{...o,source:i}:null}async function OS(e,t){let n=e.arguments[0],r=R.isExpression(n)?Ml(n,t):null,i=Cn(e.callee)?.split(".")[0],s=i?await wS(i,t):null,a=r!==null&&!R.isStringLiteral(n)?{...e,arguments:[R.stringLiteral(r),...e.arguments.slice(1)]}:e;if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&R.isObjectExpression(n)){let x=LS(n,"path"),b=x&&xr(x,t);b?.startsWith("/")&&(a={...e,arguments:[{...n,properties:n.properties.map(E=>R.isObjectProperty(E)&&Mi(E)==="path"?{...E,value:R.stringLiteral(zo(b))}:E)},...e.arguments.slice(1)]})}let l=Dr(a,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map});if(l){if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&l.endpointPattern==="/content/by-url"&&R.isObjectExpression(n)){let x=bS(n,"query"),b=R.isObjectExpression(x)?bS(x,"path"):null,E=b&&xr(b,t),S=E&&Dl(E);S&&(l.collection=S,l.evidence.push({file:t.file,reason:"CMS collection namespace from the actual content request path"}))}if(R.isMemberExpression(e.callee)){let x=await Mr(e.callee,t);if(x&&!Bl(x.node))return null;if(x&&Bl(x.node)){let b=await Gp(e,t,{node:x.node,context:x.context});return b&&{...b,...b.sourceKind===l.sourceKind?{operation:l.operation}:{}}}}if((l.operation==="getByUrl"||l.operation==="getByUrlStrict")&&R.isExpression(n)){let x=xr(n,t);x?.startsWith("/")&&(l.endpointPattern=zo(x))}return DS(l)}if(Cn(e.callee)==="Promise.all"&&R.isArrayExpression(n))return yt(n,t);if(Fl(e)){if(!Fl(e,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map})||!R.isExpression(e.callee))return null;let x=await Mr(e.callee,t);if(x)return Bl(x.node)?Gp(e,t,{node:x.node,context:x.context}):null;let b=e.arguments[0];if(b&&R.isExpression(b))return Fi(await yt(b,t))}let c=await vD(e,t);if(c)return c;let u=uS(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 _D(e,t);if(d)return d;let f=await CD(e,t);if(f)return f;let m=await RD(e,t);if(m)return m;let g=await Gp(e,t);if(g)return g;let p=[];for(let x of e.arguments)if(R.isExpression(x)){let b=await yt(x,t);b&&p.push(b)}let h=Qp(p);return h.length===1?Fi(h[0]):null}async function vD(e,t){let n=Cn(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=kD(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(R.isIdentifier(s)){let a=await Di(s.name,t);if(a)return(await Ho(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!R.isObjectExpression(r))return jl(t.file,`${n} without static options`);let o=LS(r,"queryFn");if(!o)return jl(t.file,`${n} without queryFn`);if(R.isIdentifier(o)){let i=await Di(o.name,t);return i?(await Ho(i.node,[],i.context)).returnSource:jl(t.file,`${n} queryFn unresolved`)}return R.isArrowFunctionExpression(o)||R.isFunctionExpression(o)?(await Ho(o,[],t)).returnSource:R.isCallExpression(o)?OS(o,t):null}function LS(e,t){for(let n of e.properties){if(!R.isObjectProperty(n)||!R.isExpression(n.value))continue;if(Mi(n)===t)return n.value}return null}function bS(e,t){let n=new Set;for(let i of e.properties){if(!R.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=>R.isObjectProperty(i)&&Mi(i)===t);if(r.length!==1)return null;let o=r[0];return R.isObjectProperty(o)&&R.isExpression(o.value)?o.value:null}function kD(e,t,n){return R.isStringLiteral(e)?{sourceKind:e.value.startsWith("/api/")?"site-api-route":"external-api",sourceType:"api-field",endpointPattern:e.value,confidence:"exact",readonly:!0,evidence:[{file:t,reason:n}]}:null}async function _D(e,t){if(!R.isMemberExpression(e.callee)||!R.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted","reverse","toReversed"].includes(n))return null;let r=R.isExpression(e.callee.object)?await yt(e.callee.object,t):null;if(!r)return null;if(n!=="map")return fo(r);let o=e.arguments[0];if(R.isIdentifier(o)){let i=await Di(o.name,t);if(!i)return fo(r);let s=await Ho(i.node,[r],i.context);return{...fo(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(R.isArrowFunctionExpression(o)||R.isFunctionExpression(o)){let i=await Ho(o,[r],t);return{...fo(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return fo(r)}async function CD(e,t){return!R.isMemberExpression(e.callee)||!R.isIdentifier(e.callee.property,{name:"json"})||!R.isExpression(e.callee.object)?null:yt(e.callee.object,t)}async function RD(e,t){return!R.isMemberExpression(e.callee)||!R.isIdentifier(e.callee.property,{name:"then"})||!R.isExpression(e.callee.object)?null:Fi(await yt(e.callee.object,t))}async function Gp(e,t,n){let r=n;if(!r&&R.isIdentifier(e.callee))r=await Di(e.callee.name,t)??void 0;else if(!r&&R.isMemberExpression(e.callee)){let s=await Mr(e.callee,t);s&&Bl(s.node)&&(r={node:s.node,context:s.context})}if(!r)return null;let o=[];for(let s of e.arguments){if(!R.isExpression(s)){o.push(jl(t.file,`unsupported argument for ${Cn(e.callee)??"call"}`));continue}let a=await yt(s,t);o.push(a)}return(await Ho(r.node,o,r.context,{arguments:e.arguments,context:t})).returnSource}function Bl(e){return R.isFunctionDeclaration(e)||Xl(e)||R.isObjectMethod(e)&&e.kind==="method"}async function Mr(e,t,n=new Set){let r={node:null,context:t};if(n.has(e)||n.size>=32)return r;let o=new Set(n).add(e);if(R.isTSAsExpression(e)||R.isTSSatisfiesExpression(e)||R.isTSNonNullExpression(e))return Mr(e.expression,t,o);if(R.isIdentifier(e)){let i=mo(e.name,t),s=i??t;if(yr(i?.scopeFunction??t.analysis.ast,e.name))return r;let a=s.paramArguments.get(e.name);if(a)return Mr(a.expression,a.context,o);let l=i?i.scopeVariables?.get(e.name):s.analysis.variables.get(e.name);if(l)return Mr(l,s,o);if(i)return null;let c=s.analysis.functions.get(e.name);if(c)return{node:c,context:s};let u=s.analysis.imports.get(e.name);if(!u||s.importDepth>=s.options.maxImportDepth)return null;let d=await nm(u,s);return d?Mr(R.identifier(u.importedName),go(d,s,{importDepth:s.importDepth+1}),o):null}if(R.isMemberExpression(e)&&R.isExpression(e.object)){let i=e.computed?R.isStringLiteral(e.property)?e.property.value:null:R.isIdentifier(e.property)?e.property.name:null;if(!i)return null;let s=await Mr(e.object,t,o);if(!s)return null;if(!R.isObjectExpression(s.node))return{node:null,context:s.context};if(s.node.properties.some(c=>R.isSpreadElement(c)||c.computed))return{node:null,context:s.context};let a=s.node.properties.filter(c=>(R.isObjectMethod(c)||R.isObjectProperty(c))&&(R.isIdentifier(c.key)?c.key.name:R.isStringLiteral(c.key)?c.key.value:null)===i);if(a.length===0)return null;if(a.length!==1)return{node:null,context:s.context};let l=a[0];return R.isObjectMethod(l)?l.kind==="method"?{node:l,context:s.context}:null:R.isObjectProperty(l)&&R.isExpression(l.value)?Mr(l.value,s.context,o):null}return{node:e,context:t}}async function Di(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),Xl(r.expression))return{node:r.expression,context:r.context};if(R.isIdentifier(r.expression))return Di(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 nm(i,t);if(!s)return null;let a=go(s,t,{importDepth:t.importDepth+1}),l=US(i,s);return l?{node:l,context:a}:Di(i.importedName,a)}async function Ho(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=go(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 h of po(d))o.paramSources.delete(h),o.paramArguments.delete(h);let m=R.isAssignmentPattern(d)?d.left:d,g=r?.arguments[f];R.isIdentifier(m)&&R.isExpression(g)&&r&&o.paramArguments.set(m.name,{expression:g,context:r.context});let p=t[f];p&&Ul(d,Yp(p),o)});let a=PD(e,o),l=null,c,u=!1;for(let d of a){let f=go(n.analysis,o);if(R.isObjectExpression(d)){c={...c??{},...await FS(d,f)},l=l??Kl(c,n.file);continue}let m=await yt(d,f);if(m){if(!l){l=m;continue}let g=qp(l,m);if(!g){u=!0,l=null;continue}l=g}}return{returnSource:u?null:l,...c?{objectReturnMap:c}:{}}}function Ul(e,t,n){if(R.isIdentifier(e)){n.paramSources.set(e.name,Ht(t));return}if(R.isAssignmentPattern(e)){Ul(e.left,t,n);return}if(R.isObjectPattern(e))for(let r of e.properties){if(!R.isObjectProperty(r)||r.computed||!R.isIdentifier(r.key))continue;let o=ca(t,[{kind:"property",name:r.key.name}],!0),i=R.isAssignmentPattern(r.value)?r.value.left:r.value;o&&Ul(i,o,n)}}function PD(e,t){if(R.isArrowFunctionExpression(e)&&R.isExpression(e.body))return[e.body];let n=[],r=e.body;if(!R.isBlockStatement(r))return n;let o=i=>{if(R.isFunction(i)&&i!==e)return;if(R.isReturnStatement(i)){i.argument&&R.isExpression(i.argument)&&n.push(i.argument);return}if(R.isIfStatement(i)){let a=Oi(i.test,{file:t.file,imports:new Map([...t.analysis.imports].filter(([l])=>!mo(l,t))),functions:t.analysis.functions});if(a!==void 0){a?o(i.consequent):i.alternate&&o(i.alternate);return}}let s=R.VISITOR_KEYS[i.type];for(let a of s??[]){let l=i[a];if(Array.isArray(l))for(let c of l)R.isNode(c)&&o(c);else R.isNode(l)&&o(l)}};return o(r),n}async function FS(e,t){let n={};for(let r of e.properties){if(!R.isObjectProperty(r))continue;let o=Mi(r);if(!o||!R.isExpression(r.value))continue;let i=await yt(r.value,t);i&&(n[o]=i)}return n}function Mi(e){return R.isIdentifier(e.key)&&!e.computed?e.key.name:R.isStringLiteral(e.key)?e.key.value:null}function ND(e){let t=[],n=e;for(;R.isMemberExpression(n)||R.isOptionalMemberExpression(n);){let r=n.property;n.computed?R.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):R.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):R.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return R.isIdentifier(n),t}function ca(e,t,n){if(t.length===0)return Ht(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?ca(s,t.slice(1),n):null}let i=Ht(e);if(i.sourceType==="cms-field"){let s=t.filter(l=>l.kind==="property").map(l=>l.name);if(s[0]==="data"&&s[1]==="items")return i.valuePath=Li(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=Li(i.valuePath,"data")),i.fieldPath=Li(i.fieldPath,s.slice(a+1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=Li(i.fieldPath,s.join(".")),i):(i.valuePath=Li(i.valuePath,ES(t)),i)}return i.valuePath=Li(i.valuePath,ES(t)),i}function ES(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Li(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function DS(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 fo(e){let t=Ht(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function Yp(e){let t=Ht(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&!t.fieldPath&&(t.cmsFieldRoot=!1),t}function Fi(e){return e?{...Ht(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function SS(e,t){return e?t?qp(e,t):Ht(e):t?Ht(t):null}function qp(e,t){if(Vl(e)!==Vl(t))return null;let n=jS(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Qp(e){let t=new Map;for(let n of e){let r=Vl(n),o=t.get(r);t.set(r,o?qp(o,n):Ht(n))}return[...t.values()]}function Vl(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Vl(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 Kl(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 jl(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Jl(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 MS(e){let t=[...e].sort(BS),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 AD(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 BS(e,t){return IS(e.targetKind)-IS(t.targetKind)||jS(e.confidence,t.confidence)||vS(e.sourceKind)-vS(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function IS(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function vS(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function jS(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function em(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=kS.get(n)?.get(e),i=o?.source===t?o.ast:cD(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=[],l=[];R.traverse(i,{enter(d){switch(R.isFunction(d)&&(s.functionParents.set(d,a.at(-1)??null),a.push(d)),d.type){case"CallExpression":l.push(d);break;case"JSXElement":{let f=d.loc;if(!f)return;let m=Hl({startLine:f.start.line,startColumn:f.start.column,endLine:f.end.line,endColumn:f.end.column});s.jsxElementsByRange.has(m)||s.jsxElementsByRange.set(m,d);break}case"ImportDeclaration":{let f=d.source.value;for(let m of d.specifiers)R.isImportSpecifier(m)&&R.isIdentifier(m.local)?s.imports.set(m.local.name,{source:f,importedName:R.isIdentifier(m.imported)?m.imported.name:m.imported.value,localName:m.local.name,isDefault:!1}):R.isImportDefaultSpecifier(m)&&s.imports.set(m.local.name,{source:f,importedName:"default",localName:m.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),m=f&&(R.isFunctionDeclaration(f)||R.isFunctionExpression(f)||R.isArrowFunctionExpression(f)||R.isObjectMethod(f))?f:null,g=m?s.functionVariables.get(m)??new Map:s.variables;m&&!s.functionVariables.has(m)&&s.functionVariables.set(m,g);for(let[p,h]of $l(d.id,R.isExpression(d.init)?d.init:null))g.set(p,h);if(R.isArrayPattern(d.id)&&R.isCallExpression(d.init)&&Cn(d.init.callee)==="useState"){let[p,h]=d.id.elements;R.isIdentifier(p)&&R.isIdentifier(h)&&s.stateSetters.set(p.name,h.name)}R.isIdentifier(d.id)&&Xl(d.init)&&s.functions.set(d.id.name,d.init);break}case"ExportNamedDeclaration":{let f=d.declaration,m=d.source?.value;if(m)for(let g of d.specifiers){if(!R.isExportSpecifier(g))continue;let p=R.isIdentifier(g.exported)?g.exported.name:g.exported.value,h=g.local.name;s.imports.set(p,{source:m,importedName:h,localName:p,isDefault:h==="default"})}if(R.isFunctionDeclaration(f)&&f.id?.name&&s.functions.set(f.id.name,f),R.isVariableDeclaration(f))for(let g of f.declarations)R.isIdentifier(g.id)&&Xl(g.init)&&s.functions.set(g.id.name,g.init);break}case"ExportDefaultDeclaration":{let f=d.declaration;if((R.isFunctionDeclaration(f)||R.isFunctionExpression(f)||R.isArrowFunctionExpression(f))&&s.functions.set("default",f),R.isIdentifier(f)){let m=s.functions.get(f.name);m&&s.functions.set("default",m)}break}}},exit(d){R.isFunction(d)&&a.pop()}});let c=new Set(s.stateSetters.values()),u=(d,f)=>{let m=s.stateSetterCandidates.get(d)??[];m.push(f),s.stateSetterCandidates.set(d,m)};if(c.size>0)for(let d of l){let f=R.isIdentifier(d.callee)?d.callee.name:null;f&&c.has(f)&&R.isExpression(d.arguments[0])&&u(f,d.arguments[0]);let m=new Set;for(let g of d.arguments)R.isIdentifier(g)&&g.name!==f&&c.has(g.name)&&m.add(g.name);for(let g of m)u(g,d)}return n.set(e,s),s}function $l(e,t){return R.isIdentifier(e)?[[e.name,t]]:R.isAssignmentPattern(e)?$l(e.left,t):R.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!R.isRestElement(n)?$l(n,t?R.memberExpression(t,R.numericLiteral(r),!0):null):[]):R.isObjectPattern(e)?e.properties.flatMap(n=>{if(!R.isObjectProperty(n)||n.computed)return[];let r=Mi(n);return r?$l(n.value,t?R.memberExpression(t,R.stringLiteral(r),!0):null):[]}):[]}function po(e){return!e||R.isVoidPattern(e)?[]:R.isIdentifier(e)?[e.name]:R.isObjectPattern(e)?e.properties.flatMap(t=>R.isObjectProperty(t)?po(t.value):po(t.argument)):R.isArrayPattern(e)?e.elements.flatMap(t=>t?po(R.isRestElement(t)?t.argument:t):[]):R.isAssignmentPattern(e)?po(e.left):R.isRestElement(e)?po(e.argument):[]}function Xl(e){return R.isFunctionExpression(e)||R.isArrowFunctionExpression(e)}function $S(e,t){let n=tm(e,t);return n?e.functionVariables.get(n):void 0}function tm(e,t){return e.functions.get(t)??e.functions.get("default")}async function nm(e,t){let n=await rm(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return em(n,r,t.fileCache)}function US(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function rm(e,t,n){return kt(t)?_o(e,t,n):null}function go(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 TD(e){return e?Ht(e):null}function Ht(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,Ht(n)]))}:{}}}import*as im from"@babel/parser";import om from"@babel/traverse";import*as ye from"@babel/types";import{classifySiteEditPropertyName as wD}from"@vcp-dev/contracts";var sm=typeof om=="function"?om:om.default;function am(e){let t=wD(e.propertyName);if(t.owner!=="generic")return Rn("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return Rn("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return Rn("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return Rn("missing-instance-index","A repeat property target requires an instance index");let r;try{r=im.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(h){return Rn("repeat-not-found",`Unable to parse repeat source: ${h instanceof Error?h.message:String(h)}`)}let o=OD(r,e.element.sourceRange);if(!o)return Rn("repeat-not-found","The selected element is not inside a supported map repeat");if(!ye.isIdentifier(o.callback.params[0]))return Rn("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=LD(r,o.collection,e.file,e.sources);if(!i)return Rn("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:l}=i,c=[],u=[];for(let[h,x]of s.elements.entries()){if(!x||!ye.isObjectExpression(x)||!HS(x))return Rn("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let b=[{kind:"index",index:h}];c.push(b),u.push({kind:"value",root:a.root,path:b})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return Rn("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let f=n.instanceIndex;if(f>=d)return Rn("index-out-of-range",`Selected repeat instance ${f} is outside the source collection`);let m=s.elements[f];if(!m||!ye.isObjectExpression(m))return Rn("unsafe-collection","Selected repeat item is not an object");let g=$D(e.element,e.propertyName),p=BD(m,e.propertyName);return p?{ok:!0,sourceFile:l,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[f],sourceItemIndex:f,sourceItemPath:c[f],collectionIndexMap:Array.from({length:d},(h,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:p,selectedResolution:jD(m,e.propertyName),...g?{property:g}:{},selectionRef:n}:Rn("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function OD(e,t){let n=[];return sm(e,{CallExpression(r){let o=VS(r.node);o&&JS(o.callback,t)&&n.push({...o,span:KS(r.node)})},OptionalCallExpression(r){let o=VS(r.node);o&&JS(o.callback,t)&&n.push({...o,span:KS(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function VS(e){let t=e.callee;if(!ye.isMemberExpression(t)&&!ye.isOptionalMemberExpression(t)||t.computed||!ye.isIdentifier(t.property)||t.property.name!=="map"||!ye.isExpression(t.object))return null;let n=e.arguments[0];return!n||!ye.isExpression(n)||!ye.isArrowFunctionExpression(n)&&!ye.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function LD(e,t,n,r){let o=la(t);if(o&&ye.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:GS(o)}},sourceFile:n};if(!ye.isIdentifier(t))return null;let i=[];if(sm(e,{VariableDeclarator(s){ye.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=la(i[0].init);return!s||!ye.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return FD(e,t.name,n,r)}function FD(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!ye.isImportDeclaration(o))continue;let i=o.specifiers.find(f=>f.local.name===t);if(!i||!ye.isStringLiteral(o.source)||!ye.isImportSpecifier(i))continue;let s=MD(n,o.source.value,r);if(!s)return null;let a=ye.isIdentifier(i.imported)?i.imported.name:i.imported.value,l=r.get(s);if(l===void 0)return null;let c;try{c=im.parse(l,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=DD(c,a),d=u?la(u):null;return!d||!ye.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 sm(e,{VariableDeclarator(r){n||!ye.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!ye.isExpression(r.node.init)||(n=r.node.init)}}),n}function MD(e,t,n){let r=rr(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 la(e){return ye.isParenthesizedExpression(e)?la(e.expression):ye.isTSAsExpression(e)?zS(e.typeAnnotation)?la(e.expression):null:ye.isTSSatisfiesExpression(e)?null:e}function zS(e){return ye.isTSTypeReference(e)&&ye.isIdentifier(e.typeName)&&e.typeName.name==="const"}function HS(e){return e.properties.every(t=>!ye.isObjectProperty(t)||t.computed||!ye.isExpression(t.value)?!1:Yl(t.value))}function Yl(e){if(ye.isTSAsExpression(e)&&zS(e.typeAnnotation))return Yl(e.expression);if(ye.isTSSatisfiesExpression(e))return!1;if(ye.isArrayExpression(e))return e.elements.every(n=>!n||ye.isSpreadElement(n)||!ye.isExpression(n)?!1:Yl(n));if(ye.isObjectExpression(e))return HS(e);let t=cr(e);return t.status==="resolved"||t.status==="undefined"}function BD(e,t){let n=e.properties.filter(o=>ye.isObjectProperty(o)&&WS(o.key)===t);if(n.length>1)return null;let r=n[0];return r?ye.isExpression(r.value)?Yl(r.value)?"static":ye.isIdentifier(r.value)||ye.isMemberExpression(r.value)?"binding":null:null:"missing"}function jD(e,t){let n=e.properties.filter(o=>ye.isObjectProperty(o)&&WS(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!ye.isExpression(r.value)?{status:"undefined"}:cr(r.value)}function $D(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function WS(e){return ye.isIdentifier(e)?e.name:ye.isStringLiteral(e)?e.value:ye.isNumericLiteral(e)?String(e.value):null}function GS(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 KS(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function JS(e,t){let n=GS(e);return XS(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&XS(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function XS(e,t,n,r){return e===n?t-r:e-n}function Rn(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as kM}from"@vcp-dev/contracts";import*as ke from"@babel/types";import ma from"node:path";import*as se from"@babel/types";import*as tI from"@babel/parser";import cm from"@babel/traverse";import*as Ae from"@babel/types";function ql(e,t){let n=[],r=e;for(;Ae.isMemberExpression(r);){if(r.computed)if(Ae.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(Ae.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!Ae.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!Ae.isIdentifier(r)||r.name!==t?null:n}function YS(e){if(Ae.isIdentifier(e))return{base:e.name,path:[]};if(!Ae.isMemberExpression(e))return null;let t=[],n=e;for(;Ae.isMemberExpression(n);){if(n.computed)if(Ae.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ae.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!Ae.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return Ae.isIdentifier(n)?{base:n.name,path:t}:null}function Qt(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n===null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return;n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return;n=n[r.index]}return n}var br=Symbol("not-closed-literal");function Zl(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:br;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return Zl(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||Ae.isSpreadElement(n))return br;let r=Zl(n);if(r===br)return br;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!Ae.isObjectProperty(n)||n.computed||n.shorthand||!Ae.isExpression(n.value))return br;let r=Ae.isIdentifier(n.key)?n.key.name:Ae.isStringLiteral(n.key)?n.key.value:null;if(!r)return br;let o=Zl(n.value);if(o===br)return br;t[r]=o}return t}default:return br}}function ZS(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,l,c,u,d){let f=Zl(i);if(f!==br)return f;if(!Ae.isTemplateLiteral(i)){if(Ae.isTSAsExpression(i)||Ae.isTSSatisfiesExpression(i)||Ae.isTSNonNullExpression(i))return await n(i.expression,s,a,l,c,u,d);if(Ae.isIdentifier(i)){let m=s.getBinding(i.name);if(!m)return;let g=await t({currentFile:a,binding:m,readFile:l,exists:c,fileCache:u,visited:d});return g?.kind==="static"?g.value:void 0}if(Ae.isArrayExpression(i)){let m=[];for(let g of i.elements){if(!g||Ae.isSpreadElement(g))return;let p=await r(g,s,a,l,c,u,d);if(p===void 0)return;m.push(p)}return m}if(Ae.isObjectExpression(i)){let m={};for(let g of i.properties){if(!Ae.isObjectProperty(g)||g.computed)return;let p=null;if(Ae.isIdentifier(g.key)?p=g.key.name:Ae.isStringLiteral(g.key)&&(p=g.key.value),!p)return;if(g.shorthand){if(!Ae.isIdentifier(g.value))return;let x=await r(g.value,s,a,l,c,u,d);if(x===void 0)return;m[p]=x;continue}if(!Ae.isExpression(g.value))return;let h=await r(g.value,s,a,l,c,u,d);h!==void 0&&(m[p]=h)}return m}if(Ae.isMemberExpression(i)){let m=await o(i,s,a,l,c,u,d);if(!m)return;let g=s.getBinding(m.base);if(!g)return;let p=await t({currentFile:a,binding:g,readFile:l,exists:c,fileCache:u,visited:d});return!p||p.kind!=="static"?void 0:Qt(p.value,m.path)}}}async function r(i,s,a,l,c,u,d){if(!Ae.isSpreadElement(i))return await n(i,s,a,l,c,u,d)}async function o(i,s,a,l,c,u,d){if(Ae.isIdentifier(i))return{base:i.name,path:[]};if(!Ae.isMemberExpression(i))return null;let f=[],m=i;for(;Ae.isMemberExpression(m);){if(m.computed){let g=m.property;if(Ae.isNumericLiteral(g))f.unshift({kind:"index",index:g.value});else if(Ae.isStringLiteral(g))f.unshift({kind:"property",name:g.value});else{let p=Ae.isExpression(g)?await n(g,s,a,l,c,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(!Ae.isIdentifier(m.property))return null;f.unshift({kind:"property",name:m.property.name})}m=m.object}return Ae.isIdentifier(m)?{base:m.name,path:f}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var nI=typeof cm=="function"?cm:cm.default,qS=new WeakMap;function rI(e){try{return tI.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Ql(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=rI(n);return e.set(t,{source:n,ast:o}),o}function eu(e,t){return lm(ua(e).expressionRanges,t,!1)}function oI(e,t){return ua(e).exactExpressions.get(iI(t))??null}function tu(e,t){return lm(ua(e).jsxRanges,t,!0)}function ua(e){let t=qS.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return nI(e,{Expression(r){let o=r;n.expressions.push(o);let i=QS(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=iI(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=QS(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(eI),n.jsxRanges.sort(eI),qS.set(e,n),n}function QS(e,t){let n=da(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function iI(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function eI(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function lm(e,t,n,r){let o=0,i=e.length;for(;o<i;){let l=o+Math.floor((i-o)/2),c=e[l].range;c.startLine<t.startLine||c.startLine===t.startLine&&c.startColumn<t.startColumn?o=l+1:i=l}let s=null,a=n?1/0:-1;for(let l=o;l<e.length;l++){let c=e[l],u=c.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(c.path))continue;((n?c.span<a:c.span>a)||c.span===a&&(!s||c.traversalIndex>s.traversalIndex))&&(s=c,a=c.span)}return s?.path??null}function da(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 Bi(e,t){if(t)return um(e,t);let n=YS(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function um(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function fa(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of ua(e).expressions){if(um(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function sI(e,t,n,r){return lm(ua(e).expressionRanges,r,!0,o=>um(o.node,t)===n)}function ji(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function pa(e){let t=null;if(nI(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function qn(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=rI(o),s={source:o,ast:i};return n.set(e,s),s}function UD(e){return se.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:se.isMemberExpression(e.callee)&&se.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function VD(e){if(!se.isNewExpression(e)||!se.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!se.isIdentifier(e.arguments[0])||!se.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!se.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!se.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(se.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(se.isIfStatement(i)&&se.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=se.isIfStatement(i)?i.test:null,l=a&&se.isLogicalExpression(a,{operator:"&&"})?a.right:null,c=se.isIfStatement(i)?se.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=se.isReturnStatement(s)?s.argument:null;return!a||!se.isLogicalExpression(a,{operator:"&&"})||!se.isBinaryExpression(a.left,{operator:"==="})||!se.isUnaryExpression(a.left.left,{operator:"typeof"})||!se.isIdentifier(a.left.left.argument,{name:r.name})||!se.isStringLiteral(a.left.right,{value:"string"})||!se.isUnaryExpression(l,{operator:"!"})||!se.isBinaryExpression(l.argument,{operator:"in"})||!se.isIdentifier(l.argument.left,{name:r.name})||!se.isIdentifier(l.argument.right,{name:n.name})||!se.isReturnStatement(c)||!se.isIfStatement(i)||i.alternate||!se.isCallExpression(u)||!se.isMemberExpression(u.callee)||!se.isIdentifier(u.callee.object,{name:"Reflect"})||!se.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!se.isIdentifier(u.arguments[0],{name:n.name})||!se.isIdentifier(u.arguments[1],{name:r.name})||!se.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function KD(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()||!se.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 aI(e,t){let n=KD(e.path);if(!n)return null;let r=ki(e,t);return r?{...n,...r}:null}function cI(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function dm(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 fm(e,t){for(let n of e.program.body){if(t==="default"&&se.isExportDefaultDeclaration(n))return se.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(se.isFunctionDeclaration(n.declaration)||se.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(se.isExportNamedDeclaration(n)){if(n.declaration){if(se.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(se.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((se.isFunctionDeclaration(n.declaration)||se.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((se.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&se.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 lI(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(p){let{currentFile:h,binding:x,readFile:b,exists:E,fileCache:S,visited:v}=p,A=`${h}::${x.kind}::${x.identifier.name}`;if(v.has(A))return null;v.add(A);try{let I=await a({currentFile:h,binding:x,readFile:b,exists:E,fileCache:S,visited:v});if(I)return I;if(x.path.isImportSpecifier()||x.path.isImportDefaultSpecifier())return await m({currentFile:h,binding:x,readFile:b,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,fileCache:S,visited:v});if(x.kind==="param")return null;if(x.path.isVariableDeclarator()){let _=x.path.node.init;if(!_||!se.isExpression(_))return null;let k=VD(_);if(k&&!x.path.scope.getBinding("Proxy")&&!x.path.scope.getBinding("Reflect")){let $=x.path.scope.getBinding(k),J=$?await s({...p,binding:$}):null;if(J?.kind==="static"&&J.value!==null&&!Array.isArray(J.value)&&typeof J.value=="object")return J}let T=x.path.get("init");if(T&&!Array.isArray(T)&&T.isExpression()){let $=await t({currentFile:h,expressionPath:T,readFile:b,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v});if($)return $;if(T.isCallExpression()){let J=await n({currentFile:h,callPath:T,readFile:b,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v});if(J)return J}}let L=await r(_,x.path.scope,h,b,E,S,v);return L===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:x.identifier.name},value:L,sourceKind:"binding"}}if(x.path.isIdentifier()&&x.path.parentPath?.isExportDefaultDeclaration()){let _=x.path.parentPath.node.declaration;if(!se.isExpression(_))return null;let k=await r(_,x.path.scope,h,b,E,S,v);return k===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:x.identifier.name},value:k,sourceKind:"binding"}}return null}finally{v.delete(A)}}async function a(p){let{currentFile:h,binding:x,readFile:b,exists:E,fileCache:S,visited:v}=p;if(!x.path.isVariableDeclarator()||!x.path.get("id").isArrayPattern())return null;let A=x.path,I=A.node.init;if(!I||!se.isCallExpression(I))return null;let _=UD(I);if(!_||!se.isArrayPattern(A.node.id)||A.node.id.elements.findIndex(J=>se.isIdentifier(J)&&J.name===x.identifier.name)!==0)return null;let T=_==="useReducer"?1:0,L=I.arguments[T];if(!L||!se.isExpression(L))return null;let $=await r(L,A.scope,h,b,E,S,v);return $===void 0?null:{kind:"static",file:h,root:{kind:"hook-state",name:x.identifier.name,hook:_},value:$,sourceKind:"binding"}}async function l(p){let h=p.expressionPath.scope.getBinding(p.sourceInfo.base);if(!h||!h.constant||h.kind!=="param"||!p.graph)return null;let x=aI(h,p.sourceInfo);if(!x)return null;let b=[...p.graph.elements.values()].filter(S=>cI(S,p.currentFile,x.componentName,x.exportName));if(!b.length)return null;let E=[];for(let S of b){if(S.sourceFile!==b[0].sourceFile||S.componentName!==b[0].componentName||S.attributeSpreads?.length)return null;let v=await qn(S.sourceFile,p.readFile,p.fileCache),A=v.ast?tu(v.ast,S.sourceRange):null;if(!A)return null;let I=A.parentPath;for(;I&&!I.isFunction();){if(I.isJSXElement()){let z=I.node.openingElement.name;if(!se.isJSXIdentifier(z)||!/^[a-z]/.test(z.name))return null}else if(!I.isJSXFragment()&&!I.isReturnStatement()&&!I.isBlockStatement())return null;I=I.parentPath}if(!I)return null;let _=A.get("openingElement").get("attributes").filter(z=>z.isJSXAttribute()&&se.isJSXIdentifier(z.node.name,{name:x.propName}));if(_.length!==1)return null;let k=_[0];if(!k?.isJSXAttribute())return null;let T=k.get("value"),L=T.isJSXExpressionContainer()?T.get("expression"):T;if(!L.isExpression())return null;let $=await r(L.node,L.scope,S.sourceFile,p.readFile,p.exists,p.fileCache,p.visited),J=$===void 0?void 0:Qt($,x.remainingPath);if(J===void 0)return null;E.push(J)}return E}async function c(p){let h=aI(p.binding,p.sourceInfo);if(!h||!p.graph)return null;let x=["component-prop",p.currentFile,p.binding.identifier.start??p.binding.path.node.start??-1,h.componentName,h.propName].join(":");if(p.visited.has(x))return null;p.visited.add(x);try{return await u(p,h,p.graph)}finally{p.visited.delete(x)}}async function u(p,h,x){let b=[...x.elements.values()].filter(k=>cI(k,p.currentFile,h.componentName,h.exportName));if(b.length!==1)return null;let E=b[0],S=E.attributes?.find(k=>k.name===h.propName);if(S&&!S.source){let k=await d({caller:E,propName:h.propName,remainingPath:h.remainingPath,readFile:p.readFile,fileCache:p.fileCache});if(k)return dm(k,{componentName:h.componentName,propName:h.propName,file:E.sourceFile})}if(!S?.source){let k=await f({caller:E,propName:h.propName,remainingPath:h.remainingPath,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(k)return dm(k,{componentName:h.componentName,propName:h.propName,file:E.sourceFile});let T=cE(p.binding,h.componentName,h.propName);if(!T||T.propName!==h.propName)return null;let L=await r(T.expressionPath.node,T.expressionPath.scope,p.currentFile,p.readFile,p.exists,p.fileCache,p.visited);if(L===void 0)return null;let $=h.remainingPath;return $.length>0&&Qt(L,$)===void 0?null:{kind:"value",file:p.currentFile,root:{kind:"binding",name:h.propName},path:$,sourceKind:"binding",semanticKind:"component-prop",displayExpression:T.displayPath,chainPrefix:[{kind:"component-prop",file:p.currentFile,displayName:T.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let v=await qn(E.sourceFile,p.readFile,p.fileCache);if(!v.ast)return null;let A=sI(v.ast,v.source,S.source.expression,S.sourceRange)??fa(v.ast,v.source,S.source.expression);if(!A)return null;let I={...S.source,expression:ji(S.source.expression,h.remainingPath),path:[...S.source.path,...h.remainingPath]},_=await o({currentFile:E.sourceFile,expressionPath:A,sourceInfo:I,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 _?dm(_.kind==="external"?_:{..._,displayExpression:I.expression},{componentName:h.componentName,propName:h.propName,file:E.sourceFile}):null}async function d(p){let h=await qn(p.caller.sourceFile,p.readFile,p.fileCache);if(!h.ast)return null;let x=tu(h.ast,p.caller.sourceRange);if(!x)return null;let b=x.get("openingElement").get("attributes").find(A=>A.isJSXAttribute()&&A.node.name.type==="JSXIdentifier"&&A.node.name.name===p.propName);if(!b?.isJSXAttribute())return null;let E=b.get("value"),S=E.isStringLiteral()?E:E.isJSXExpressionContainer()?E.get("expression"):null;if(!S?.isExpression())return null;let v=da(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 h=await qn(p.caller.sourceFile,p.readFile,p.fileCache);if(!h.ast)return null;let x=tu(h.ast,p.caller.sourceRange);if(!x)return null;let b=x.get("openingElement");for(let E of b.get("attributes")){if(!E.isJSXSpreadAttribute())continue;let S=E.get("argument");if(!S.isExpression())continue;let v=await i({expression:S.node,scope:S.scope,source:h.source,currentFile:p.caller.sourceFile,readFile:p.readFile,exists:p.exists,fileCache:p.fileCache,visited:p.visited});if(!v)continue;let A=[{kind:"property",name:p.propName},...p.remainingPath],I={...v,expression:ji(v.expression,A),path:[...v.path,...A]},_=await o({currentFile:p.caller.sourceFile,expressionPath:S,sourceInfo:I,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(_)return _.kind==="external"?_:{..._,displayExpression:I.expression}}return null}async function m(p){let{currentFile:h,binding:x,readFile:b,exists:E,fileCache:S,visited:v}=p,A=x.path.parentPath;if(!A||!A.isImportDeclaration())return null;let I=A.node.source.value;if(typeof I!="string")return null;let _=await _o(h,I,E);if(!_)return null;if(x.path.isImportDefaultSpecifier()){let z=await qn(_,b,S),Z=z.ast?fm(z.ast,"default"):null,W=await g({file:_,exportName:"default",readFile:b,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v});return!W||W.kind!=="static"?null:{kind:"static",file:Z?.kind==="default-expression"?W.file:_,root:Z?.kind==="default-expression"?W.root:{kind:"default-export"},value:W.value,sourceKind:"imported-binding"}}if(!x.path.isImportSpecifier())return null;let k=x.path.node.imported,T=se.isIdentifier(k)?k.name:k.value,L=await qn(_,b,S),$=L.ast?fm(L.ast,T):null,J=await g({file:_,exportName:T,readFile:b,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v});return J?J.kind==="external"?J:{kind:"static",file:$?.kind==="re-export"?J.file:_,root:$?.kind==="re-export"||J.root.kind==="binding"&&J.root.name!==$?.name?J.root:{kind:"named-export",name:T},value:J.value,sourceKind:"imported-binding"}:null}async function g(p){let{file:h,exportName:x,readFile:b,exists:E,fileCache:S,visited:v}=p,A=`export::${h}::${x}`;if(!v.has(A)){v.add(A);try{let I=await qn(h,b,S);if(!I.ast)return;let _=fm(I.ast,x);if(!_)return;if(_.kind==="default-expression"){let $=_.expression;if(!$||!se.isIdentifier($))return;let J=pa(I.ast).getBinding($.name);return J?await s({currentFile:h,binding:J,readFile:b,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v})??void 0:void 0}if(_.kind==="re-export"){if(!_.source||!_.name)return;let $=await _o(h,_.source,E);return $?g({...p,file:$,exportName:_.name}):void 0}let k=_.name;if(!k)return;let T=pa(I.ast).getBinding(k);return T?await s({currentFile:h,binding:T,readFile:b,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v})??void 0:void 0}finally{v.delete(A)}}}return{resolveExportValue:g,resolveComponentPropBinding:c,resolveComponentPropValues:l,resolveBindingTarget:s}}import*as ge from"@babel/types";function mm(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=Yn(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!JD(s,r)?null:{callPath:s,basePath:i}}function JD(e,t){let n=e.node.callee;return!ge.isMemberExpression(n)||!ge.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function pI(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:El(r,t)}function uI(e,t){return e?ge.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function dI(e,t,n,r,o){let i=ge.isExpression(e.body)?e.body:e.body.body.find(a=>ge.isReturnStatement(a))?.argument;if(!i||!ge.isExpression(i))return;let s=pm(i,t,n,r,o);return typeof s=="number"?s:void 0}function pm(e,t,n,r,o){if(ge.isNumericLiteral(e)||ge.isStringLiteral(e)||ge.isBooleanLiteral(e))return e.value;if(ge.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(ge.isMemberExpression(e)){let i=ql(e,t);if(i)return Qt(r,i);let s=ql(e,n);return s?Qt(o,s):void 0}if(ge.isBinaryExpression(e)&&e.operator==="-"){let i=ge.isExpression(e.left)?pm(e.left,t,n,r,o):void 0,s=ge.isExpression(e.right)?pm(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function XD(e){if(ge.isExpression(e.body))return e.body;for(let t of e.body.body)if(ge.isReturnStatement(t)&&t.argument&&ge.isExpression(t.argument))return t.argument;return null}function zD(e,t,n){let r=Go(e,t,n);return typeof r=="boolean"?r:void 0}function Go(e,t,n){if(ge.isStringLiteral(e)||ge.isNumericLiteral(e)||ge.isBooleanLiteral(e))return e.value;if(ge.isNullLiteral(e))return null;if(ge.isIdentifier(e))return e.name===t?n:void 0;if(ge.isMemberExpression(e)){let r=ql(e,t);return r?Qt(n,r):void 0}if(ge.isUnaryExpression(e)&&e.operator==="!"){let r=Go(e.argument,t,n);return r===void 0?void 0:!r}if(ge.isLogicalExpression(e)){let r=Go(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&Go(e.right,t,n);if(e.operator==="||")return r||Go(e.right,t,n)}if(ge.isBinaryExpression(e)){let r=ge.isExpression(e.left)?Go(e.left,t,n):void 0,o=ge.isExpression(e.right)?Go(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 mI(e){let t=[],n=e;for(;ge.isMemberExpression(n)||ge.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(ge.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(ge.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(ge.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(ge.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return ge.isIdentifier(n)?{base:n.name,segments:t}:null}function gI(e){return e.some(t=>t.kind==="dynamic")}function fI(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function hI(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 HD(e,t){let n=[],r=[];for(let o of t){let i=Qt(e,o);if(!Array.isArray(i))return null;for(let[s,a]of i.entries())n.push(a),r.push([...o,{kind:"index",index:s}])}return{value:n,collectionPathMap:r}}function yI(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(g){let{currentFile:p,callPath:h,readFile:x,exists:b,fileCache:E,visited:S}=g,v=h.node.callee;if(!ge.isMemberExpression(v)||!ge.isIdentifier(v.property)||v.property.name!=="map")return null;let A=h.get("callee");if(!A.isMemberExpression())return null;let I=A.get("object");if(Array.isArray(I)||!I.isExpression())return null;let _=await a({currentFile:p,expressionPath:I,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:E,visited:S});return!_||!Array.isArray(_.value)||_.value.length===0?null:_}async function a(g){let{currentFile:p,expressionPath:h,readFile:x,exists:b,fileCache:E,visited:S}=g;if(h.isIdentifier()){let v=h.scope.getBinding(h.node.name);if(!v)return null;let A=await t({currentFile:p,binding:v,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:E,visited:S});return A?.kind==="static"?A:null}if(h.isCallExpression())return c({currentFile:p,callPath:h,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:E,visited:S});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let v=h.get("expression");if(!Array.isArray(v)&&v.isExpression())return a({...g,expressionPath:v})}if(h.isArrayExpression()){let v=da(h.node);if(!v)return null;let A=await n(h.node,h.scope,p,x,b,E,S);return Array.isArray(A)?{kind:"static",file:p,root:{kind:"expression",sourceRange:v},value:A,sourceKind:"binding"}:null}if(h.isMemberExpression()){let v=await r({expression:h.node,scope:h.scope,currentFile:p,readFile:x,exists:b,fileCache:E,visited:S});if(!v)return null;let A=await o({currentFile:p,expressionPath:h,sourceInfo:v,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:E,visited:S});if(!A||A.kind==="external")return null;let I=await l({currentFile:p,expressionPath:h,provenance:A,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:E,visited:S});if(!I||I.kind!=="static")return null;if(A.collectionPathMap?.length){let k=HD(I.value,A.collectionPathMap);if(k)return{kind:"static",file:A.file,root:A.root,value:k.value,sourceKind:A.sourceKind,collectionPathMap:k.collectionPathMap}}let _=Qt(I.value,A.path);return Array.isArray(_)?{kind:"static",file:A.file,root:A.root,value:_,sourceKind:A.sourceKind,pathPrefix:A.path,collectionIndexMap:A.collectionIndexMap,collectionPathMap:A.collectionPathMap}:null}return null}async function l(g){let{provenance:p}=g;if(p.root.kind==="binding"){let E=g.expressionPath.scope.getBinding(p.root.name);if(!E&&p.file!==g.currentFile){let S=await qn(p.file,g.readFile,g.fileCache);E=S.ast?pa(S.ast).getBinding(p.root.name):void 0}return E?await t({currentFile:p.file,binding:E,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited}):null}if(p.root.kind!=="expression")return null;let h=await qn(p.file,g.readFile,g.fileCache);if(!h.ast)return null;let x=oI(h.ast,p.root.sourceRange);if(!x)return null;let b=await n(x.node,x.scope,p.file,g.readFile,g.exists,g.fileCache,g.visited);return b===void 0?null:{kind:"static",file:p.file,root:p.root,value:b,sourceKind:p.sourceKind}}async function c(g){return await u(g)??await d(g)??await f(g)}async function u(g){let{callPath:p}=g,h=p.node.callee;if(!ge.isMemberExpression(h)||!ge.isIdentifier(h.property)||h.property.name!=="filter")return null;let x=p.get("callee");if(!x.isMemberExpression())return null;let b=x.get("object");if(Array.isArray(b)||!b.isExpression())return null;let E=await a({currentFile:g.currentFile,expressionPath:b,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited});if(!E||!Array.isArray(E.value))return null;let[S]=p.node.arguments;if(!ge.isArrowFunctionExpression(S)&&!ge.isFunctionExpression(S))return null;let v=S.params[0];if(!ge.isIdentifier(v))return null;let A=XD(S);if(!A)return null;let I=[],_=[],k=[];for(let[T,L]of E.value.entries()){let $=zD(A,v.name,L);if(typeof $!="boolean")return null;if($){I.push(L),_.push(E.collectionIndexMap?.[T]??T);let J=E.collectionPathMap?.[T];J&&k.push(J)}}return{...E,value:I,pathPrefix:E.pathPrefix,collectionIndexMap:_,...k.length>0?{collectionPathMap:k}:{}}}async function d(g){let{callPath:p}=g,h=p.node.callee;if(!ge.isMemberExpression(h)||!ge.isIdentifier(h.property)||h.property.name!=="slice")return null;let x=p.get("callee");if(!x.isMemberExpression())return null;let b=x.get("object");if(Array.isArray(b)||!b.isExpression())return null;let E=await a({currentFile:g.currentFile,expressionPath:b,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited});if(!E||!Array.isArray(E.value))return null;let[S,v]=p.node.arguments,A=uI(S,0),I=uI(v,E.value.length);if(A===null||I===null)return null;let _=Math.max(0,A<0?E.value.length+A:A),k=Math.max(0,I<0?E.value.length+I:I),T=E.value.map(($,J)=>E.collectionIndexMap?.[J]??J).slice(_,k),L=E.collectionPathMap?.slice(_,k);return{...E,value:E.value.slice(_,k),pathPrefix:E.pathPrefix,collectionIndexMap:T,...L?{collectionPathMap:L}:{}}}async function f(g){let{callPath:p}=g,h=p.node.callee;if(!ge.isMemberExpression(h)||!ge.isIdentifier(h.property)||h.property.name!=="sort"&&h.property.name!=="toSorted")return null;let x=p.get("callee");if(!x.isMemberExpression())return null;let b=x.get("object");if(Array.isArray(b)||!b.isExpression())return null;let E=await a({currentFile:g.currentFile,expressionPath:b,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited});if(!E||!Array.isArray(E.value))return null;let[S]=p.node.arguments;if(!ge.isArrowFunctionExpression(S)&&!ge.isFunctionExpression(S))return null;let[v,A]=S.params;if(!ge.isIdentifier(v)||!ge.isIdentifier(A))return null;let I=E.value.map((k,T)=>({value:k,sourceIndex:E.collectionIndexMap?.[T]??T,originalIndex:T})),_=[...I];for(let k of I)for(let T of I)if(dI(S,v.name,A.name,k.value,T.value)===void 0)return null;return _.sort((k,T)=>{let L=dI(S,v.name,A.name,k.value,T.value)??0;return L===0?k.originalIndex-T.originalIndex:L}),{...E,value:_.map(k=>k.value),pathPrefix:E.pathPrefix,collectionIndexMap:_.map(k=>k.sourceIndex),...E.collectionPathMap?{collectionPathMap:_.map(k=>E.collectionPathMap?.[k.originalIndex]).filter(k=>!!k)}:{}}}async function m(g){let p=null,h=!1,x,b=[];for(let S of g.segments){if(S.kind!=="dynamic")continue;let v=await r({expression:S.expression,scope:g.expressionPath.scope,source:g.fileCache.get(g.currentFile)?.source,currentFile:g.currentFile,readFile:g.readFile,exists:g.exists,fileCache:g.fileCache,visited:g.visited});if(!v)return null;let A=mm(g.expressionPath,v.base),I;if(A){h=!0;let _=await s({currentFile:g.currentFile,callPath:A.callPath,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited});if(!_||!Array.isArray(_.value))return null;I=_.value.map((k,T)=>{let L=Qt(_.value,[{kind:"index",index:T},...A.basePath,...v.path]);return fI(L)}),x??=_.collectionIndexMap}else{let _=await i({...g,sourceInfo:v});if(!_)return null;I=_.map(fI)}if(I.some(_=>_===null)||p!==null&&p!==I.length)return null;p=I.length,b.push(I)}if(p===null||p===0)return null;let E=[];for(let S=0;S<p;S+=1){let v=[...g.rootPath],A=0;for(let I of g.segments){if(I.kind==="dynamic"){let _=b[A]?.[S];if(!_)return null;v.push(_),A+=1;continue}v.push({...I})}E.push(v)}return{sourceKind:h||p>1?"repeat-template":"binding",...x?{collectionIndexMap:x}:{},collectionPathMap:E}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:WD,evaluateStaticExpression:nu}=ZS({resolveBindingTarget:e=>ru(e)}),{resolveRepeatCollectionTarget:GD,resolveCollectionCallTarget:YD,resolveDynamicMemberPathMap:ZD}=yI({resolveBindingTarget:e=>ru(e),evaluateStaticExpression:nu,buildExpressionSourceInfo:Er,resolveSourceInfoProvenance:Vn,resolveComponentPropValues:e=>eM(e)}),{resolveExportValue:qD,resolveComponentPropBinding:QD,resolveComponentPropValues:eM,resolveBindingTarget:ru}=lI({resolveExternalExpression:Sm,resolveCollectionCallTarget:YD,evaluateStaticExpression:nu,resolveSourceInfoProvenance:Vn,buildExpressionSourceInfo:Er});function CI(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var xI=new WeakMap;function tM(e){let t=xI.get(e);return t||(t=new WeakMap,xI.set(e,t)),t}function bI(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 RI(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Ql(s,t,n);if(!a)return null;let l=eu(a,r.sourceRange);if(!l)return null;let c=await Er({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!c){let f=await _m({currentFile:t,expressionPath:l,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});return f?ym(f,Bi(l.node,n)):null}let u=new Set,d=await vM({currentFile:t,expressionPath:l,segment:{...r,source:c},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:u});return d?ym(d,c.expression):null}async function $i(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Ql(i,t,n);if(!s)return null;let a=e.sourceRange?eu(s,e.sourceRange):e.expression!==void 0?fa(s,n,e.expression):null;if(!a)return null;let l=ou(a);if(!l.isIdentifier()&&!l.isMemberExpression())return null;let c=new Set,u=await Er({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:c}),d=u?await Vn({currentFile:t,expressionPath:l,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:c}):await FI({currentFile:t,expressionPath:l,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:c});return ym(d,e.expression??Bi(l.node,n))}async function Em(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Ql(i,t,n);if(!s)return Pn("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?nM({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}):rM({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function Er(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 WD(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:Bi(e.expression,e.source),base:t.base,path:t.path}:null}function ym(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 nM(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:l}=e,c=eu(r,o.sourceRange),u=c?await Er({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:l}):null;if(!u){if(!c||c.isStringLiteral()||c.isTemplateLiteral()&&c.node.expressions.length===0)return EI(t,o.value);let f=await _m({currentFile:t,expressionPath:c,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});return f?f.kind==="external"?_I(t,f):bm(t,Bi(c.node,n),f):oM({expression:c.node,scope:c.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:l,functionCallContracts:e.functionCallContracts})}if(!c)return Pn("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await Vn({currentFile:t,expressionPath:c,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});if(!d){let f=xm(c.node);if(f)return Pn(f.code,f.message);let m=c.scope.getBinding(u.base);if(m?.path.isVariableDeclarator()){let g=xm(m.path.node.init);if(g)return Pn(g.code,g.message)}return m?.path.isVariableDeclarator()&&ke.isCallExpression(m.path.node.init)?iM("unsupported-expression",wI(m.path.node.init,e.functionCallContracts)):Pn("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?_I(t,d):bm(t,u.expression,d)}async function rM(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:l}=e;if(!o.conditionSource)return Pn("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let c=fa(r,n,o.conditionExpression);if(!c)return Pn("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await Vn({currentFile:t,expressionPath:c,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});if(!u)return Pn("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Pn("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=bm(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 EI(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 oM(e){let t=await NI(e);if(t.length===0)return Pn("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(sM(e.expression))return PI(t);if(TI(e.expression))return Pn("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 Pn("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Pn(n.code,n.message)}function Pn(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function iM(e,t){return PI([{code:e,message:t}])}function PI(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function sM(e){return ke.isCallExpression(e)||ke.isConditionalExpression(e)||ke.isLogicalExpression(e)||ke.isBinaryExpression(e)}function ga(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 NI(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:l}=e,c=xm(t);if(c)return[c];if(ke.isCallExpression(t))return[{code:"unsupported-expression",message:wI(t,l)}];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 f=await nu(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 ke.isBinaryExpression(t)?ga([...await gm(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)?ga([...await gm(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)?ga([...await gm(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 xm(e){return TI(e)?SI("i18n helpers require a static message id string"):dM(e)?SI("CMS helpers require static entry id and field path string arguments"):null}async function gm(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await NI({...t,expression:o}));return r}function aM(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:[cM(e.sourceType)]}}async function Sm(e){for(let n of gM){if(!II(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return kI(vI(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(!II(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return kI(vI(r),e.externalAdapters)}return null}function cM(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function lM(e){return{code:"external-source-readonly",message:e}}function SI(e){return{code:"unsupported-expression",message:e}}function Im(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 II(e,t){if(!t||t.length===0)return!0;let n=Im(e.node);return n?t.includes(n):!1}function vI(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:ga(e.diagnostics??[])}:{match:e,diagnostics:[]}}function kI(e,t){let n=aM(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:ga([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function uM(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 dM(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 AI(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 TI(e){return AI(e)===null}async function fM(e,t,n){let r=new Set,o=ma.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=ma.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"]:[ma.posix.join(i,"locales"),ma.posix.join(i,"messages")];for(let a of s){let l=ma.posix.join(a,`${t}.json`);if(await n(l))return l}}return null}async function pM(e){let t=AI(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await fM(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function mM(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 nu(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:[lM("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var gM=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>uM(e)},{helperNames:["apiField"],resolve:e=>mM(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>pM({currentFile:e,expressionPath:t,exists:n})}];function vm(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function _I(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 bm(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(c=>c.kind==="index"),i=IM(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,l=[...n.chainPrefix??[]];return n.sourceKind==="binding"?l.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:n.editMode!=="readonly"}):n.sourceKind==="imported-binding"?l.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"&&l.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:n.editMode!=="readonly"}),n.path.length>0&&n.sourceKind!=="repeat-template"&&l.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:n.editMode!=="readonly"}),i&&l.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"?l.map(c=>({...c,canEditHere:!1})):l,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var hM=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function km(e,t){let n=[...hM,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function wI(e,t){let n=e.callee;return ke.isIdentifier(n)&&km(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 _m(e){let t=await Sm(e);if(t)return t;let n=await OI({...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 Er({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 Vn({...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 EM(e)}async function OI(e){let t=await Qn({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=ou(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:vm(t.provenance)}async function Qn(e){let t=ou(e.expressionPath),n=bM(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 Er({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 Vn({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 Er({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 Vn({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}),l=await Qn({...e,expressionPath:i,allowComposed:!1});return hm(s,a,l)}if(t.isCallExpression())return yM({...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 hm(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 hm(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 ou(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 yM(e){let t=Im(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 hm(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!xM(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function xM(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 bM(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function EM(e){if(!e.expressionPath.isCallExpression())return null;let t=Im(e.expressionPath.node);if(!t)return null;let n=km(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 LI({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?vm(i):null}async function LI(e){let t=await Sm({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 Er({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 Vn({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 _m({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 SM(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=km(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 LI({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?vm(a):null}function IM(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=ji(t,e.path);return{sourceId:o,displayPath:o}}async function vM(e){let t=e.segment.source;return t?Vn({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 Vn(e){let t=e.sourceInfo,n=mm(e.expressionPath,t.base);if(n){let c=await GD({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(!c){let p=pI(n.callPath,[...n.basePath,...t.path]);return qs(p)?bI(e.currentFile,p.sourceId,p.displayPath):null}let u=hI(c,[...n.basePath,...t.path]),d=c.collectionIndexMap?.[0]??0,f=[...c.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],m=[{kind:"index",index:0},...n.basePath,...t.path];return Qt(c.value,m)===void 0?null:{kind:"value",file:c.file,root:c.root,path:u?.[0]??f,sourceKind:"repeat-template",collectionIndexMap:c.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let c=t.path[0],u=r.path.parentPath;if(!c||c.kind!=="property"||!u?.isImportDeclaration())return null;let d=await _o(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let f=await qD({file:d,exportName:c.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 m=t.path.slice(1);return Qt(f.value,m)===void 0?null:{kind:"value",file:f.file,root:f.root,path:m,sourceKind:"imported-binding",collectionIndexMap:f.collectionIndexMap}}let o=sE(r);if(o){let c=o.expressionPath,u=await Er({expression:c.node,scope:c.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let d=await Vn({...e,expressionPath:c,sourceInfo:{...u,expression:ji(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}else if(r.constant){let d=`dynamic-alias:${e.currentFile}:${c.node.start}`;if(e.visited.has(d))return null;e.visited.add(d);try{let f=await FI({...e,expressionPath:ou(c),memberSuffix:t.path});if(f?.kind==="value")return f}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await OI({currentFile:e.currentFile,expressionPath:c,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 QD({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 SM({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=xl(r,t.path,tM(e.fileCache));if(qs(s))return bI(e.currentFile,s.sourceId,s.displayPath);let a=await ru({currentFile:e.currentFile,binding:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return a?a.kind==="external"?t.path.length===0?a:null:Qt(a.value,t.path)===void 0?null:{kind:"value",file:a.file,root:a.root,path:t.path,sourceKind:a.sourceKind,collectionIndexMap:a.collectionIndexMap}:null}async function FI(e){let t=mI(e.expressionPath.node);if(!t||!gI(t.segments))return null;let n=await Vn({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 ZD({...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 ru({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>Qt(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:Bi(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function DI(e){let t=kM(e.propertyName);if(t.owner==="blocked")return ho(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return ho(t.owner,{code:"owner-delegated",message:`Property '${e.propertyName}' is owned by ${t.owner}`});let n=e.element.attributes?.filter(c=>c.name===e.propertyName)??[];if(n.length>1)return ho("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 c of i)o.push({kind:"spread",order:c.order,spread:c,target:await CM(e,c)});o.sort((c,u)=>c.order-u.order);let s=o.at(-1);if(!s)return{status:"missing",owner:"generic"};if(o.filter(c=>c.kind==="spread"&&c.order>s.order).some(c=>!c.target))return ho("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}:ho("generic",{code:"ambiguous-property-source",message:`The final spread source for '${e.propertyName}' is not provably writable`});let l=o.filter(c=>c.kind==="spread"&&c.order<s.order);return e.operation==="remove"&&l.length>0?ho("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):_M(e,s.attribute)}async function _M(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await $i({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}}:ho("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 $i({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"?ho("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 CM(e,t){let n=t.source?.expression;if(!n)return;let r=await $i({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:RM(r,e.propertyName)}}function RM(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 ho(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function MI(e){let t=new Map;for(let r of e.elements.values()){if(r.importedFrom===void 0)continue;let o=t.get(r.importedFrom);o||(o={candidates:[],keys:new Map},t.set(r.importedFrom,o)),o.candidates.push(r)}let n=r=>{if(Yo(r.tag))return r.identity.key;let o=t.get(r.sourceFile);if(!o)return null;if(o.keys.has(r.componentName))return o.keys.get(r.componentName);let i=o.candidates.filter(a=>TM(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>PM({...r,graph:e},n)}function PM(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=AM(n,r,o,t),a=s?.tag??(Yo(r.tag)?r.tag:r.componentName),l=s?.identity.key??t(r,o)??n,c=OM(s),u=LM(n,r,o,i,s),d=NM(n,r,o,i,l);return{componentName:a,instanceKey:l,templateOwner:wM(s??r,a),...c.length>0?{variantKeys:c}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:FM(d),alternativeStrategies:DM(d)}}function NM(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Cm(e,n)?"instance":!Yo(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function AM(e,t,n,r){if(Yo(t.tag))return t;let o=Cm(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function TM(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function wM(e,t){return Yo(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function OM(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=Cm(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let l=a?.chain.find(u=>u.kind==="component-prop");if(!l)continue;let c=l.displayName.split(".").pop();c&&i.add(c)}return i.size===0&&Yo(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Cm(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Yo(r.tag))return r;n=r.parentKey}return null}function Yo(e){return/^[A-Z]/.test(e)}function FM(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 $I(e){let t=e.isRepeat??(e.graph?XM(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=JM(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>MM({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,l=(e.element.attributeSpreads??[]).slice().sort((u,d)=>u.order-d.order).map(u=>({raw:u.raw,sourceRange:zM(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."}]})),c=t&&e.selectionRef?.instanceIndex!==void 0&&i;return{documentVersion:e.documentVersion,...e.selectionRef?{selectionRef:e.selectionRef}:{},items:s,spreads:l,creation:t?{selection:c?"materialize":"unsupported",template:"unsupported"}:{selection:a?"unsupported":"direct",template:a?"unsupported":"direct"}}}function MM(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=BM(t,n,e.isRepeat),s=["selection","template"].map(h=>({scope:h,result:Rl({state:n,scope:h,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:h})=>h.ok)?.result,l=a?.ok?a.target:void 0,c=l?.kind==="value-binding"&&o&&(JSON.stringify(l.locator.root)!==JSON.stringify(o.selectedParentObjectLocator.root)||JSON.stringify(l.locator.path??[])!==JSON.stringify([...o.selectedParentObjectLocator.path??[],{kind:"property",name:t.name}]))?null:o,u=jM(t,n,c,e.isRepeat),d=l?VM(l,e.element,t.name):void 0,f=s.filter(({result:h})=>h.ok).map(({scope:h})=>h),m=f.length>0?UM(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",p=KM(t,n,r);if(f.length===0&&p.length===0){let h=s.find(({result:x})=>!x.ok)?.result;h&&!h.ok&&p.push({code:h.code,message:h.reason})}return{name:t.name,source:i,resolution:u,editMode:m,sourceScope:g,allowedWriteScopes:f,...d?{effectiveWriteTarget:d}:{},diagnostics:p}}function BM(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 jM(e,t,n,r){return n?BI(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:BI($M(e))}function $M(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 BI(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function UM(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 VM(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:jI({...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:jI(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function KM(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 JM(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function XM(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 jI(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 zM(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 HM(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var WM=160;function UI(e,t,n,r={}){let o=ui(e),i=[];for(let[s,a]of e.elements){let l=n.get(s),c={canUpdateText:r.canUpdateTextByKey?.get(s)??l?.canUpdateText??!1,canInsertChild:l?.canInsertChild??!1,canMove:l?.canMove??!1,canRemove:l?.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:c,...r.dynamicDataSummaryByKey?.get(s)?{dynamicDataSummary:r.dynamicDataSummaryByKey.get(s)}:{}})}return{composition:o,routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:i}}function VI(e,t,n,r,o,i,s,a,l,c,u){let d=ui(t),f=t.elements.get(e),m=n.nodes.get(e),g=r.get(e);if(!f||!m||!g)throw new Error(`Node not found: ${e}`);let p=HI(f.textSegments,s),h=WI(e,t,f,g,p),x=p?qM(p):void 0,b=QM(i,p),E=f.textSegments.map(I=>({index:I.index,value:I.value,editable:GI(I,g,s?.get(I.index)??null),source:o.get(I.index)??null})),S=XI(f,t),v=f.childKeys.map(I=>{let _=t.elements.get(I);return _?{key:I,tag:_.tag,label:_.tag}:null}).filter(I=>I!==null),A=[];if(f.parentKey){let I=t.elements.get(f.parentKey);if(I)for(let _ of I.childKeys){if(_===e)continue;let k=t.elements.get(_);k&&A.push({key:_,tag:k.tag,label:k.tag})}}return{composition:d,key:e,tag:f.tag,componentName:f.componentName,sourceFile:f.sourceFile,sourceLocator:JI(f),label:f.tag,capabilities:h,writeTarget:i,effectiveWriteTarget:b,provenanceChain:x,componentSemantic:l,styleSource:c,conditional:a,...u?{dynamicData:u}:{},textSegments:E,boundaryKind:f.boundaryKind,isOpaque:f.isOpaque,ancestors:S,children:v,siblings:A}}function KI(e,t,n,r,o,i,s,a){let l=ui(t),c=t.elements.get(e),u=n.nodes.get(e),d=r.get(e);if(!c||!u||!d)throw new Error(`Node not found: ${e}`);let f=HI(c.textSegments,i),m=GM(c);return{composition:l,key:e,tag:c.tag,...m?{linkSourceKind:m}:{},componentName:c.componentName,sourceFile:c.sourceFile,sourceLocator:JI(c),label:c.tag,capabilities:WI(e,t,c,d,f),provenanceChain:f?{editMode:f.editMode,diagnostics:f.diagnostics.map(g=>({code:g.code,message:g.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:c.textSegments.map(g=>{let p=o.get(g.index);return{index:g.index,editable:GI(g,d,i?.get(g.index)??null),source:p?{kind:p.kind}:null}}),boundaryKind:c.boundaryKind,isOpaque:c.isOpaque,ancestors:XI(c,t)}}function GM(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 JI(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:YM(e.sourceRange),structuralPath:e.identity.structuralPath,...ZM(e.textSegments)}}function XI(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 YM(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function ZM(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,WM)}:{}}function zI(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 HI(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function WI(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,l=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"},c=r.canUpdateText&&YI(l.mode);return{...r,canUpdateText:c,editModes:{updateText:l,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 GI(e,t,n){return!e.editable||!t.canUpdateText?!1:n?YI(n.editMode):!0}function YI(e){return e==="direct"||e==="proxy"||e==="upstream"}function qM(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 QM(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}:HM(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 Rm=["set-class-name-source","apply-style-draft"];function ZI(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Rm,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:Rm,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Rm}}import qI from"node:path";function Nm(){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 ev(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=rB(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 l=t.has(a),c=n?await n(a):!1;if(l||c)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 iu(e){let t=()=>eB(e);return e.mutex?e.mutex.runExclusive(t):t()}async function eB(e){let t=await ev(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=tB(e.overlay,t.plan),r;try{r=await e.buildCandidate({overlay:n,plan:t.plan})}catch(c){return{ok:!1,stage:"build",reason:"Candidate build failed.",error:c,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(c){return Pm({candidate:r,plan:t.plan,failedStage:"commit",error:c,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let s=r;try{let c=await e.validateCandidate({candidate:r,plan:t.plan,receipt:i});c!==void 0&&(s=c)}catch(c){return Pm({candidate:r,plan:t.plan,failedStage:"validate",error:c,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let a;try{a=await e.publishCandidate({candidate:s,plan:t.plan,history:o,receipt:i})}catch(c){return Pm({candidate:s,plan:t.plan,failedStage:"publish",error:c,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let l={candidate:s,plan:t.plan,history:o,receipt:i,published:a};try{await e.swapCandidate?.(l)}catch(c){return QI("swap",c,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(l)}catch(c){return QI("finalize",c,"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 tB(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 Pm(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:nB(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 QI(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function nB(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 rB(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)||qI.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=qI.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 oB=50,iB=8*1024*1024;function ov(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??oB),s=Math.max(0,t.maxUndoBytes??iB);return{prepareRewritePlan:a,execute:l,executeFilePlan:c,undo:u,redo:d};async function a(I){let _=[...I.steps].sort((z,Z)=>z.order-Z.order),k=_.filter(z=>z.type!=="invoke-external-adapter");if(k.length!==_.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let T=new Set(k.map(z=>z.file)),L=await b(T),$=new Map(L.map(z=>[z.file,z.exists===!1?"":z.content])),J;for(let z of k){let Z=rv(z,$.get(z.file)??"");if(!Z.ok)return{ok:!1,errorCode:Z.errorCode,reason:Z.reason};$.set(z.file,Z.source),J=Z.selectionRef??J}return{ok:!0,filePlan:{operationId:I.operationId,kind:"source-edit",target:I.target,documentVersion:I.documentVersion,conflictPolicy:"compare-and-swap",edits:[...$].map(([z,Z])=>({operation:"upsert",file:z,content:Z,baseContentHash:L.find(W=>W.file===z)?.sha256??null}))},...J?{selectionRef:J}:{}}}async function l(I){let _=[...I.steps].sort((W,Ee)=>W.order-Ee.order),k=_.filter(W=>W.type!=="invoke-external-adapter"),T=_.filter(W=>W.type==="invoke-external-adapter"),L=new Set(k.map(W=>W.file));if(k.length>0&&T.length>0)return{ok:!1,operationId:I.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(k.length===0)return h(I,T);let $=await b(L),J=new Map;for(let W of $)J.set(W.file,W.exists===!1?"":W.content);let z;for(let W of k){let Ee=J.get(W.file)??"",xe=rv(W,Ee);if(!xe.ok)return{ok:!1,operationId:I.operationId,errorCode:xe.errorCode,reason:xe.reason,rolledBack:!1};J.set(W.file,xe.source),xe.selectionRef&&(z=xe.selectionRef)}let Z=await S([...J].map(([W,Ee])=>({file:W,content:Ee,exists:!0,version:0,sha256:je(Ee)})),$);return Z.ok===!1?{ok:!1,operationId:I.operationId,errorCode:Z.rolledBack?"writeback-failed":"rollback-failed",reason:Z.reason,rolledBack:Z.rolledBack}:(n.push({operationId:I.operationId,preSnapshots:$,postSnapshots:Z.snapshots,plan:I}),f(),r.length=0,{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:Math.max(...Z.snapshots.map(W=>W.version)),affectedFiles:[...L],...z?{selectionRef:z}:{}})}async function c(I){let _=new Set(I.edits.map(Z=>Z.file)),k=await b(_),T=x(I,k);if(T)return{ok:!1,operationId:I.operationId,errorCode:"stale-version",reason:T.reason,affectedFiles:[T.file],rolledBack:!1};let L=new Map(k.map(Z=>[Z.file,Z])),$=I.edits.find(Z=>Z.operation==="create-only"&&L.get(Z.file)?.exists!==!1);if($)return{ok:!1,operationId:I.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${$.file}`,affectedFiles:[$.file],rolledBack:!1};let J=I.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:je(Z.content)}),z=await S(J,k,new Set(I.edits.filter(Z=>Z.operation==="create-only").map(Z=>Z.file)));return z.ok===!1?{ok:!1,operationId:I.operationId,errorCode:z.rolledBack?"writeback-failed":"rollback-failed",reason:z.reason,rolledBack:z.rolledBack}:(n.push({operationId:I.operationId,preSnapshots:k,postSnapshots:z.snapshots,plan:{operationId:I.operationId,kind:I.kind,target:I.target,documentVersion:I.documentVersion,steps:[],preSnapshots:k}}),f(),r.length=0,{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:Math.max(...z.snapshots.map(Z=>Z.version)),affectedFiles:[..._]})}async function u(){let I=n.at(-1);if(!I)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let _=await S(I.preSnapshots,I.postSnapshots);return _.ok===!1?{ok:!1,operationId:I.operationId,errorCode:_.rolledBack?"writeback-failed":"rollback-failed",reason:_.reason,rolledBack:_.rolledBack}:(n.pop(),r.push(I),{ok:!0,operationId:I.operationId,kind:I.plan.kind,target:I.plan.target,resultVersion:Math.max(..._.snapshots.map(k=>k.version)),affectedFiles:I.preSnapshots.map(k=>k.file)})}async function d(){let I=r.at(-1);if(!I)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let _=await S(I.postSnapshots,I.preSnapshots);return _.ok===!1?{ok:!1,operationId:I.operationId,errorCode:_.rolledBack?"writeback-failed":"rollback-failed",reason:_.reason,rolledBack:_.rolledBack}:(r.pop(),n.push(I),f(),{ok:!0,operationId:I.operationId,kind:I.plan.kind,target:I.plan.target,resultVersion:Math.max(..._.snapshots.map(k=>k.version)),affectedFiles:I.postSnapshots.map(k=>k.file)})}function f(){for(;n.length>i;)n.shift();for(;n.length>0&&m()>s;)n.shift()}function m(){return n.reduce((I,_)=>I+g(_),0)}function g(I){return p(I.preSnapshots)+p(I.postSnapshots)}function p(I){return I.reduce((_,k)=>_+k.file.length+k.content.length,0)}async function h(I,_){let k=[];for(let T of _){let L=T.capability??"write-text",$=o.find(z=>z.sourceType===T.sourceType&&(T.adapterId===void 0||z.adapterId===T.adapterId)&&(z.capabilities===void 0||z.capabilities.includes(L)));if(!$)return{ok:!1,operationId:I.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${T.sourceType}`,rolledBack:!1};let J=await $.execute(T);if(!J.ok)return{ok:!1,operationId:I.operationId,errorCode:"writeback-failed",reason:J.reason??`External adapter failed for ${T.sourceType}`,rolledBack:!1};k.push(T.file)}return{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:0,affectedFiles:k}}function x(I,_){if(I.conflictPolicy!=="compare-and-swap")return null;let k=new Map(_.map(T=>[T.file,T]));for(let T of I.edits){if(T.operation==="create-only")continue;if(T.baseContentHash===void 0)return{file:T.file,reason:`Source file ${T.file} is missing baseContentHash. Reopen the file before saving.`};let L=k.get(T.file),$=T.baseContentHash;if($===null){if(L?.exists!==!1)return{file:T.file,reason:`Source file ${T.file} was created or changed before save.`};continue}if(!$)return{file:T.file,reason:`Source file ${T.file} is missing baseContentHash. Reopen the file before saving.`};if(L?.exists===!1||L?.sha256!==$)return{file:T.file,reason:`Source file ${T.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function b(I){let _=[];for(let k of I)_.push(await E(k));return _}async function E(I){if(!await e.exists(I))return{file:I,content:"",version:0,exists:!1};let k=Math.max(1,e.getVersion(I)),T=await e.readFile(I);return{file:I,content:T,version:k,exists:!0,sha256:je(T)}}async function S(I,_,k=new Set){let T=[];try{for(let L of I){if(k.has(L.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(L.file,L.content)}else await v(L);let $=e.bumpVersion(L.file);T.push(L.file),L.version=$}}catch(L){let $=await A(_.filter(z=>T.includes(z.file)));if($.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${$.failedFiles.join(", ")}: ${nv(L)}`,rolledBack:!1,instanceConflict:tv(L)};let J=tv(L);return{ok:!1,reason:`${J?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${nv(L)}`,rolledBack:!0,instanceConflict:J}}return{ok:!0,snapshots:I.map(sB)}}async function v(I){if(I.exists===!1){await e.deleteFile(I.file);return}await e.writeFile(I.file,I.content)}async function A(I){let _=[];for(let k of I)try{await v(k),e.bumpVersion(k.file)}catch{_.push(k.file)}return _.length===0?{ok:!0}:{ok:!1,failedFiles:_}}}function tv(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function sB(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:je(e.content)}:{}}}function nv(e){return e instanceof Error?e.message:String(e)}function rv(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 Wt(Dn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return Wt(li({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return Wt(Oo({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return Wt(Fn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return Wt(cc({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return Wt(xs({source:t,locator:e.locator,next:e.value}));case"update-array-item":return Wt(xs({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return Wt(mc({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return Wt(lc({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return Wt(gc({source:t,locator:e.locator,index:e.index}));case"move-array-item":return Wt(hc({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return Wt(Fo({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return Wt(uc({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 aB(e,t);case"set-property-changes":return Wt(dc({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return Wt(fc({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return Wt(pc({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return Wt(xc({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function aB(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!yy(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};let r=n.oldAttrRange!==null&&n.oldAttrRaw!==null,o=n.openingElementRange.start,i=n.openingElementRange.end,s=t.slice(o,i);if(!(Number.isInteger(o)&&Number.isInteger(i)&&o>=0&&i>o&&i<=t.length&&s.startsWith("<")&&s.endsWith(">")&&!s.startsWith("</")&&(n.oldAttrRange===null||n.oldAttrRange.start>=o&&n.oldAttrRange.end<=i)))return{ok:!1,reason:"The opening element range changed before className save.",errorCode:"stale-version"};if(!r&&n.expectedVersion.contentHash!==je(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:hy({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function Wt(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 su,SiteEditCompositionContextSchema as cB,SiteEditCompositionSelectorSchema as lB}from"@vcp-dev/contracts";var en=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function iv(e,t){throw new en("INVALID_COMPOSITION",e,{value:t})}function au(e){let t=cB.safeParse(e);return t.success?t.data:iv("Invalid SiteEditCompositionContext.",e)}function sv(e){let t=[],n=new Map,r=new Map;for(let c of e.compositions){let u=au(c?.context);if(typeof c.entryFile!="string"||!c.entryFile)throw new en("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=su(u);if(n.has(d))throw new en("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let f=r.get(c.entryFile);if(f)throw new en("DUPLICATE_COMPOSITION",`Entry file ${c.entryFile} is registered more than once.`,{entryFile:c.entryFile,context:f});let m={context:u,entryFile:c.entryFile,key:d};t.push(m),n.set(d,m),r.set(c.entryFile,d)}if(t.length===0)throw new en("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let c of e.initialDocumentVersions??[]){let u=au(c?.composition);if(!Number.isInteger(c?.version)||(c?.version??-1)<0)throw new en("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:c?.version});let d=su(u);if(!n.has(d))throw new en("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new en("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:d});o.set(d,c.version)}function i(c){let u=lB.safeParse(c);if(!u.success)return iv("Invalid SiteEditCompositionSelector.",c);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 en("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new en("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(c){let u=au(c),d=su(u),f=n.get(d);if(!f)throw new en("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return f}function a(c){let u=au(c?.context);if(typeof c.entryFile!="string"||!c.entryFile)throw new en("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=su(u),f=n.get(d);if(f){if(f.entryFile===c.entryFile)return f;throw new en("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let m=[...n.values()].find(p=>p.entryFile===c.entryFile);if(m)throw new en("DUPLICATE_COMPOSITION",`Entry file ${c.entryFile} is registered more than once.`,{entryFile:c.entryFile,context:m.context});let g={context:u,entryFile:c.entryFile,key:d};return t.push(g),n.set(d,g),g}function l(c){let u=n.get(c);if(!u)return;n.delete(c);let d=t.findIndex(f=>f.key===c);return d>=0&&t.splice(d,1),o.delete(c),u}return{entries:t,byKey:n,initialVersions:o,register:a,unregister:l,resolveSelector:i,resolveContext:s,getByKey:c=>n.get(c),routeIds:()=>[...new Set(t.map(({context:c})=>c.routeId))]}}function Am(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 av(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 l=o++;try{n[l]=await t(e[l])}catch(c){r.push({index:l,error:c})}}}),s=await Promise.allSettled(i),a=r.sort((l,c)=>l.index-c.index)[0];if(a)throw a.error;for(let l of s)if(l.status==="rejected")throw l.reason;return n}import{composeSiteEditRepeatInstanceKey as uB,stripSiteEditRepeatInstanceKeys as cv}from"@vcp-dev/contracts";function lv(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=cv(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 dB(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 cu(e){return e?.map(t=>({...t}))}function Tm(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=cu(e.collectionPathMap?.[t])??cu(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:cu(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>cu(o)??[])}}function uv(e,t,n){let r=new Set;for(let m of t.regions)if(m.kind==="repeat-region")for(let g of m.childKeys)r.add(g);if(r.size===0)return e;let o=new Map(e.entries.map(m=>[m.key,m])),i=[],s=new Map,a=(m,g)=>uB(m,g),l=(m,g,p)=>{let h=o.get(m);if(!h)return a(m,p);let x=a(m,p),b={...h,key:x,parentKey:g,childKeys:[]};return i.push(b),b.childKeys=h.childKeys.flatMap(E=>c(E,p,x)),x},c=(m,g,p)=>{if(!r.has(m))return[l(m,p,g)];let h=d(m,g),x=[];for(let b=0;b<h;b+=1)x.push(l(m,p,[...g,b]));return x},u=Array.from(new Set([...e.rootKeys,...e.entries.filter(m=>m.parentKey===null).map(m=>m.key)]));for(let m of u){if(!r.has(m)){l(m,null,[]);continue}let g=d(m,[]);for(let p=0;p<g;p+=1)l(m,null,[p])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(m,g){let p=new Set;for(let h of f(m)){let x=n.get(h);if(x){for(let b of[...x.textTargets.values(),...x.elementPropertyTargets.values()])if(!(b?.kind!=="value-binding"||b.sourceKind!=="repeat-template"))for(let E of fB(b))E.length<=g.length||pB(E,g)&&p.add(E[g.length])}}return p.size>0?p.size:dB(n.get(m))}function f(m){let g=s.get(m);if(g)return g;let p=[m],h=o.get(m);for(let x of h?.childKeys??[])p.push(...f(x));return s.set(m,p),p}}function dv(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function fv(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((cv(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function fB(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 pB(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 pv(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 l=i.childKeys.map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label})),c=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:l,siblings:c}}function mv(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(l=>[l.key,l])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let l=o.get(a);if(!l)break;s.push({key:l.key,tag:l.tag,label:l.label}),a=l.parentKey}return s.reverse(),{...e,key:i.key,ancestors:s}}function gv(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function mB(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var ha=class extends Error{constructor(t){let n=t.map(gv);super(mB(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function hv(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof ha?{routeId:e,message:n,diagnostics:t.diagnostics.map(gv)}:{routeId:e,message:n}}function wm(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Om(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function ya(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function yv(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function lu(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((c,u)=>c.preDigest===r[u]),i=t.files.every((c,u)=>c.postDigest===r[u]),s=t.historyTransition,a=n.digest===s.expectedIndexDigest,l=n.digest===s.publishedIndexDigest&&n.cursor===s.publishedCursor&&n.currentId===s.publishedCurrentId;return o&&a?"safely-uncommitted":i&&l?"durably-committed":"ambiguous"}var IB=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,vB=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],bv=32,du=256;function kB(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Ev={maxEntries:50,maxBytes:8*1024*1024};function _B(){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 Sv(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 CB(){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>Ev.maxEntries||RB(e)>Ev.maxBytes;)e.shift()}}function RB(e){return e.reduce((t,n)=>t+PB(n),0)}function PB(e){return Iv(e.preSnapshots)+Iv(e.postSnapshots)+NB(e.provenance)}function NB(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function Iv(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function vv(e,t){return{key:hB(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 fu=class extends Error{constructor(t){super(t.reason),this.result=t}},Zo=class extends Error{constructor(t){super(wm(t)),this.failedRoutes=t}};function kv(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=pn(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(pn(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function AB(e,t,n){if(!n)return;let r=pn(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 TB=/\.(?:[cm]?[jt]sx?)$/i,wB=/\.json$/i,OB=/\.(?:css|scss|sass)$/i,LB=/\.mdx$/i,FB=/\.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 MB(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function BB(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=Av(await e.listFiles(i)),a=new Map(s.files.map(c=>[c.path,c]));for(let[c,u]of n)if(jB(c,i.roots??[])){if(!u.exists){a.delete(c);continue}a.set(c,{path:c,sizeBytes:Buffer.byteLength(u.content,"utf8")})}let l=[...a.values()].sort((c,u)=>c.path.localeCompare(u.path));return s.truncated?{files:l,truncated:s.truncated}:l},getVersion(i){return e.getVersion(i)},bumpVersion(i){return e.getVersion(i)}}}function jB(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Av(e){return Array.isArray(e)?{files:e}:e}function $B(e){if(!xB(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!==EB||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=yB(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(TB.test(e.path)){let t=or({source:e.content,profile:Ro({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(wB.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(OB.test(e.path)){let t=_v({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(LB.test(e.path)){let t=_v({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(FB.test(e.path))try{SB(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${on(t)}`,details:{path:e.path}}}return{ok:!0}}function _v({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,l=!1,c=!0;for(let d=0;d<e.length;d+=1){let f=e[d]??"",m=e[d+1]??"";if(n==="mdx"&&c&&e.startsWith("```",d)){l=!l;let g=e.indexOf(`
|
|
8
|
+
`,d);if(g===-1){c=!0;break}d=g,c=!0;continue}if(l){c=f===`
|
|
9
|
+
`||f==="\r";continue}if(s){f==="*"&&m==="/"&&(s=!1,d+=1),c=f===`
|
|
10
10
|
`||f==="\r";continue}if(a){f===`
|
|
11
11
|
`||f==="\r"?(a=!1,c=!0):c=!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
|
|
13
|
-
`||f==="\r";continue}if(f==="/"&&
|
|
14
|
-
`||f==="\r"}if(s)return Ei(t,`Unterminated block comment in ${t}.`);if(o)return Ei(t,`Unterminated string literal in ${t}.`);if(l)return Ei(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Ei(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Ei(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Ol(e){let t="idle",n=e.fileSystem??cB(),r=Zh(),o=jv({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,l=null,c=e.history??(e.historyStore?$y(e.historyStore):lB()),u=Mv(n,{externalAdapters:e.externalAdapters}),d=new Map,f=ay(Tl),g=new Set,m=0,p=e.historyStore?.recoveryRequired??!1,h=rm(),x=v();function E(y){return(Al.isAbsolute(y)?Al.relative(e.projectRoot,y):y).replace(/\\/g,"/").replace(/^\.\//,"")}function b(y,R){let k=Al.posix.dirname(y),T=R.replace(/\.(?:tsx?|jsx?)$/i,""),B=Al.posix.relative(k,T);return B.startsWith(".")?B:`./${B}`}function S(y,R){return y.startLine===R.startLine&&y.startColumn===R.startColumn&&y.endLine===R.endLine&&y.endColumn===R.endColumn}async function v(){let y=e.historyStore;if(y)try{let R=await y.readTransactionJournal();if(!R)return;let k=await y.readIndex(),T=await Promise.all(R.files.map(async j=>await n.exists(j.path)?Te(await n.readFile(j.path)):null));if(Zv({journal:R,index:k,observedFileDigests:T})!=="ambiguous"){await y.clearTransactionJournal(R.transactionId);let j=await y.readStatus();j.recoveryRequired||(await y.cleanupTmp(),j=await y.readStatus()),p=j.recoveryRequired;return}await y.markRecoveryRequired(`Ambiguous transaction journal ${R.transactionId} at phase ${R.phase}`),p=!0}catch(R){p=!0,await y.markRecoveryRequired(`Transaction journal recovery failed: ${Ht(R)}`).catch(()=>{})}}function P(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let y of o.entries){let R=nI(y.context,y.entryFile);i.set(y.key,R),I(R,R.dependencyFiles)}function I(y,R){let k=new Set(R);C(y),y.dependencyFiles=k;for(let T of y.dependencyFiles){let B=s.get(T);B||(B=new Set,s.set(T,B)),B.add(y.key)}}function C(y){for(let R of y.dependencyFiles){let k=s.get(R);k&&(k.delete(y.key),k.size===0&&s.delete(R))}y.dependencyFiles.clear()}function N(y){let R=new Set;for(let k of y)for(let T of s.get(k)??[])R.add(T);return R}function w(y){for(let R of y)if(!s.has(R))return!1;return!0}async function L(y,R,k,T,B,j){let X=new Map,z=hv(y),te=iv(B.values()),W=oS(B.values()),H=typeof j.exists=="function"?ie=>j.exists(ie):async()=>!1;for(let[ie,fe]of y.elements){let Ae=R.nodes.get(ie);if(!Ae)continue;let ce=k.get(fe.sourceFile)??T.get(fe.sourceFile),Be=new Map,Ce=new Map,V=new Map,ee=[];for(let ot of fe.textSegments){if(!ce){Be.set(ot.index,null);continue}let wi=await sv({file:fe.sourceFile,source:ce,segment:ot,readFile:sn=>j.readFile(sn),exists:H,graph:y,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:sn,adapterId:ro,capabilities:Su})=>({sourceType:sn,adapterId:ro,capabilities:Su})),functionCallContracts:e.functionCallContracts,fileCache:te}),zt=await Wp({file:fe.sourceFile,source:ce,target:{kind:"text-segment",segment:ot},readFile:sn=>j.readFile(sn),exists:H,graph:y,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:sn,adapterId:ro,capabilities:Su})=>({sourceType:sn,adapterId:ro,capabilities:Su})),functionCallContracts:e.functionCallContracts,fileCache:te}),xn=bB(wi);Be.set(ot.index,xn),Ce.set(ot.index,wi),V.set(ot.index,zt),ee.push({editable:ot.editable,source:xn})}let Se=new Map,Fe=new Map;if(ce)for(let ot of fe.attributes??[]){let wi=await bi({file:fe.sourceFile,source:ce,sourceRange:ot.sourceRange,expression:ot.source?.expression??ot.value,sourceInfo:ot.source,readFile:xn=>j.readFile(xn),exists:H,graph:y,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:xn,adapterId:sn,capabilities:ro})=>({sourceType:xn,adapterId:sn,capabilities:ro})),functionCallContracts:e.functionCallContracts,fileCache:te}),zt=await gv({element:fe,file:fe.sourceFile,source:ce,propertyName:ot.name,readFile:xn=>j.readFile(xn),exists:H,graph:y,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:xn,adapterId:sn,capabilities:ro})=>({sourceType:xn,adapterId:sn,capabilities:ro})),functionCallContracts:e.functionCallContracts,fileCache:te});Fe.set(ot.name,zt),Se.set(ot.name,wi)}let je=_v(EB(Ae.writeTarget),ee),ut=z({key:ie,element:fe,provenances:V}),kr=Av(fe),Vn=ce?await fl({element:fe,graph:y,file:fe.sourceFile,source:ce,readFile:ot=>j.readFile(ot),exists:H,fileCache:W}):void 0,no=y.regions.find(ot=>ot.kind==="conditional-region"&&ot.childKeys.includes(ie)),Ft,yn=no?.sourceCandidates?.[0];if(ce&&no&&yn?.kind==="conditional-branch"){let ot=await Wp({file:fe.sourceFile,source:ce,target:{kind:"conditional-branch",candidate:yn},readFile:zt=>j.readFile(zt),exists:H,graph:y,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:zt,adapterId:xn,capabilities:sn})=>({sourceType:zt,adapterId:xn,capabilities:sn})),functionCallContracts:e.functionCallContracts,fileCache:te});Ft={currentBranch:no.childKeys.indexOf(ie)<=0?"then":"else",availableBranches:no.childKeys.length>1?["then","else"]:["then"],conditionExpression:yn.conditionExpression,provenance:{finalSource:ot.finalSource?{kind:ot.finalSource.kind,file:ot.finalSource.file,displayPath:ot.finalSource.displayPath}:null,chain:ot.chain.map(zt=>({kind:zt.kind,file:zt.file,displayName:zt.displayName,canEditHere:zt.canEditHere})),confidence:ot.confidence,editMode:ot.editMode,diagnostics:ot.diagnostics.map(zt=>({code:zt.code,message:zt.message}))}}}X.set(ie,{textSources:Be,textTargets:Ce,elementPropertyTargets:Se,propertyProvenances:Fe,isRepeat:jB(ie,y),provenances:V,writeTarget:je,componentSemantic:ut,styleSource:kr,conditional:Ft,dynamicData:Vn})}return X}function D(y){return typeof n.getVersion=="function"?n.getVersion(y):0}function U(y,R){let k=o.initialVersions.get(y.key)??0;for(let T of R.values())k=Math.max(k,T);return Math.max(k,y.graph?.version??0)}function M(y){return i.get(y)?.graph?.version??o.initialVersions.get(y)??0}function G(y){try{return M(o.resolveSelector(y.composition).key)}catch{return 0}}async function K(y,R,k=n,T={}){let B=await zo(y,R,j=>k.readFile(j),j=>k.exists(j),{additionalEntries:await oe(y,k),...T});if(B.diagnostics.length>0)throw new Vs(B.diagnostics);return T.validationOnly||f.remember(B.parsedModules.values()),B}async function ge(y,R,k={}){let T=i.get(y);if(!T)return null;let B=k.sourceCache??am(d,[]),j=k.fileSystem??om(n),{graph:X,allSources:z,parsedModules:te,entryModule:W}=await K(T.entryFile,R,j,{version:T.graph?.version??1}),H=new Map;for(let Ft of z.keys())H.set(Ft,D(Ft));let ie=Math.max(U(T,H),k.minimumVersion??0);k.changed&&ie<=(T.graph?.version??0)&&(ie=(T.graph?.version??0)+1),X.version=ie;for(let[Ft,yn]of z)Nl(B,Ft,yn,Tl);let fe=await Me(T.composition,T.entryFile,z,B,j);X.routeId=T.routeId,X.composition=T.composition;let Ae=Rc(X),ce=ja(Ae,X),Be=await L(X,Ae,z,B,te,j);st(ce,Be);let Ce=xe(X,ce,Be),V=pt(Be),ee=Kv(Ev(X,Ae,ce,{canUpdateTextByKey:Ce,dynamicDataSummaryByKey:V}),X,Be),Se=On({route:T.routeId,composition:T.composition,entryFile:T.entryFile,version:ie,source:R,ast:W?.ast}),Fe=Vx(Se),je=null,ut=[];if(Se.ok){_B(ee,X,Se.projection,te);let Ft=_c({composition:T.composition,entryFile:T.entryFile,graph:X,parsedModules:te,projection:Se.projection});if(Ft.diagnostics.length===0){let yn=ps({composition:T.composition,entryFile:T.entryFile,graph:X,parsedModules:te,projection:Se.projection,documentVersion:ie,roots:Ft.roots});yn.diagnostics.length===0&&(je=yn,ut=yn.descriptors)}}let kr={...ee,composition:T.composition,pageBlocks:ut,...fe?{styleContext:fe}:{},pageComposition:Fe},Vn=new Set([T.entryFile,...z.keys()]);if(fe){Vn.add(fe.entryCss.path);for(let Ft of fe.stylesheets)Vn.add(Ft.path)}let no={...T,dependencyFiles:Vn,graph:X,topology:Ae,capabilities:ce,document:kr,pageBlockIndex:je,pageComposition:Fe,pageCompositionProjection:Se.projection,pagePlacementByKey:Se.ok?Se.projection.placementByKey:null,pagePlacementUnitByKey:Se.ok?Se.projection.placementUnitByKey:null,pageUnitByKey:Se.ok?Se.projection.unitByKey:null,pagePlacementsByUnitKey:Se.ok?Se.projection.placementsByUnitKey:null,documentIndex:Vv(kr),detailProjections:Be,fileVersions:H,styleContext:fe};if(k.publish===!1)return no;for(let Ft of Vn){let yn=z.get(Ft)??B.get(Ft);yn!==void 0&&(Nl(d,Ft,yn,Tl),g.delete(Ft))}return I(T,Vn),Object.assign(T,no),T}async function oe(y,R=n){let k=[];for(let T of OB(y))typeof R.exists=="function"&&await R.exists(T)&&k.push({file:T,source:await R.readFile(T)});return k}async function Me(y,R,k,T,B){let j=[];for(let[H,ie]of k){if(cm(H)){j.push(H);continue}for(let fe of LB(ie)){let Ae=cI(H,fe);Ae&&j.push(Ae)}}if(!j.length){for(let H of FB(R))if(await B.exists(H)){j.push(H);break}}let X=new Map,z=BB(j).slice(0,qv);for(;z.length>0&&X.size<qv;){let H=z.shift();if(X.has(H)||!cm(H))continue;let ie=await He(H,T,B);if(ie!==null){X.set(H,{path:H,content:ie});for(let fe of DB(ie)){let Ae=cI(H,fe);Ae&&!X.has(Ae)&&!z.includes(Ae)&&z.push(Ae)}}}let te=[...X.values()].map(H=>({...H,hash:Te(H.content)})),W=te[0];return W?{composition:y,revision:Te(JSON.stringify(te.map(({path:H,hash:ie})=>({path:H,hash:ie})))),entryCss:W,stylesheets:te.slice(1)}:null}async function He(y,R,k){let T=R.get(y);if(T!==void 0)return T;if(!await k.exists(y))return null;let B=await k.readFile(y);return Nl(R,y,B,Tl),B}function pt(y){let R=new Map;for(let[k,T]of y)T.dynamicData?.bindings.length&&R.set(k,hS(T.dynamicData.bindings));return R}function xe(y,R,k){let T=new Map;for(let[B,j]of y.elements){if(!R.get(B)?.canUpdateText){T.set(B,!1);continue}let z=k.get(B),te=j.textSegments.some(W=>{if(!W.editable)return!1;let H=z?.provenances.get(W.index)??null;return!H||Je(H)});T.set(B,te)}return T}function st(y,R){for(let[k,T]of R){let B=y.get(k);B?.canUpdateText&&T.dynamicData?.bindings.some(j=>j.readonly&&(j.targetKind==="text"||j.targetKind==="richtext"))&&y.set(k,{...B,canUpdateText:!1})}}function Je(y){return y.editMode==="direct"||y.editMode==="proxy"||y.editMode==="upstream"}async function pe(y,R={}){let k=[...new Set(y)],T=R.affectedCompositionKeys!==void 0,B=T?new Set(R.affectedCompositionKeys):N(k);if(!T&&(B.size===0||!w(k)))for(let W of i.values())ia(W,k)&&B.add(W.key);let j=!T&&B.size===0&&k.some(aI),X=R.publish===!1?am(d,k):void 0,z={rebuiltRoutes:[],failedRoutes:[],...R.publish===!1?{candidateRouteStates:[],candidateSourceCache:X}:{}},te=om(n);for(let W of i.values())if(!(R.excludedCompositionKeys?.has(W.key)||!(B.has(W.key)||j)))try{let ie=!!W.graph,fe=await te.readFile(W.entryFile),Ae=await ge(W.key,fe,{...R,fileSystem:te,...X?{sourceCache:X}:{}});Ae?.graph&&(z.rebuiltRoutes.push({documentChanged:ie,composition:W.composition,routeId:W.routeId,version:Ae.graph.version}),z.candidateRouteStates?.push({composition:W.composition,key:W.key,routeId:W.routeId,state:Ae}))}catch(ie){z.failedRoutes.push({...Gv(W.routeId,ie),composition:W.composition})}return z}function $(y){let R=[...new Set(y)],k=N(R);if(k.size>0&&w(R))return[...k];for(let T of i.values())ia(T,R)&&k.add(T.key);return[...k]}function ae(y){let R=new Set($(y));return o.entries.filter(k=>R.has(k.key)).map(k=>k.context)}function he(y){return[...new Set($(y))].sort((k,T)=>k<T?-1:k>T?1:0).map(k=>o.getByKey(k)?.context).filter(k=>k!==void 0)}function Le(y,R){let k=new Set($(R)),T=y.provenance?.affectedCompositions??[];if(T.length===0)return k;if([...new Set(T.map(j=>o.resolveContext(j).key))].some(j=>!k.has(j)))throw new Error("History provenance does not match the affected composition index.");return k}function kt(y,R){let k=y.composition??y.provenance?.initiatingComposition;if(k){let j=o.resolveContext(k);return{context:j.context,key:j.key}}let T=[...new Set($(R))];if(T.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${T.length}).`);let B=o.getByKey(T[0]);if(!B)throw new Error("Legacy history entry references an unknown affected composition.");return{context:B.context,key:B.key}}function Un(y,R){r.emit({type:"operation-completed",composition:y.composition,result:y});for(let{composition:k,version:T}of R.rebuiltRoutes)r.emit({type:"document-changed",composition:k,version:T});for(let{composition:k,message:T}of R.failedRoutes)r.emit({type:"graph-error",composition:k,message:T})}function ia(y,R){return R.some(k=>y.dependencyFiles.has(k)||y.entryFile===k||y.graph?.fileIndex.has(k))}function kg(y){for(let R of y)a.add(R);l||P()||(l=(async()=>{t="building";let R=!1;try{for(;a.size>0;){if(P())return;await v_(),await h.runExclusive(async()=>{if(m>0||P())return;let k=[...a];a.clear();let T=await _g(k);if(T.length===0)return;let B=$(T);for(let z of B){let te=i.get(z)?.composition;te&&r.emit({type:"graph-invalidated",composition:te})}let{rebuiltRoutes:j,failedRoutes:X}=await pe(T,{changed:!0});for(let{documentChanged:z,composition:te,version:W}of j)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)R=!0,r.emit({type:"graph-error",composition:z,message:te})})}}finally{l=null,t!=="disposed"&&(t=!R&&[...i.values()].some(k=>k.graph)?"ready":"idle"),a.size>0&&kg([])}})())}async function v_(){for(;m>0;)await new Promise(y=>setTimeout(y,0))}async function _g(y){let R=[];for(let k of new Set(y)){let T=d.get(k);if(T===void 0){if(g.has(k)&&!await n.exists(k))continue;g.delete(k),R.push(k);continue}try{await n.readFile(k)!==T&&(g.delete(k),R.push(k))}catch(B){if(!kB(B))try{if(await n.exists(k))continue}catch{continue}g.add(k),R.push(k)}}return R}function Rg(y){Yv(d,y);for(let R of y)R.exists===!1?g.add(R.file):g.delete(R.file)}function Pg(y){g.clear();for(let R of y)g.add(R)}async function Cg(y){let R=await _g(y);if(R.length===0)return;let k=$(R);for(let j of k){let X=i.get(j)?.composition;X&&r.emit({type:"graph-invalidated",composition:X})}let{rebuiltRoutes:T,failedRoutes:B}=await pe(R,{changed:!0});for(let{documentChanged:j,composition:X,version:z}of T)r.emit({type:"graph-ready",composition:X,version:z}),j&&r.emit({type:"document-changed",composition:X,version:z});for(let{composition:j,message:X}of B)r.emit({type:"graph-error",composition:j,message:X})}async function I_(y,R){let k=Bo(y,R);if(!k?.graph)return;let T=en(y)??y,B=k.graph.elements.get(T);B&&await Cg([B.sourceFile])}async function Ng(y){let R=new Set;if(y.target.kind==="node"){let k=Bo(y.target.key,y.composition),T=en(y.target.key)??y.target.key,B=k?.graph?.elements.get(T);B&&R.add(B.sourceFile)}else if(y.target.kind==="route"){let k=i.get(o.resolveSelector(y.target.composition).key);k&&R.add(k.entryFile)}else if(y.target.kind==="page-unit"){let k=i.get(o.resolveSelector(y.target.composition).key);k&&R.add(k.entryFile)}else if(y.target.kind==="page-block"){let k=i.get(o.resolveSelector(y.target.composition).key),T=k?.pageBlockIndex?.bindings.get(y.target.blockKey);if(T&&(R.add(T.ownerFile),R.add(T.descriptor.source.file)),k?.pageBlockIndex&&y.params.kind==="move-node"&&"kind"in y.params.target&&y.params.target.kind==="block-boundary"){let B=k.pageBlockIndex.bindings.get(y.params.target.anchorBlockKey);B&&(R.add(B.ownerFile),R.add(B.descriptor.source.file))}}else if(y.target.kind==="source-file")R.add(y.target.path);else if(y.target.kind==="source-batch")for(let k of y.target.paths)R.add(k);if(y.params.kind==="move-node"&&!("kind"in y.params.target)){let k=[y.params.target.parentKey,...y.params.target.relation==="before"||y.params.target.relation==="after"?[y.params.target.anchorKey]:[]];for(let T of k){let B=Bo(T,y.composition),j=en(T)??T,X=B?.graph?.elements.get(j);X&&R.add(X.sourceFile)}}await Cg(R)}async function k_(y){if(y.params.kind!=="source-edit")return yu(y,"invalid-params","source-edit requires source-edit params");for(let R of y.params.edits){let k=IB(R);if(!k.ok)return yu(y,k.errorCode,k.message,k.details)}m+=1;try{let R=await O_(y.params.edits);if(!R.ok)return yu(y,R.errorCode,R.message,R.details);await Ng(y);let k={operationId:y.id,kind:"source-edit",target:y.target,documentVersion:y.documentVersion,conflictPolicy:y.params.conflictPolicy,edits:y.params.edits.map(T=>T.operation==="delete"?{operation:"delete",file:T.path,baseContentHash:T.baseContentHash??null}:{operation:"upsert",file:T.path,baseContentHash:T.baseContentHash??null,content:T.content})};return await Ir({request:y,filePlan:k})}catch(R){return{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!1,resultVersion:G(y),error:{code:J.INTERNAL_ERROR,message:Ht(R)}}}finally{m-=1}}async function __(y){if(y.target.kind!=="project"||y.params.kind!=="insert-page-resource")return Z(y,J.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");m+=1;try{let R=await Fi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...y.params.artifact.components.flatMap(T=>T.materialization.files.map(B=>({path:B.pathTemplate,content:B.content}))),...y.params.artifact.pages.flatMap(T=>T.materialization.files.map(B=>({path:B.pathTemplate,content:B.content})))],exists:T=>n.exists(T),readFile:T=>n.readFile(T)});if(!R.ok)return Z(y,J.MATERIALIZATION_REJECTED,R.message);let k=await Dd({artifact:y.params.artifact,exists:T=>n.exists(T)});return k.ok?await Ir({request:y,filePlan:{operationId:y.id,kind:"source-edit",target:y.target,documentVersion:y.documentVersion,conflictPolicy:"overwrite",edits:k.files},output:{kind:"insert-page-resource",package_instance_id:k.packageInstanceId,pages:k.pages},historyPolicy:"none"}):Z(y,k.code==="MATERIALIZATION_CONFLICT"?J.MATERIALIZATION_CONFLICT:J.MATERIALIZATION_REJECTED,k.message,k.path?{path:k.path}:void 0)}catch(R){return Z(y,J.INTERNAL_ERROR,Ht(R))}finally{m-=1}}async function R_(y){if(y.target.kind!=="project"||y.params.kind!=="delete-page-source")return Z(y,J.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return Z(y,J.PLAN_FAILED,"Complete project file listing is required for page deletion.");m+=1;try{let R=lI(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(R.truncated)return Z(y,J.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:R.truncated.reasons});let k=R.files.filter(({path:X})=>/\.(?:tsx?|jsx?)$/.test(X)),T=Object.fromEntries(await Promise.all(k.map(async({path:X})=>[X,await n.readFile(X)]))),B=Bb({expectedUrlPath:y.params.expectedUrlPath,files:T});if(!B.ok)return Z(y,B.code==="HOME_PAGE_LOCKED"?J.HOME_PAGE_LOCKED:B.code==="ROUTE_NOT_FOUND"?J.ROUTE_NOT_FOUND:J.PLAN_FAILED,B.message);let j=await Promise.all(B.edits.map(async X=>({...X,baseContentHash:Te(await n.readFile(X.file))})));return Ir({request:y,filePlan:{operationId:y.id,kind:"source-edit",target:y.target,documentVersion:y.documentVersion,conflictPolicy:"compare-and-swap",edits:j},output:{kind:"delete-page-source",deleted_files:B.deletedFiles,updated_files:B.updatedFiles,preserved_shared_files:B.preservedSharedFiles,warnings:B.warnings},historyPolicy:"none"})}catch(R){return Z(y,J.INTERNAL_ERROR,Ht(R))}finally{m-=1}}async function P_(y,R){if(y.kind!=="insert-child"&&y.kind!=="replace-node")return Z(y,J.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(y.params.kind!=="insert-child"&&y.params.kind!=="replace-node"||y.kind!==y.params.kind)return Z(y,J.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(y.params.kind==="insert-child"){if(!("kind"in y.params.position)||y.params.position.kind!=="page-composition")return Z(y,J.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(y.params.position.documentVersion!==y.documentVersion)return Z(y,J.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let k=R.document,T=R.pageCompositionProjection;if(!k||k.pageComposition?.status!=="supported"||!T||T.status!=="supported")return Z(y,J.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(y.documentVersion!==k.version||T.documentVersion!==k.version)return Z(y,J.VERSION_STALE,`Document version ${y.documentVersion} is stale (current: ${k.version}).`);let B=y.params.node.kind==="component-call"?y.params.node.materialization:void 0;if(!B)return Z(y,J.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let j=y.params.kind==="insert-child"?y.params.position:null,X=await Fi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:B.files.map(W=>({path:W.pathTemplate,content:W.content})),exists:W=>n.exists(W),readFile:W=>n.readFile(W)});if(!X.ok)return Z(y,J.MATERIALIZATION_REJECTED,X.message);let z=await eI(n,Object.keys(B.projectDependencies??{})),te=await Kd({manifest:B,generatedRoot:"components/site/generated",controlledFiles:B.files.map(W=>({pathTemplate:W.pathTemplate})),exists:W=>n.exists(W),availableHostDependencies:z,hostCapabilities:Td(),commit:async W=>{let H=await n.readFile(R.entryFile),ie=R.document,fe=R.pageCompositionProjection;if(!ie||ie.pageComposition?.status!=="supported"||ie.version!==y.documentVersion||!fe||fe.status!=="supported"||fe.documentVersion!==ie.version)return{ok:!0,data:Z(y,J.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Ae=W.entry.path,ce=$_(W.instanceName),Be,Ce=[];if(y.params.kind==="insert-child"){if(!j||!("kind"in j)||j.kind!=="page-composition")return{ok:!0,data:Z(y,J.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let Fe=ss({routeId:R.routeId,entryFile:R.entryFile,currentDocumentVersion:ie.version,expectedDocumentVersion:y.documentVersion,source:H,projection:fe,placementKey:j.placementKey,component:{source:Ae,exportName:W.entry.export.kind==="default"?"default":W.entry.export.name,localName:ce}});if(!Fe.ok)return{ok:!0,data:Z(y,Eu(Fe.error.code),Fe.error.message,{diagnostics:Fe.error.diagnostics})};let je=Fe.plan.rewriteStep,ut;switch(je.kind){case"insert-root-expression":ut=as({source:H,locator:je.locator,expectedSourceHash:je.sourceHash,action:{kind:"insert",jsx:je.node.jsx,placement:je.placement,replaceOriginal:je.replaceOriginal}});break;case"insert-child":ut=Sn({source:H,locator:je.parentLocator,node:je.node,placement:je.placement,...je.anchorLocator?{anchorLocator:je.anchorLocator}:{}});break;default:ut={ok:!1,source:H,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(je)}`}}}if(!ut.ok)return{ok:!0,data:Z(y,J.AST_PARSE_ERROR,ut.diagnostic.message)};Be=ut.source}else{let Fe=cf({routeId:R.routeId,composition:R.composition,entryFile:R.entryFile,currentDocumentVersion:ie.version,expectedDocumentVersion:y.documentVersion,source:H,projection:fe,placementUnitKey:y.target.placementUnitKey,operation:"replace-node"});if(!Fe.ok)return{ok:!0,data:Z(y,Eu(Fe.error.code),Fe.error.message,{diagnostics:Fe.error.diagnostics})};let je=Fe.plan.rewriteStep,ut;switch(je.kind){case"replace-root-expression":ut=as({source:H,locator:je.locator,expectedSourceHash:je.sourceHash,action:{kind:"replace",jsx:`<${ce} />`}});break;case"replace-node":ut=$o({source:H,locator:je.locator,node:{jsx:`<${ce} />`}});break;default:ut={ok:!1,source:H,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${je.kind}`}}}if(!ut.ok)return{ok:!0,data:Z(y,J.AST_PARSE_ERROR,ut.diagnostic.message)};let kr=await hu({routeState:R,placementUnitKey:y.target.placementUnitKey,source:H,mutatedSource:ut.source});Be=kr.source,Ce=await Promise.all(kr.files.map(async Vn=>({operation:"delete",file:Vn,baseContentHash:Te(await n.readFile(Vn))})))}let V=vn({source:Be,moduleSpecifier:b(R.entryFile,Ae),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:Z(y,J.AST_PARSE_ERROR,V.diagnostic.message)};let ee=W.files.map(Fe=>({operation:"create-only",file:Fe.path,content:Fe.content})),Se=[{operation:"upsert",file:R.entryFile,content:V.source,baseContentHash:Te(H)},...ee,...Ce];m+=1;try{let Fe=await Ir({request:y,filePlan:{operationId:y.id,kind:"source-edit",target:{kind:"source-file",path:R.entryFile},documentVersion:y.documentVersion,conflictPolicy:"compare-and-swap",edits:Se}});return!Fe.ok&&Fe.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Fe.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:Fe}}finally{m-=1}}});return te.ok?te.data:Z(y,te.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?J.MATERIALIZATION_CONFLICT:J.MATERIALIZATION_REJECTED,te.error.message,{materializationCode:te.error.code})}async function C_(y,R){if(y.kind!=="insert-child"&&y.kind!=="replace-node")return Z(y,J.UNSUPPORTED_OPERATION,"Only page-block insert-child and replace-node use this materialization transaction.");if(y.params.kind!==y.kind||y.kind==="replace-node"&&y.params.kind!=="replace-node"||y.kind==="insert-child"&&y.params.kind!=="insert-child")return Z(y,J.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let k=R.document,T=R.pageBlockIndex;if(!k||!T||T.diagnostics.length>0)return Z(y,J.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(y.documentVersion!==k.version||T.documentVersion!==k.version)return Z(y,J.VERSION_STALE,`Document version ${y.documentVersion} is stale (current: ${k.version}).`);let B=ni(T,y.target,y.documentVersion,y.selectionRef);if(!B.ok)return Z(y,sa(B.code),B.message);let j=B.binding;if(!(y.kind==="insert-child"?j.descriptor.capabilities.insert:j.descriptor.capabilities.replace)){let ce=j.descriptor.unavailableReasons?.[y.kind==="insert-child"?"insert":"replace"]?.reason??"The selected page block does not permit this operation.";return Z(y,J.UNSUPPORTED_OPERATION,ce)}let z=(y.kind==="insert-child",y.params);if(z.kind!==y.kind)return Z(y,J.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let te=z.node;if(te.kind!=="component-call"||!te.materialization)return Z(y,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 Z(y,J.INVALID_PARAMS,"Page-block insert-child requires a block-boundary position.");if(ce.documentVersion!==y.documentVersion)return Z(y,J.VERSION_STALE,"The block insertion boundary belongs to a different document version.");let Be=Pc(T,ce);if(!Be.ok)return Z(y,sa(Be.code),Be.message);W=Be.boundary}let H=te.materialization,ie=await Fi({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 Z(y,J.MATERIALIZATION_REJECTED,ie.message);let fe=await eI(n,Object.keys(H.projectDependencies??{})),Ae=await Kd({manifest:H,generatedRoot:"components/site/generated",controlledFiles:H.files.map(ce=>({pathTemplate:ce.pathTemplate})),exists:ce=>n.exists(ce),availableHostDependencies:fe,hostCapabilities:Td(),commit:async ce=>{let Be=R.document,Ce=R.pageBlockIndex;if(!Be||!Ce||Be.version!==y.documentVersion||Ce.documentVersion!==Be.version||!Ce.bindings.has(j.blockKey))return{ok:!0,data:Z(y,J.VERSION_STALE,"The route or selected block changed before materialization could commit.")};let V=Ce.bindings.get(j.blockKey);if(!V||V.ownerFile!==j.ownerFile||V.ownerSourceHash!==j.ownerSourceHash||V.sourceHash!==j.sourceHash)return{ok:!0,data:Z(y,J.VERSION_STALE,"The selected block owner or source changed before materialization could commit.")};let ee=new Set([j.ownerFile,j.descriptor.source.file,...W?[W.ownerFile,W.anchorLocator.file,...W.parentLocator?[W.parentLocator.file]:[]]:[]]),Se=new Map;try{for(let je of ee)Se.set(je,await n.readFile(je))}catch{return{ok:!0,data:Z(y,J.VERSION_STALE,"A selected owner, root, or boundary file is no longer readable.")}}let Fe=xb({operationId:y.id,documentVersion:y.documentVersion,target:y.target,binding:j,...W?{boundary:W}:{},operation:z.kind,materialization:ce,files:Se});if(!Fe.ok){let je=w_(Fe.code);return{ok:!0,data:Z(y,je,Fe.message,{materializationCode:Fe.code})}}m+=1;try{let je=await Ir({request:y,filePlan:Fe.plan});return!je.ok&&je.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:je.error.message||"Static prefab instance conflicted during commit."}}:{ok:!0,data:je}}finally{m-=1}}});return Ae.ok?Ae.data:Z(y,Ae.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?J.MATERIALIZATION_CONFLICT:J.MATERIALIZATION_REJECTED,Ae.error.message,{materializationCode:Ae.error.code})}async function N_(y,R){if(y.kind!=="move-node"&&y.kind!=="remove-node")return Z(y,J.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let k=R.document,T=R.pageCompositionProjection;if(!k||k.pageComposition?.status!=="supported"||!T||T.status!=="supported")return Z(y,J.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(y.documentVersion!==k.version||T.documentVersion!==k.version)return Z(y,J.VERSION_STALE,`Document version ${y.documentVersion} is stale (current: ${k.version}).`);let B=await n.readFile(R.entryFile),j=cf({routeId:R.routeId,composition:R.composition,entryFile:R.entryFile,currentDocumentVersion:k.version,expectedDocumentVersion:y.documentVersion,source:B,projection:T,placementUnitKey:y.target.placementUnitKey,operation:y.kind,targetPlacement:y.kind==="move-node"&&y.params.kind==="move-node"&&"kind"in y.params.target&&y.params.target.kind==="page-composition"?y.params.target:void 0});if(!j.ok)return Z(y,Eu(j.error.code),j.error.message,{diagnostics:j.error.diagnostics});let X=j.plan.rewriteStep,z;switch(X.kind){case"move-node":z=go({source:B,locator:X.locator,targetParentLocator:X.targetParentLocator,placement:X.placement,...X.anchorLocator?{anchorLocator:X.anchorLocator}:{}});break;case"remove-node":z=po({source:B,locator:X.locator});break;case"remove-root-expression":z=as({source:B,locator:X.locator,expectedSourceHash:X.sourceHash,action:{kind:"remove"}});break;default:z={ok:!1,source:B,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${X.kind}`}}}if(!z.ok)return Z(y,J.AST_PARSE_ERROR,z.diagnostic.message);let te=z.source,W=[];if(y.kind==="remove-node"){let ie=await hu({routeState:R,placementUnitKey:y.target.placementUnitKey,source:B,mutatedSource:te});te=ie.source,W=await Promise.all(ie.files.map(async fe=>({operation:"delete",file:fe,baseContentHash:Te(await n.readFile(fe))})))}let H=[{operation:"upsert",file:R.entryFile,content:te,baseContentHash:Te(B)},...W];m+=1;try{return await Ir({request:y,filePlan:{operationId:y.id,kind:"source-edit",target:{kind:"source-file",path:R.entryFile},documentVersion:y.documentVersion,conflictPolicy:"compare-and-swap",edits:H}})}finally{m-=1}}async function A_(y,R){if(y.kind!=="move-node"&&y.kind!=="remove-node")return Z(y,J.UNSUPPORTED_OPERATION,"Only page-block move-node and remove-node use this source transaction.");let k=R.document,T=R.pageBlockIndex;if(!k||!T||T.diagnostics.length>0)return Z(y,J.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(y.documentVersion!==k.version||T.documentVersion!==k.version)return Z(y,J.VERSION_STALE,`Document version ${y.documentVersion} is stale (current: ${k.version}).`);let B=ni(T,y.target,y.documentVersion,y.selectionRef);if(!B.ok)return Z(y,sa(B.code),B.message);let j=B.binding;if(j.documentVersion!==k.version)return Z(y,J.VERSION_STALE,"The resolved page-block binding is stale.");if(!(y.kind==="move-node"?j.descriptor.capabilities.move:j.descriptor.capabilities.remove)){let Ce=j.descriptor.unavailableReasons?.[y.kind==="move-node"?"move":"remove"]?.reason??"The selected block does not permit this operation.";return Z(y,J.UNSUPPORTED_OPERATION,Ce)}if(y.kind==="remove-node"){let Ce=[...i.values()].filter(V=>V.dependencyFiles.has(j.ownerFile));if(Ce.includes(R)||Ce.push(R),Ce.some(V=>!V.pageBlockIndex||V.pageBlockIndex.descriptors.length<=1))return Z(y,J.UNSUPPORTED_OPERATION,"The selected source is the last editable page block in an affected composition.")}let z=null;if(y.kind==="move-node"){if(y.params.kind!=="move-node"||!("kind"in y.params.target)||y.params.target.kind!=="block-boundary")return Z(y,J.INVALID_PARAMS,"Page-block move requires a block-boundary target.");if(y.params.target.anchorBlockKey===j.blockKey)return Z(y,J.INVALID_TARGET,"A page block cannot be moved relative to itself.");let Ce=Pc(T,y.params.target);if(!Ce.ok)return Z(y,sa(Ce.code),Ce.message);let V=T.bindings.get(y.params.target.anchorBlockKey);if(!V||!j.descriptor.siblingBlockKeys.includes(V.blockKey)||!V.descriptor.siblingBlockKeys.includes(j.blockKey)||V.ownerFile!==j.ownerFile||V.root.ownerNode.kind!==j.root.ownerNode.kind||V.root.ownerNode.key!==j.root.ownerNode.key||V.root.parentStructuralPath!==j.root.parentStructuralPath)return Z(y,J.INVALID_TARGET,"The selected block and boundary anchor are not verified same-owner source siblings.");if(z=Ce.boundary,z.ownerFile!==j.ownerFile||z.sourceHash!==j.ownerSourceHash||!z.parentLocator)return Z(y,J.INVALID_TARGET,"The move boundary does not belong to the selected block's source owner.")}let te=j.ownerFile,W=await n.readFile(te);if(Te(W)!==j.ownerSourceHash)return Z(y,J.VERSION_STALE,"The page-block owner source changed after resolution.");let H=j.descriptor.source.file===te?W:await n.readFile(j.descriptor.source.file);if(Te(H)!==j.descriptor.source.contentHash)return Z(y,J.VERSION_STALE,"The selected page-block source changed after resolution.");let ie=T_(j),fe=y.kind==="remove-node"?po({source:W,locator:ie}):go({source:W,locator:ie,targetParentLocator:gu(z.parentLocator),anchorLocator:gu(z.anchorLocator),placement:z.placement});if(!fe.ok)return Z(y,J.AST_PARSE_ERROR,fe.diagnostic.message);let Ae=fe.source,ce=[];if(y.kind==="remove-node"&&j.root.ownerNode.kind==="route-member"&&j.root.callChain.length>0&&j.descriptor.placementUnitKey){let Ce=await hu({routeState:R,placementUnitKey:j.descriptor.placementUnitKey,source:W,mutatedSource:Ae});Ae=Ce.source,ce=Ce.files}let Be=[{operation:"upsert",file:te,content:Ae,baseContentHash:j.ownerSourceHash},...await Promise.all(ce.map(async Ce=>({operation:"delete",file:Ce,baseContentHash:Te(await n.readFile(Ce))})))];m+=1;try{return await Ir({request:y,filePlan:{operationId:y.id,kind:"source-edit",target:y.target,documentVersion:y.documentVersion,conflictPolicy:"compare-and-swap",edits:Be}})}finally{m-=1}}function T_(y){return gu(y.ownerLocator)}function gu(y){return{kind:"jsx-node",strategy:"source-range",sourceRange:y.sourceRange,...y.structuralPath&&y.componentName?{expectedIdentity:{file:y.file,component:y.componentName,structuralPath:y.structuralPath}}:{}}}function sa(y){return y==="VERSION_STALE"?J.VERSION_STALE:y==="INVALID_PARAMS"?J.INVALID_PARAMS:J.INVALID_TARGET}function w_(y){return y==="VERSION_STALE"?J.VERSION_STALE:y==="INVALID_PARAMS"?J.INVALID_PARAMS:y==="INVALID_TARGET"?J.INVALID_TARGET:y.startsWith("MATERIALIZATION_")?J.MATERIALIZATION_REJECTED:J.UNSUPPORTED_OPERATION}async function hu(y){let R={source:y.mutatedSource,files:[]},k=y.routeState.graph,T=y.routeState.pageCompositionProjection;if(!k||!T||T.status!=="supported"||!n.listFiles)return R;let j=T.placementUnitByKey.get(y.placementUnitKey)?.sourceRange;if(!j)return R;let X=[...k.elements.values()].find(V=>V.sourceFile===y.routeState.entryFile&&V.importedFrom&&S(V.sourceRange,j));if(!X?.importedFrom||!X.exportName)return R;let z=E(X.importedFrom),te="components/site/generated/";if(!z.startsWith(te))return R;let W=z.slice(te.length).split("/")[0];if(!W||!/-[0-9a-f]{8}$/i.test(W))return R;let H=`${te}${W}`;if([...k.elements.values()].filter(V=>V.sourceFile===y.routeState.entryFile&&E(V.importedFrom??"")===z).length!==1)return R;let fe=await n.listFiles({maxFiles:5e3,maxDepth:32}),Ae=Array.isArray(fe)?fe:fe.files;if(!Array.isArray(fe)&&fe.truncated)return R;let ce=Ae.map(({path:V})=>V).filter(V=>V===H||V.startsWith(`${H}/`));if(ce.length===0||!ce.includes(z))return R;for(let{path:V}of Ae)if(!(V===y.routeState.entryFile||V===H||V.startsWith(`${H}/`)))try{if((await n.readFile(V)).includes(W))return R}catch{return R}let Be=b(y.routeState.entryFile,z),Ce=Vo({source:y.mutatedSource,moduleSpecifier:Be,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))}:R}async function O_(y){if(n.getFileInfo){for(let X of y)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 y){if(X.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(X.path))continue;let z=await n.exists(X.path)?await Du(n,X.path):null;if(z?.ok){let te=qM(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=F_(y);if(R.length===0)return{ok:!0};let k=SB(n,y),T=new Map,B=(X,z)=>{let te=T.get(X);if(te?.source===z)return te.result;let W=Ee(X,z);return T.set(X,{source:z,result:W}),W},j;try{j=await $v(R,async X=>{let z=i.get(X);return z?[...(await K(z.entryFile,await k.readFile(z.entryFile),k,{validationOnly:!0,parseModule:B,validatedImports:f.getImports})).parsedModules.values()]:[]})}catch(X){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Ht(X)}`,details:{compositionKeys:R}}}for(let X of j)f.remember(X);return{ok:!0}}function F_(y){return y.map(k=>k.path).some(aI)?[...i.keys()]:[]}function yu(y,R,k,T){let B=Js(R);return{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!1,resultVersion:G(y),error:{code:B,message:k,...T?{details:T}:{}}}}async function xu(y){let R=[];for(let k of new Set(y))R.push(await L_(k));return R}async function L_(y){if(!(typeof n.exists=="function"?await n.exists(y):!0))return{file:y,content:"",version:Math.max(0,D(y)),exists:!1};let k=await n.readFile(y);return{file:y,content:k,version:Math.max(1,D(y)),exists:!0,sha256:Te(k)}}async function Ag(y,R,k,T){if(!e.historyStore)return null;let B=new Map(R.map(z=>[z.file,z])),j=new Map(k.map(z=>[z.file,z])),X=[...new Set([...B.keys(),...j.keys()])].sort().map(z=>{let te=B.get(z),W=j.get(z);return{path:z,preDigest:te?.exists===!1||!te?null:Te(te.content),postDigest:W?.exists===!1||!W?null:Te(W.content)}});return{schemaVersion:2,transactionId:`${y}:${T.expectedIndexDigest}`,operationId:y,phase:"prepared",historyTransition:T,files:X}}async function Tg(y){return!y||!e.historyStore||await e.historyStore.writeTransactionJournal(y),y}async function Mo(y){y&&e.historyStore&&await e.historyStore.clearTransactionJournal(y.transactionId)}async function bu(y,R){let k=[];try{for(let T of y)await wg(T),typeof n.bumpVersion=="function"&&n.bumpVersion(T.file),k.push(T.file)}catch(T){let B=await D_(R.filter(j=>k.includes(j.file)));return B.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Ht(T)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${B.failedFiles.join(", ")}: ${Ht(T)}`,rolledBack:!1}}return{ok:!0,snapshots:y.map(M_)}}async function wg(y){if(y.exists===!1){await n.deleteFile(y.file);return}await n.writeFile(y.file,y.content)}async function D_(y){let R=[];for(let k of y)try{await wg(k),typeof n.bumpVersion=="function"&&n.bumpVersion(k.file)}catch{R.push(k.file)}return R.length===0?{ok:!0}:{ok:!1,failedFiles:R}}function M_(y){let R=y.exists!==!1;return{file:y.file,content:R?y.content:"",version:y.version,exists:R,...R?{sha256:Te(y.content)}:{}}}async function Ir(y){return h.runExclusive(()=>B_(y))}async function B_(y){let R=y.filePlan.edits.map(V=>V.file),k=o.resolveSelector(y.request.composition),T=k.context,B=y.historyPolicy==="none"?void 0:{initiatingComposition:T,affectedCompositions:he(R)},j=await xu(R),X=new Map(j.filter(V=>V.exists!==!1).map(V=>[V.file,V.content])),z=Fg(),te=new Map(d),W=new Set(g),H=new Set([...i.values()].filter(V=>y.filePlan.edits.some(ee=>ee.operation==="delete"&&ee.file===V.entryFile)).map(V=>V.key)),ie=y.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:Te(V.content)}),fe={operationId:y.filePlan.operationId,intents:y.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})},Ae=null,ce=!1,Be=await _l({overlay:X,exists:V=>n.exists(V),plan:fe,buildCandidate:async({plan:V})=>({plan:V}),prepareHistory:async()=>{let V=y.historyPolicy==="none"?null:await c.prepareAppend({composition:o.resolveSelector(y.request.composition).context,operationId:y.request.id,kind:y.request.kind,target:y.request.target,preSnapshots:j,postSnapshots:ie,...y.selectionRef?{selectionRef:y.selectionRef}:{},...y.output?{output:y.output}:{},...B?{provenance:B}:{}}),ee=V?.historyTransition?V.historyTransition:e.historyStore?aB(await e.historyStore.readIndex()):null;if(e.historyStore&&!ee)throw new Error("Durable history did not provide an exact index transition.");return Ae=await Ag(y.request.id,j,ie,ee),Ae=await Tg(Ae),{history:V,historyTransition:ee}},reverify:async()=>{},writeCandidate:async()=>{let V=await u.executeFilePlan(y.filePlan);if(!V.ok)throw new wl(V);return{postSnapshots:await xu(V.affectedFiles),affectedFiles:V.affectedFiles,internalResultVersion:V.resultVersion}},validateCandidate:async({candidate:V,receipt:ee})=>{let Se=await pe(ee.affectedFiles,{changed:!0,minimumVersion:ee.internalResultVersion,publish:!1,excludedCompositionKeys:H});if(Se.failedRoutes.length>0)throw new To(Se.failedRoutes);let Fe=Dg(z,Se.candidateRouteStates??[]),je=Lg(Fe,k.key);return{...V,rebuild:Se,routeSnapshots:Fe,resultVersion:je,...rI(y.selectionRef,Fe.map(ut=>ut.state.document))?{selectionRef:rI(y.selectionRef,Fe.map(ut=>ut.state.document))}:{}}},publishCandidate:async({candidate:V,history:ee,receipt:Se})=>{ee?.history&&(await c.publishPrepared(ee.history),ce=!0);let Fe=V.resultVersion??Se.internalResultVersion;return{composition:T,requestId:y.request.id,kind:y.request.kind,target:y.request.target,ok:!0,resultVersion:Fe,affectedFiles:Se.affectedFiles,fileChanges:Se.postSnapshots.map(je=>({path:je.file,operation:je.exists===!1?"delete":"upsert"})),...y.output?{output:y.output}:{},...V.selectionRef?{selectionRef:V.selectionRef}:{}}},swapCandidate:({candidate:V,receipt:ee})=>{V.routeSnapshots&&aa(V.routeSnapshots),V.rebuild?.candidateSourceCache&&Ks(d,V.rebuild.candidateSourceCache),Rg(ee.postSnapshots)},finalizeCandidate:async()=>{await Mo(Ae);for(let V of H)i.delete(V)},emitCommitted:({candidate:V,published:ee})=>{Un(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 Se=await bu(j,ee.postSnapshots);if(!Se.ok)throw new Error(Se.reason)}aa(z),Ks(d,te),Pg(W),V?.history&&await c.discardPrepared?.(V.history),await Mo(Ae)}});if(Be.ok)return Be.published;if(Be.stage==="precheck"||Be.stage==="build")try{await Mo(Ae)}catch(V){let ee=await la(Ht(V));return Z(y.request,ee,"Unable to clear an uncommitted transaction journal.")}if(Be.recoveryRequired){let V=await la(Be.reason);return Z(y.request,V===J.RECOVERY_PERSIST_FAILED?V:J.ROLLBACK_FAILED,Be.reason)}let Ce=Be.error;return Ce instanceof wl?{...Z(y.request,Js(Ce.result.errorCode),Ce.result.reason),...Ce.result.affectedFiles?{affectedFiles:Ce.result.affectedFiles}:{}}:Ce instanceof To?Z(y.request,J.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${sm(Ce.failedRoutes)}`,{failedRoutes:Ce.failedRoutes}):Z(y.request,Bg(Be.stage),Ht(Ce))}async function Og(y){return h.runExclusive(async()=>{let R=y==="undo"?await c.prepareUndo():await c.prepareRedo();return R?j_(y,R):{composition:o.entries[0].context,requestId:y,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:J.INTERNAL_ERROR,message:y==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function j_(y,R){let k=R.entry,T=y==="undo"?k.preSnapshots:k.postSnapshots,B=y==="undo"?k.postSnapshots:k.preSnapshots,j=T.map(ee=>ee.file),{context:X,key:z}=kt(k,j),te=await xu(j),W=new Map(te.filter(ee=>ee.exists!==!1).map(ee=>[ee.file,ee.content])),H=M(z),ie=Fg(),fe=new Map(d),Ae=new Set(g),ce=null,Be=!1,Ce,V=await _l({overlay:W,plan:{operationId:`${y}:${k.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 Ag(`${y}:${k.operationId}`,te,T,R.historyTransition),ce=await Tg(ce),R),reverify:async()=>{},writeCandidate:async()=>{let ee=await bu(T,B);if(!ee.ok)throw new Error(ee.reason);return{snapshots:ee.snapshots}},validateCandidate:async({candidate:ee})=>{Ce=Le(k,j);let Se=await pe(j,{changed:!0,minimumVersion:H+1,publish:!1,affectedCompositionKeys:Ce});if(Se.failedRoutes.length>0)throw new To(Se.failedRoutes);let Fe=Dg(ie,Se.candidateRouteStates??[]),je=Lg(Fe,z);return{...ee,rebuild:Se,routeSnapshots:Fe,resultVersion:je}},publishCandidate:async({candidate:ee,history:Se,receipt:Fe})=>{if(!Se)throw new Error("history cursor intent is missing");await c.publishPrepared(Se),Be=!0;let je=ee.resultVersion??H+1;return{composition:X,requestId:y,kind:k.kind,target:k.target,ok:!0,resultVersion:je,affectedFiles:j,fileChanges:Fe.snapshots.map(ut=>({path:ut.file,operation:ut.exists===!1?"delete":"upsert"})),...k.output?{output:k.output}:{}}},swapCandidate:({candidate:ee,receipt:Se})=>{ee.routeSnapshots&&aa(ee.routeSnapshots),ee.rebuild?.candidateSourceCache&&Ks(d,ee.rebuild.candidateSourceCache),Rg(Se.snapshots)},finalizeCandidate:async()=>{await Mo(ce)},emitCommitted:({candidate:ee,published:Se})=>Un(Se,ee.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:ee,receipt:Se})=>{if(Be)throw new Error("history cursor was published before transaction finalization failed");if(Se){let Fe=await bu(B,Se.snapshots);if(!Fe.ok)throw new Error(Fe.reason)}aa(ie),Ks(d,fe),Pg(Ae),ee&&await c.discardPrepared?.(ee),await Mo(ce)}});if(V.ok)return V.published;if(V.stage==="precheck"||V.stage==="build")try{await Mo(ce)}catch(ee){let Se=await la(Ht(ee));return{composition:X,requestId:y,kind:k.kind,target:k.target,ok:!1,resultVersion:H,error:{code:Se,message:"Unable to clear an uncommitted transaction journal."}}}if(V.recoveryRequired){let ee=await la(V.reason);return{composition:X,requestId:y,kind:k.kind,target:k.target,ok:!1,resultVersion:H,affectedFiles:j,error:{code:ee===J.RECOVERY_PERSIST_FAILED?ee:J.ROLLBACK_FAILED,message:V.reason}}}return{composition:X,requestId:y,kind:k.kind,target:k.target,ok:!1,resultVersion:H,affectedFiles:j,error:{code:V.error instanceof To?J.ROUTE_REBUILD_FAILED:Bg(V.stage),message:Ht(V.error),...V.error instanceof To?{details:{failedRoutes:V.error.failedRoutes}}:{}}}}function Fg(){return[...i.values()].map(y=>({composition:y.composition,key:y.key,routeId:y.routeId,state:{...y,dependencyFiles:new Set(y.dependencyFiles),fileVersions:new Map(y.fileVersions)}}))}function Lg(y,R){return y.find(T=>T.key===R)?.state.graph?.version??o.initialVersions.get(R)??0}function Dg(y,R){let k=new Map(y.map(T=>[T.key,T]));for(let T of R)k.set(T.key,T);return[...k.values()]}function aa(y){for(let R of i.values())C(R);for(let R of y){let k={...R.state,dependencyFiles:new Set(R.state.dependencyFiles),fileVersions:new Map(R.state.fileVersions)};i.set(R.key,k),I(k,k.dependencyFiles)}}async function ca(y){let R=i.get(y);if(!R)throw new Error(`Composition not found: ${y}`);if(R.graph)return;let k=await n.readFile(R.entryFile);await ge(y,k)}function Bo(y,R){let k=i.get(o.resolveSelector(R).key)??null;return!k||!Mg(k,y)?null:k}function Mg(y,R){if(y.documentIndex?.entriesByKey.has(R)||y.graph?.elements.has(R))return!0;let k=en(R);return k&&k!==R?y.graph?.elements.has(k)===!0:!1}function Z(y,R,k,T){return{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!1,resultVersion:G(y),error:{code:R,message:k,...T?{details:T}:{}}}}function Bg(y){return y==="validate"?J.ROUTE_REBUILD_FAILED:y==="publish"?J.HISTORY_COMMIT_FAILED:J.WRITE_IO_ERROR}async function la(y){if(p=!0,!c.markRecoveryRequired)return J.RECOVERY_REQUIRED;try{return await c.markRecoveryRequired(y),J.RECOVERY_REQUIRED}catch{return J.RECOVERY_PERSIST_FAILED}}function $_(y){let k=y.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(T=>T.charAt(0).toUpperCase()+T.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return k?`Prefab${k}`:"GeneratedPrefab"}function Eu(y){return y==="VERSION_STALE"?J.VERSION_STALE:y==="CROSS_PAGE_MOVE_UNSUPPORTED"?J.CROSS_PAGE_MOVE_UNSUPPORTED:J.UNSUPPORTED_OPERATION}async function jg(y){if(y.target.kind==="route"){let k=i.get(o.resolveSelector(y.target.composition).key)??null;return k?(k.graph||await ca(k.key),k):Z(y,J.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(y.target.kind==="page-unit"){let k=i.get(o.resolveSelector(y.target.composition).key)??null;return k?(k.graph||await ca(k.key),k):Z(y,J.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(y.target.kind==="page-block"){let k=i.get(o.resolveSelector(y.target.composition).key)??null;return k?(k.graph||await ca(k.key),k):Z(y,J.ROUTE_NOT_FOUND,"Composition not found for page-block target.")}if(y.target.kind!=="node")return Z(y,J.UNSUPPORTED_OPERATION,`${y.kind} source target execution is not implemented yet.`);let R=i.get(o.resolveSelector(y.composition).key)??null;return R?(R.graph||await ca(R.key),Mg(R,y.target.key)?R:Z(y,J.NODE_NOT_FOUND,`Target key not found: ${y.target.key}`)):Z(y,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(y,R){let k=o.register({context:y,entryFile:R}),T=i.get(k.key);if(T?.entryFile===R)return;T&&C(T);let B=nI(k.context,R);i.set(k.key,B),I(B,B.dependencyFiles),r.emit({type:"graph-invalidated",composition:k.context})},unregisterComposition(y){let R=o.resolveSelector(y),k=i.get(R.key);k&&(C(k),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(y=>y.entryFile)},getCompositionContext(y){return o.resolveSelector(y).context},async initializeComposition(y){let R=o.resolveSelector(y),k=i.get(R.key);if(!k)throw new Error(`Composition not registered: ${R.key}`);if(k.graph)t="ready";else{t="building";try{let T=await n.readFile(k.entryFile);await ge(R.key,T),t="ready",r.emit({type:"graph-ready",composition:R.context,version:i.get(R.key)?.graph?.version??0})}catch(T){throw t="idle",r.emit({type:"graph-error",composition:R.context,message:Ht(T)}),T}}},getDocument(y){let R=o.resolveSelector(y),k=i.get(R.key);if(!k)throw new Error(`Composition not registered: ${R.key}`);if(!k.document)throw new Error(`Composition not built: ${R.key}`);return k.document},async getHistoryStatus(){await x;let y=await c.getStatus?.();return y?{...y,recoveryRequired:p}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:p}},getObjectEditContext(y,R,k){let T=Bo(y,R),B=en(y)??y;if(T?.graph&&T.topology&&T.capabilities&&T.detailProjections){let j=T.detailProjections.get(B);if(j){let X=T.graph.elements.get(B);if(!X)throw new Error(`Key not found: ${y}`);let z=pB(y,B,k),te=new Map;if(j.isRepeat&&z?.instanceIndex!==void 0)for(let ie of X.attributes??[])te.set(ie.name,Lp({file:X.sourceFile,source:d.get(X.sourceFile)??"",element:X,propertyName:ie.name,selectionRef:z,graph:T.graph,sources:d}));let W=bv({element:X,graph:T.graph,source:d.get(X.sourceFile),documentVersion:T.graph.version,selectionRef:k,isRepeat:j.isRepeat,propertyProvenance:j.propertyProvenances,repeatTargets:te}),H=vv(B,T.graph,T.topology,T.capabilities,j.textSources,j.provenances,j.dynamicData,W);return y===B?H:Hv(H,y,T.document??null,T.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${y}`)},getRenderDetail(y,R){let k=Bo(y,R),T=en(y)??y;if(k?.graph&&k.topology&&k.capabilities&&k.detailProjections){let B=k.detailProjections.get(T);if(B){let j=Sv(T,k.graph,k.topology,k.capabilities,B.textSources,B.writeTarget,B.provenances,B.conditional,B.componentSemantic,B.styleSource,B.dynamicData);return y===T?j:zv(j,y,k.document??null,k.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${y}`)},getClassNameSource(y,R){let k=Bo(y,R),T=en(y)??y;if(!k?.graph)throw new Error(`Key not found: ${y}`);let B=k.graph.elements.get(T);if(!B)throw new Error(`Key not found: ${y}`);let j=d.get(B.sourceFile);if(j===void 0)throw new Error(`Source not loaded: ${B.sourceFile}`);return td({key:T,route:{composition:k.composition,routeId:k.routeId,graph:k.graph,source:j}})},refreshSourceForKey:I_,async execute(y){if(await x,p)return Z(y,J.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(y.kind==="source-edit")return k_(y);if(y.kind==="insert-page-resource")return __(y);if(y.kind==="delete-page-source")return R_(y);let R=await jg(y);if("ok"in R)return R;await Ng(y);let k=await jg(y);if("ok"in k)return k;let T=k;if(y.target.kind==="page-unit"){let H=y;return y.kind==="insert-child"||y.kind==="replace-node"?P_(H,T):y.kind==="move-node"||y.kind==="remove-node"?N_(H,T):Z(y,J.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}if(y.target.kind==="page-block"){let H=y;return y.kind==="insert-child"||y.kind==="replace-node"?C_(H,T):y.kind==="move-node"||y.kind==="remove-node"?A_(H,T):Z(y,J.UNSUPPORTED_OPERATION,"Page-block operation is not supported by the current structural transaction.")}let j=y.params,X=y.target.kind==="node"?y.target.key:null;if(j.kind==="move-node"&&"kind"in j.target&&j.target.kind==="source-sibling"){let H=j.target,ie=X?T.document?.entries.find(ee=>ee.key===X):null,fe=T.document?.entries.find(ee=>ee.key===H.anchorKey),Ae=ie?.pageCompositionActionScope,ce=Ae?.kind==="source-siblings"?Ae.siblingKeys:null,Be=ce?.indexOf(ie?.key??"")??-1,Ce=ce?.indexOf(H.anchorKey)??-1,V=H.relation==="before"?Be-1:Be+1;if(!ie||!fe||!ce||Be<0||Ce!==V||fe.pageCompositionActionScope?.kind!=="source-siblings"||fe.pageCompositionActionScope.siblingKeys.length!==ce.length||fe.pageCompositionActionScope.siblingKeys.some((ee,Se)=>ee!==ce[Se])||!ie.operationSummary.canMove)return Z(y,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(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!1,resultVersion:G(y),error:{code:y.target.kind==="route"?J.ROUTE_NOT_FOUND:J.NODE_NOT_FOUND,message:y.target.kind==="route"?"Composition not ready for route target.":y.target.kind==="node"?`Target key not found: ${y.target.key}`:`${y.kind} source target execution is not implemented yet.`}};let z=TB(T,T.graph,T.capabilities,d,i),te=await new Qc(z).plan(y);if(!te.ok)return{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!1,resultVersion:G(y),error:{code:Js(te.errorCode),message:te.reason}};let W=te.plan;if(W.steps.length===0)return y.kind==="set-props"?{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!0,resultVersion:G(y),affectedFiles:[]}:{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!1,resultVersion:G(y),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 Z(y,Js(ie.errorCode),ie.reason);let fe={composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!0,resultVersion:Math.max(G(y),ie.resultVersion),affectedFiles:ie.affectedFiles,...ie.selectionRef?{selectionRef:ie.selectionRef}:{}};return Un(fe,{rebuiltRoutes:[],failedRoutes:[]}),fe}let H=await u.prepareRewritePlan(W);return H.ok?await Ir({request:y,filePlan:H.filePlan,...H.selectionRef?{selectionRef:H.selectionRef}:{}}):Z(y,Js(H.errorCode),H.reason)}catch(H){return{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!1,resultVersion:G(y),error:{code:J.INTERNAL_ERROR,message:Ht(H)}}}finally{m-=1}},async undo(y){if(await x,p)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:M(o.entries[0].key),error:{code:J.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};m+=1;try{return await Og("undo")}finally{m-=1}},async redo(y){if(await x,p)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:M(o.entries[0].key),error:{code:J.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};m+=1;try{return await Og("redo")}finally{m-=1}},notifyFileChanged(y){kg([y])},getAffectedCompositions(y){return ae(y)},subscribe(y){return r.subscribe(y)}}}function kB(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function _B(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},l=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&&Xs(d.sourceRange,p.sourceRange)));if(!f)continue;let g=f.placementUnitKey;a(d,g)}let c=!0;for(;c;){c=!1;for(let d of t.elements.values()){if(d.sourceFile===n.entryFile||!d.importedFrom||!/^[A-Z]/.test(d.tag))continue;let f=l(d);if(f)for(let g of f)c=a(d,g)||c}}let u=n.placements.find(d=>d.placementKey===n.container.placementKey&&d.relation==="append");for(let d of e.entries){let f=en(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&&Xs(g.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let h=n.placements.find(x=>x.members.some(E=>E.sourceRange!==null&&(Xs(g.sourceRange,E.sourceRange)||AB(E.sourceRange,g.sourceRange))));if(h){d.pageCompositionUnitKey=h.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)}RB(e,t,n,r)}function RB(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))},l=f=>n.placements.some(g=>g.members.some(m=>m.sourceRange!==null&&Xs(f.sourceRange,m.sourceRange)));for(let f of t.elements.values())f.sourceFile!==n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag)||!l(f)||a(`${f.importedFrom}#${f.exportName??f.tag}`,1);let c=[...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<=c.length;f+=1){let g=!1;for(let m of c){let p=s.get(m.owner)??s.get(m.ownerDefault)??0;if(!p)continue;let h=s.get(m.target)??0,x=Math.min(2,h+p);x!==h&&(s.set(m.target,x),g=!0)}if(!g)break}let u=f=>s.get(`${f.sourceFile}#${f.componentName}`)??s.get(`${f.sourceFile}#default`)??0;for(let f of i){f.pageCompositionActionScope={kind:"unavailable"};let g=t.elements.get(f.key);f.pageCompositionUnitKey&&g?.sourceFile===n.entryFile&&(f.pageCompositionActionScope={kind:"route-unit"})}let d=new Map;for(let f of i){let g=t.elements.get(f.key);if(!g||g.sourceFile===n.entryFile||f.key!==(en(f.key)??f.key))continue;let m=r.get(g.sourceFile);if(!m)continue;let p=Ne(m.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:g.sourceRange});if(!p.ok||!p.match.path.isJSXElement())continue;let h=p.match.path,x=h.parentPath;if(!x||!x.isJSXFragment()&&!(x.isJSXElement()&&it(x))){u(g)===1&&iI(h)&&(f.pageCompositionActionScope={kind:"route-unit"});continue}if(!iI(x))continue;let E=d.get(x.node)??[];E.push({entry:f,element:g,parentPath:x}),d.set(x.node,E)}for(let f of d.values()){let g=f[0];if(!g)continue;let m=g.entry.pageCompositionUnitKey,p=[],h=!!(m&&u(g.element)===1);for(let E of g.parentPath.node.children){if(PB(E))continue;if(!CB(E)){h=!1;break}let b=[...t.elements.values()].find(v=>v.sourceFile===g.element.sourceFile&&v.componentName===g.element.componentName&&Xs(v.sourceRange,NB(E))),S=b?o.get(b.identity.key):null;if(!b||!S||S.parentKey||S.pageCompositionUnitKey!==m||u(b)!==1){h=!1;break}p.push(S)}if(!h||p.length!==f.length||f.some(({entry:E})=>!p.some(b=>b.key===E.key)))continue;if(p.length===1){p[0].pageCompositionActionScope={kind:"route-unit"};continue}if(p.length<2)continue;let x=p.map(E=>E.key);for(let E of p)E.pageCompositionActionScope={kind:"source-siblings",siblingKeys:x}}}function iI(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function PB(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function CB(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function NB(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 Xs(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function AB(e,t){return sI(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&sI(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function sI(e,t,n,r){return e!==n?e-n:t-r}function TB(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=l(u),f=t.elements.get(d.baseKey);return f?c(u,f):null},getChildNodes(u){let d=l(u),g=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(g)return g.map(p=>{let h=en(p)??p,x=t.elements.get(h);return x?c(p,x):null}).filter(p=>p!==null);let m=t.elements.get(d.baseKey);return m?m.childKeys.map(p=>{let h=t.elements.get(p);return h?c(p,h):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=l(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=l(u);return e.detailProjections?.get(d.baseKey)?.componentSemantic??null},getClassNameSource(u){let d=l(u),f=t.elements.get(d.baseKey),g=f?r.get(f.sourceFile):void 0;return!f||g===void 0?null:td({key:d.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:g}})},getEditableTextSegmentIndex(u){let d=l(u),g=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return g&&!g.done?g.value:null},async getTextWriteTarget(u,d){let f=l(u);return im(e.detailProjections?.get(f.baseKey)?.textTargets.get(d)??null,f.repeatIndex)},async getElementPropertyWriteTarget(u,d){let f=l(u);return im(e.detailProjections?.get(f.baseKey)?.elementPropertyTargets.get(d)??null,f.repeatIndex)},getPropertyState(u,d,f){let g=l(u),m=t.elements.get(g.baseKey);if(!m)return null;let h=e.detailProjections?.get(g.baseKey)?.propertyProvenances.get(d);if(h)return h;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,f){let g=l(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 Lp({file:m.sourceFile,source:r.get(m.sourceFile)??"",element:m,propertyName:d,selectionRef:p,graph:t,sources:r})},getTextProvenance(u,d){let f=l(u);return e.detailProjections?.get(f.baseKey)?.provenances.get(d)??null}};function l(u){let d=nB(u);return d?{baseKey:d.baseKey,repeatIndex:Xv(e.document??null,u,d.baseKey,e.documentIndex)??Jv(d)}:{baseKey:u,repeatIndex:null}}function c(u,d){let f=en(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 wB={"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 Js(e){return wB[e]}function Ht(e){return e instanceof Error&&e.message?e.message:String(e)}function aI(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function OB(e){let t=wo(e);if(!iB.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=>sB.map(a=>`${s}/${a}`))}function FB(e){let n=wo(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function LB(e){return uI(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function DB(e){return uI(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function uI(e,t){let n=[];for(let r of e.matchAll(t)){let o=dI(r[1]??"");o&&n.push(o)}return n}function cI(e,t){let n=dI(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?wo(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?wo(`${MB(e)}/${n}`):n.startsWith("/")?wo(n.slice(1)):cm(n)?wo(n):null}function dI(e){return e.split(/[?#]/,1)[0]?.trim()??""}function cm(e){return/\.css$/i.test(e)}function MB(e){let t=wo(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function BB(e){return Array.from(new Set(e))}function wo(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,""),n=[];for(let r of t.split("/"))if(!(!r||r===".")){if(r===".."){n.pop();continue}n.push(r)}return n.join("/")}function jB(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 Fl=class{constructor(t){this.options=t,this.fileSystem=new Li(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return ha(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 ya(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Ea(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Sa(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return va(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=UB.safeParse(t);if(!n.success)return{result:ga(t,n.error.issues.map(i=>i.message))};let r=new Li(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:lo(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let l=VB.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(c=>KB(c,t.kind==="source-edit")),changedCompositions:o.getAffectedCompositions(a.map(c=>c.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:l.patches.map(c=>c.path),composition:i.composition,at:new Date().toISOString()}),{result:s,patchPlan:l}}finally{o.dispose()}}dispose(){this.engine.dispose()}createEngine(t,n={}){let r=n.emitEvents??!0;return Ol({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=xa(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 KB(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:Te(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:Te(e.before)},fullContent:e.after}}function JB(e){return new Fl(e)}import{SiteEditOperationRequestSchema as HB}from"@vcp-dev/contracts";import $n from"node:fs/promises";import Wt from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as XB,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as zB}from"@vcp-dev/contracts";var Ll=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Ol({...t,fileSystem:this.fileSystem})}get status(){return this.engine.status}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return this.engine.getDocument(t)}getAffectedCompositions(t){return this.engine.getAffectedCompositions(t)}getCompositionContext(t){return this.engine.getCompositionContext(t)}initializeComposition(t){return this.engine.initializeComposition(t)}getHistoryStatus(){return this.engine.getHistoryStatus()}getObjectEditContext(t,n,r){return r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n)}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Ea(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Sa(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return va(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 $n.readFile(Wt.join(n,r),"utf8")},async readFileBytes(r){return $n.readFile(Wt.join(n,r))},async getFileInfo(r){let o=Wt.join(n,...r.split("/"));try{let i=await $n.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await Ua(Wt.join(n,r),o)},async createExclusive(r,o){let i=Wt.join(n,r);await $n.mkdir(Wt.dirname(i),{recursive:!0});let s=await $n.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await $n.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await $n.rm(Wt.join(n,r),{force:!0});let o=r.replace(/\\/g,"/"),i=["components/site/generated","src/components/site/generated"].find(l=>o.startsWith(`${l}/`));if(!i)return;let s=Wt.join(n,i),a=Wt.dirname(Wt.join(n,o));for(;a!==s&&a.startsWith(`${s}${Wt.sep}`);){try{await $n.rmdir(a)}catch(l){if(l instanceof Error&&"code"in l&&l.code==="ENOENT"){a=Wt.dirname(a);continue}break}a=Wt.dirname(a)}},async exists(r){try{return await $n.access(Wt.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...zB,...XB],i=[],s=new Set,a=new Set,l=0;for(let d of o)await u(d,i,1);let c=i.sort((d,f)=>d.path.localeCompare(f.path));return a.size>0?{files:c,truncated:{reasons:[...a]}}:{files:c};async function u(d,f,g){if(r.maxDepth!==void 0&&g>r.maxDepth){a.add("max-depth");return}let m=Wt.join(n,...d.split("/")),p;try{p=await $n.lstat(m)}catch{return}if(p.isSymbolicLink())return;if(p.isFile()){let x=p.ino>0?`${String(p.dev)}:${String(p.ino)}`:null;if(x&&s.has(x))return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&l+p.size>r.maxTotalBytes){a.add("max-total-bytes");return}x&&s.add(x),f.push({path:d,sizeBytes:p.size}),l+=p.size;return}if(!p.isDirectory())return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}let h=await $n.readdir(m,{withFileTypes:!0});for(let x of h)x.isSymbolicLink()||await u(`${d}/${x.name}`,f,g+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function lm(e){return new Ll(e)}var Dl=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=lm({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=xa(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:ha(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:ya(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=HB.safeParse(r);if(!o.success)return ga(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:lo(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:lo(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:lo(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 WB(e){return new Dl(e)}import{GeneratedSiteCapabilitiesSchema as ej}from"@vcp-dev/contracts";import{GeneratedSiteCapabilitiesSchema as GB}from"@vcp-dev/contracts";function Si(e){let t=ZB(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)?Sr(e.node,"platform-managed","controlled platform package"):t?qB(e.node.path,t)?Sr(e.node,"host-public","declared Starter runtime dependency"):Sr(e.node,"unsupported-external-private","external package is not declared by the trusted Starter contract"):Sr(e.node,"unknown","trusted host capability contract is invalid"):fI(e.node.path,n)?Sr(e.node,"platform-managed","controlled platform path"):t?mI(e.node.path,t.generated_sections_path)?Sr(e.node,"private","site-generated section path"):fI(e.node.path,t.public_paths)?Sr(e.node,"host-public","declared Starter public path"):Sr(e.node,"private","site-local file outside host public paths"):Sr(e.node,"unknown","trusted host capability contract is invalid")}function YB(e){return e.nodes.map(t=>Si({...e,node:t})).sort((t,n)=>t.path===n.path?t.ownership.localeCompare(n.ownership):t.path.localeCompare(n.path))}function Sr(e,t,n){return{path:e.path,kind:e.kind,ownership:t,reason:n}}function ZB(e){let t=GB.safeParse(e);return t.success?t.data:null}function qB(e,t){return t.runtime_dependencies.some(({name:n})=>e===n||e.startsWith(`${n}/`))}function fI(e,t){return t.some(n=>mI(e,n))}function mI(e,t){let n=QB(t),r=gI(e);return n.endsWith("/*")?r.startsWith(n.slice(0,-1)):pI(r)===pI(n)}function QB(e){return gI(e.split("#",1)[0]??e)}function gI(e){return e.replace(/^@\//u,"").replace(/\\/g,"/").replace(/^\.\//u,"")}function pI(e){return e.replace(/\.(?:jsx?|tsx?|json)$/iu,"")}function Ml(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=Si({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=tj(n).sort(nj);return{complete:o.length===0,nodes:r.sort(rj),edges:[...e.closure.edges].sort(oj),errors:o}}function tj(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function nj(e,t){return hn(e.path,t.path)||hn(e.code,t.code)||hn(e.specifier??"",t.specifier??"")||hn(e.message,t.message)}function rj(e,t){return hn(e.path,t.path)||hn(e.kind,t.kind)||hn(e.ownership,t.ownership)||hn(e.status,t.status)}function oj(e,t){return hn(e.from,t.from)||hn(e.target??"",t.target??"")||hn(e.specifier??"",t.specifier??"")||hn(e.kind,t.kind)||hn(e.resolution,t.resolution)}function hn(e,t){return e<t?-1:e>t?1:0}var hI={helper:"text",tsType:"string"},um={helper:"images",tsType:"MediaItem[]",importName:"MediaItem"},yI={helper:"image",tsType:"MediaItem | null",importName:"MediaItem"},xI=/(gallery|galleries|images|photos|pics|pictures|album|attachments|files|media)$/i;function ij(e,t,n){switch(e){case"text":case"date":return hI;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"||xI.test(n)?um:yI;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 dm(e,t,n){if(n){let r=ij(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{...xI.test(t)?um:yI};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{...hI}}}function fm(e,t,n={}){let r=`${aj(e)}View`,o=t.filter(c=>c.front_display!=="forbidden").map(c=>{let u={key:sj(c.name)?`${c.name}_field`:c.name,source:c.name,...dm(c.cms_type,c.name,c.value_shape)};return n.forceMultiMedia?.has(c.name)?{...u,helper:"images",tsType:"MediaItem[]",importName:"MediaItem"}:u}),i=[...new Set(o.map(c=>c.importName).filter(Boolean))],s=i.length?n.inferFieldTypesFromCms?i.map(c=>`type ${c} = ReturnType<typeof cms.field.${c==="MediaItem"?"images":"category"}>[number];`).join(`
|
|
12
|
+
`||f==="\r"))return Ui(t,`Unterminated string literal in ${t}.`);c=f===`
|
|
13
|
+
`||f==="\r";continue}if(f==="/"&&m==="*"){s=!0,d+=1,c=!1;continue}if(n==="mdx"&&f==="/"&&m==="/"){a=!0,d+=1,c=!1;continue}if(f==="'"||f==='"'||n==="mdx"&&f==="`"){o=f,c=!1;continue}if(f==="{"||f==="("||f==="["){r.push({char:f,offset:d}),c=!1;continue}if(f==="}"||f===")"||f==="]"){let g=f==="}"?"{":f===")"?"(":"[",p=r.pop();if(!p||p.char!==g)return Ui(t,`Unexpected closing token "${f}" in ${t}.`);c=!1;continue}c=f===`
|
|
14
|
+
`||f==="\r"}if(s)return Ui(t,`Unterminated block comment in ${t}.`);if(o)return Ui(t,`Unterminated string literal in ${t}.`);if(l)return Ui(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Ui(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Ui(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function pu(e){let t="idle",n=e.fileSystem??_B(),r=xy(),o=sv({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,l=null,c=e.history??(e.historyStore?ax(e.historyStore):CB()),u=ov(n,{externalAdapters:e.externalAdapters}),d=new Map,f=Py(du),m=new Set,g=0,p=e.historyStore?.recoveryRequired??!1,h=Nm(),x=v();function b(y){return(uu.isAbsolute(y)?uu.relative(e.projectRoot,y):y).replace(/\\/g,"/").replace(/^\.\//,"")}function E(y,P){let C=uu.posix.dirname(y),O=P.replace(/\.(?:tsx?|jsx?)$/i,""),U=uu.posix.relative(C,O);return U.startsWith(".")?U:`./${U}`}function S(y,P){return y.startLine===P.startLine&&y.startColumn===P.startColumn&&y.endLine===P.endLine&&y.endColumn===P.endColumn}async function v(){let y=e.historyStore;if(y)try{let P=await y.readTransactionJournal();if(!P)return;let C=await y.readIndex(),O=await Promise.all(P.files.map(async V=>await n.exists(V.path)?je(await n.readFile(V.path)):null));if(xv({journal:P,index:C,observedFileDigests:O})!=="ambiguous"){await y.clearTransactionJournal(P.transactionId);let V=await y.readStatus();V.recoveryRequired||(await y.cleanupTmp(),V=await y.readStatus()),p=V.recoveryRequired;return}await y.markRecoveryRequired(`Ambiguous transaction journal ${P.transactionId} at phase ${P.phase}`),p=!0}catch(P){p=!0,await y.markRecoveryRequired(`Transaction journal recovery failed: ${on(P)}`).catch(()=>{})}}function A(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let y of o.entries){let P=vv(y.context,y.entryFile);i.set(y.key,P),I(P,P.dependencyFiles)}function I(y,P){let C=new Set(P);_(y),y.dependencyFiles=C;for(let O of y.dependencyFiles){let U=s.get(O);U||(U=new Set,s.set(O,U)),U.add(y.key)}}function _(y){for(let P of y.dependencyFiles){let C=s.get(P);C&&(C.delete(y.key),C.size===0&&s.delete(P))}y.dependencyFiles.clear()}function k(y){let P=new Set;for(let C of y)for(let O of s.get(C)??[])P.add(O);return P}function T(y){for(let P of y)if(!s.has(P))return!1;return!0}async function L(y,P,C,O,U,V){let Y=new Map,Q=MI(y),ce=CI(U.values()),re=_S(U.values()),ne=typeof V.exists=="function"?fe=>V.exists(fe):async()=>!1;for(let[fe,be]of y.elements){let Be=P.nodes.get(fe);if(!Be)continue;let me=C.get(be.sourceFile)??O.get(be.sourceFile),Xe=new Map,Fe=new Map,H=new Map,ae=[];for(let mt of be.textSegments){if(!me){Xe.set(mt.index,null);continue}let ss=await RI({file:be.sourceFile,source:me,segment:mt,readFile:xn=>V.readFile(xn),exists:ne,graph:y,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:xn,adapterId:ko,capabilities:Hu})=>({sourceType:xn,adapterId:ko,capabilities:Hu})),functionCallContracts:e.functionCallContracts,fileCache:ce}),rn=await Em({file:be.sourceFile,source:me,target:{kind:"text-segment",segment:mt},readFile:xn=>V.readFile(xn),exists:ne,graph:y,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:xn,adapterId:ko,capabilities:Hu})=>({sourceType:xn,adapterId:ko,capabilities:Hu})),functionCallContracts:e.functionCallContracts,fileCache:ce}),wn=DB(ss);Xe.set(mt.index,wn),Fe.set(mt.index,ss),H.set(mt.index,rn),ae.push({editable:mt.editable,source:wn})}let Pe=new Map,Ke=new Map;if(me)for(let mt of be.attributes??[]){let ss=await $i({file:be.sourceFile,source:me,sourceRange:mt.sourceRange,expression:mt.source?.expression??mt.value,sourceInfo:mt.source,readFile:wn=>V.readFile(wn),exists:ne,graph:y,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:wn,adapterId:xn,capabilities:ko})=>({sourceType:wn,adapterId:xn,capabilities:ko})),functionCallContracts:e.functionCallContracts,fileCache:ce}),rn=await DI({element:be,file:be.sourceFile,source:me,propertyName:mt.name,readFile:wn=>V.readFile(wn),exists:ne,graph:y,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:wn,adapterId:xn,capabilities:ko})=>({sourceType:wn,adapterId:xn,capabilities:ko})),functionCallContracts:e.functionCallContracts,fileCache:ce});Ke.set(mt.name,rn),Pe.set(mt.name,ss)}let He=zI(MB(Be.writeTarget),ae),St=Q({key:fe,element:be,provenances:H}),Kr=ZI(be),nr=me?await zl({element:be,graph:y,file:be.sourceFile,source:me,readFile:mt=>V.readFile(mt),exists:ne,fileCache:re}):void 0,vo=y.regions.find(mt=>mt.kind==="conditional-region"&&mt.childKeys.includes(fe)),Xt,Tn=vo?.sourceCandidates?.[0];if(me&&vo&&Tn?.kind==="conditional-branch"){let mt=await Em({file:be.sourceFile,source:me,target:{kind:"conditional-branch",candidate:Tn},readFile:rn=>V.readFile(rn),exists:ne,graph:y,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:rn,adapterId:wn,capabilities:xn})=>({sourceType:rn,adapterId:wn,capabilities:xn})),functionCallContracts:e.functionCallContracts,fileCache:ce});Xt={currentBranch:vo.childKeys.indexOf(fe)<=0?"then":"else",availableBranches:vo.childKeys.length>1?["then","else"]:["then"],conditionExpression:Tn.conditionExpression,provenance:{finalSource:mt.finalSource?{kind:mt.finalSource.kind,file:mt.finalSource.file,displayPath:mt.finalSource.displayPath}:null,chain:mt.chain.map(rn=>({kind:rn.kind,file:rn.file,displayName:rn.displayName,canEditHere:rn.canEditHere})),confidence:mt.confidence,editMode:mt.editMode,diagnostics:mt.diagnostics.map(rn=>({code:rn.code,message:rn.message}))}}}Y.set(fe,{textSources:Xe,textTargets:Fe,elementPropertyTargets:Pe,propertyProvenances:Ke,isRepeat:nj(fe,y),provenances:H,writeTarget:He,componentSemantic:St,styleSource:Kr,conditional:Xt,dynamicData:nr})}return Y}function $(y){return typeof n.getVersion=="function"?n.getVersion(y):0}function J(y,P){let C=o.initialVersions.get(y.key)??0;for(let O of P.values())C=Math.max(C,O);return Math.max(C,y.graph?.version??0)}function z(y){return i.get(y)?.graph?.version??o.initialVersions.get(y)??0}function Z(y){try{return z(o.resolveSelector(y.composition).key)}catch{return 0}}async function W(y,P,C=n,O={}){let U=await pi(y,P,V=>C.readFile(V),V=>C.exists(V),{additionalEntries:await xe(y,C),...O});if(U.diagnostics.length>0)throw new ha(U.diagnostics);return O.validationOnly||f.remember(U.parsedModules.values()),U}async function Ee(y,P,C={}){let O=i.get(y);if(!O)return null;let U=C.sourceCache??Om(d,[]),V=C.fileSystem??Am(n),{graph:Y,allSources:Q,parsedModules:ce,entryModule:re}=await W(O.entryFile,P,V,{version:O.graph?.version??1}),ne=new Map;for(let Xt of Q.keys())ne.set(Xt,$(Xt));let fe=Math.max(J(O,ne),C.minimumVersion??0);C.changed&&fe<=(O.graph?.version??0)&&(fe=(O.graph?.version??0)+1),Y.version=fe;for(let[Xt,Tn]of Q)lu(U,Xt,Tn,du);let be=await Ce(O.composition,O.entryFile,Q,U,V);Y.routeId=O.routeId,Y.composition=O.composition;let Be=sl(Y),me=bc(Be,Y),Xe=await L(Y,Be,Q,U,ce,V);ot(me,Xe);let Fe=Ie(Y,me,Xe),H=bt(Xe),ae=uv(UI(Y,Be,me,{canUpdateTextByKey:Fe,dynamicDataSummaryByKey:H}),Y,Xe),Pe=Hn({route:O.routeId,composition:O.composition,entryFile:O.entryFile,version:fe,source:P,ast:re?.ast}),Ke=lb(Pe),He=null,St=[];if(Pe.ok){VB(ae,Y,Pe.projection,ce);let Xt=il({composition:O.composition,entryFile:O.entryFile,graph:Y,parsedModules:ce,projection:Pe.projection});if(Xt.diagnostics.length===0){let Tn=Us({composition:O.composition,entryFile:O.entryFile,graph:Y,parsedModules:ce,projection:Pe.projection,documentVersion:fe,roots:Xt.roots});Tn.diagnostics.length===0&&(He=Tn,St=Tn.descriptors)}}let Kr={...ae,composition:O.composition,pageBlocks:St,...be?{styleContext:be}:{},pageComposition:Ke},nr=new Set([O.entryFile,...Q.keys()]);if(be){nr.add(be.entryCss.path);for(let Xt of be.stylesheets)nr.add(Xt.path)}let vo={...O,dependencyFiles:nr,graph:Y,topology:Be,capabilities:me,document:Kr,pageBlockIndex:He,pageComposition:Ke,pageCompositionProjection:Pe.projection,pagePlacementByKey:Pe.ok?Pe.projection.placementByKey:null,pagePlacementUnitByKey:Pe.ok?Pe.projection.placementUnitByKey:null,pageUnitByKey:Pe.ok?Pe.projection.unitByKey:null,pagePlacementsByUnitKey:Pe.ok?Pe.projection.placementsByUnitKey:null,documentIndex:lv(Kr),detailProjections:Xe,fileVersions:ne,styleContext:be};if(C.publish===!1)return vo;for(let Xt of nr){let Tn=Q.get(Xt)??U.get(Xt);Tn!==void 0&&(lu(d,Xt,Tn,du),m.delete(Xt))}return I(O,nr),Object.assign(O,vo),O}async function xe(y,P=n){let C=[];for(let O of YB(y))typeof P.exists=="function"&&await P.exists(O)&&C.push({file:O,source:await P.readFile(O)});return C}async function Ce(y,P,C,O,U){let V=[];for(let[ne,fe]of C){if(Lm(ne)){V.push(ne);continue}for(let be of qB(fe)){let Be=Nv(ne,be);Be&&V.push(Be)}}if(!V.length){for(let ne of ZB(P))if(await U.exists(ne)){V.push(ne);break}}let Y=new Map,Q=tj(V).slice(0,bv);for(;Q.length>0&&Y.size<bv;){let ne=Q.shift();if(Y.has(ne)||!Lm(ne))continue;let fe=await Me(ne,O,U);if(fe!==null){Y.set(ne,{path:ne,content:fe});for(let be of QB(fe)){let Be=Nv(ne,be);Be&&!Y.has(Be)&&!Q.includes(Be)&&Q.push(Be)}}}let ce=[...Y.values()].map(ne=>({...ne,hash:je(ne.content)})),re=ce[0];return re?{composition:y,revision:je(JSON.stringify(ce.map(({path:ne,hash:fe})=>({path:ne,hash:fe})))),entryCss:re,stylesheets:ce.slice(1)}:null}async function Me(y,P,C){let O=P.get(y);if(O!==void 0)return O;if(!await C.exists(y))return null;let U=await C.readFile(y);return lu(P,y,U,du),U}function bt(y){let P=new Map;for(let[C,O]of y)O.dynamicData?.bindings.length&&P.set(C,MS(O.dynamicData.bindings));return P}function Ie(y,P,C){let O=new Map;for(let[U,V]of y.elements){if(!P.get(U)?.canUpdateText){O.set(U,!1);continue}let Q=C.get(U),ce=V.textSegments.some(re=>{if(!re.editable)return!1;let ne=Q?.provenances.get(re.index)??null;return!ne||Ve(ne)});O.set(U,ce)}return O}function ot(y,P){for(let[C,O]of P){let U=y.get(C);U?.canUpdateText&&O.dynamicData?.bindings.some(V=>V.readonly&&(V.targetKind==="text"||V.targetKind==="richtext"))&&y.set(C,{...U,canUpdateText:!1})}}function Ve(y){return y.editMode==="direct"||y.editMode==="proxy"||y.editMode==="upstream"}async function F(y,P={}){let C=[...new Set(y)],O=P.affectedCompositionKeys!==void 0,U=O?new Set(P.affectedCompositionKeys):k(C);if(!O&&(U.size===0||!T(C)))for(let re of i.values())ts(re,C)&&U.add(re.key);let V=!O&&U.size===0&&C.some(Pv),Y=P.publish===!1?Om(d,C):void 0,Q={rebuiltRoutes:[],failedRoutes:[],...P.publish===!1?{candidateRouteStates:[],candidateSourceCache:Y}:{}},ce=Am(n);for(let re of i.values())if(!(P.excludedCompositionKeys?.has(re.key)||!(U.has(re.key)||V)))try{let fe=!!re.graph,be=await ce.readFile(re.entryFile),Be=await Ee(re.key,be,{...P,fileSystem:ce,...Y?{sourceCache:Y}:{}});Be?.graph&&(Q.rebuiltRoutes.push({documentChanged:fe,composition:re.composition,routeId:re.routeId,version:Be.graph.version}),Q.candidateRouteStates?.push({composition:re.composition,key:re.key,routeId:re.routeId,state:Be}))}catch(fe){Q.failedRoutes.push({...hv(re.routeId,fe),composition:re.composition})}return Q}function q(y){let P=[...new Set(y)],C=k(P);if(C.size>0&&T(P))return[...C];for(let O of i.values())ts(O,P)&&C.add(O.key);return[...C]}function ee(y){let P=new Set(q(y));return o.entries.filter(C=>P.has(C.key)).map(C=>C.context)}function qe(y){return[...new Set(q(y))].sort((C,O)=>C<O?-1:C>O?1:0).map(C=>o.getByKey(C)?.context).filter(C=>C!==void 0)}function ht(y,P){let C=new Set(q(P)),O=y.provenance?.affectedCompositions??[];if(O.length===0)return C;if([...new Set(O.map(V=>o.resolveContext(V).key))].some(V=>!C.has(V)))throw new Error("History provenance does not match the affected composition index.");return C}function nn(y,P){let C=y.composition??y.provenance?.initiatingComposition;if(C){let V=o.resolveContext(C);return{context:V.context,key:V.key}}let O=[...new Set(q(P))];if(O.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${O.length}).`);let U=o.getByKey(O[0]);if(!U)throw new Error("Legacy history entry references an unknown affected composition.");return{context:U.context,key:U.key}}function tr(y,P){r.emit({type:"operation-completed",composition:y.composition,result:y});for(let{composition:C,version:O}of P.rebuiltRoutes)r.emit({type:"document-changed",composition:C,version:O});for(let{composition:C,message:O}of P.failedRoutes)r.emit({type:"graph-error",composition:C,message:O})}function ts(y,P){return P.some(C=>y.dependencyFiles.has(C)||y.entryFile===C||y.graph?.fileIndex.has(C))}function _r(y){for(let P of y)a.add(P);l||A()||(l=(async()=>{t="building";let P=!1;try{for(;a.size>0;){if(A())return;await ri(),await h.runExclusive(async()=>{if(g>0||A())return;let C=[...a];a.clear();let O=await Kn(C);if(O.length===0)return;let U=q(O);for(let Q of U){let ce=i.get(Q)?.composition;ce&&r.emit({type:"graph-invalidated",composition:ce})}let{rebuiltRoutes:V,failedRoutes:Y}=await F(O,{changed:!0});for(let{documentChanged:Q,composition:ce,version:re}of V)r.emit({type:"graph-ready",composition:ce,version:re}),Q&&r.emit({type:"document-changed",composition:ce,version:re});for(let{composition:Q,message:ce}of Y)P=!0,r.emit({type:"graph-error",composition:Q,message:ce})})}}finally{l=null,t!=="disposed"&&(t=!P&&[...i.values()].some(C=>C.graph)?"ready":"idle"),a.size>0&&_r([])}})())}async function ri(){for(;g>0;)await new Promise(y=>setTimeout(y,0))}async function Kn(y){let P=[];for(let C of new Set(y)){let O=d.get(C);if(O===void 0){if(m.has(C)&&!await n.exists(C))continue;m.delete(C),P.push(C);continue}try{await n.readFile(C)!==O&&(m.delete(C),P.push(C))}catch(U){if(!UB(U))try{if(await n.exists(C))continue}catch{continue}m.add(C),P.push(C)}}return P}function Io(y){yv(d,y);for(let P of y)P.exists===!1?m.add(P.file):m.delete(P.file)}function ns(y){m.clear();for(let P of y)m.add(P)}async function rs(y){let P=await Kn(y);if(P.length===0)return;let C=q(P);for(let V of C){let Y=i.get(V)?.composition;Y&&r.emit({type:"graph-invalidated",composition:Y})}let{rebuiltRoutes:O,failedRoutes:U}=await F(P,{changed:!0});for(let{documentChanged:V,composition:Y,version:Q}of O)r.emit({type:"graph-ready",composition:Y,version:Q}),V&&r.emit({type:"document-changed",composition:Y,version:Q});for(let{composition:V,message:Y}of U)r.emit({type:"graph-error",composition:V,message:Y})}async function ja(y,P){let C=ii(y,P);if(!C?.graph)return;let O=pn(y)??y,U=C.graph.elements.get(O);U&&await rs([U.sourceFile])}async function N(y){let P=new Set;if(y.target.kind==="node"){let C=ii(y.target.key,y.composition),O=pn(y.target.key)??y.target.key,U=C?.graph?.elements.get(O);U&&P.add(U.sourceFile)}else if(y.target.kind==="route"){let C=i.get(o.resolveSelector(y.target.composition).key);C&&P.add(C.entryFile)}else if(y.target.kind==="page-unit"){let C=i.get(o.resolveSelector(y.target.composition).key);C&&P.add(C.entryFile)}else if(y.target.kind==="page-block"){let C=i.get(o.resolveSelector(y.target.composition).key),O=C?.pageBlockIndex?.bindings.get(y.target.blockKey);if(O&&(P.add(O.ownerFile),P.add(O.descriptor.source.file)),C?.pageBlockIndex&&y.params.kind==="move-node"&&"kind"in y.params.target&&y.params.target.kind==="block-boundary"){let U=C.pageBlockIndex.bindings.get(y.params.target.anchorBlockKey);U&&(P.add(U.ownerFile),P.add(U.descriptor.source.file))}}else if(y.target.kind==="source-file")P.add(y.target.path);else if(y.target.kind==="source-batch")for(let C of y.target.paths)P.add(C);if(y.params.kind==="move-node"&&!("kind"in y.params.target)){let C=[y.params.target.parentKey,...y.params.target.relation==="before"||y.params.target.relation==="after"?[y.params.target.anchorKey]:[]];for(let O of C){let U=ii(O,y.composition),V=pn(O)??O,Y=U?.graph?.elements.get(V);Y&&P.add(Y.sourceFile)}}await rs(P)}async function B(y){if(y.params.kind!=="source-edit")return is(y,"invalid-params","source-edit requires source-edit params");for(let P of y.params.edits){let C=$B(P);if(!C.ok)return is(y,C.errorCode,C.message,C.details)}g+=1;try{let P=await os(y.params.edits);if(!P.ok)return is(y,P.errorCode,P.message,P.details);await N(y);let C={operationId:y.id,kind:"source-edit",target:y.target,documentVersion:y.documentVersion,conflictPolicy:y.params.conflictPolicy,edits:y.params.edits.map(O=>O.operation==="delete"?{operation:"delete",file:O.path,baseContentHash:O.baseContentHash??null}:{operation:"upsert",file:O.path,baseContentHash:O.baseContentHash??null,content:O.content})};return await Vr({request:y,filePlan:C})}catch(P){return{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!1,resultVersion:Z(y),error:{code:G.INTERNAL_ERROR,message:on(P)}}}finally{g-=1}}async function K(y){if(y.target.kind!=="project"||y.params.kind!=="insert-page-resource")return ie(y,G.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");g+=1;try{let P=await cs({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...y.params.artifact.components.flatMap(O=>O.materialization.files.map(U=>({path:U.pathTemplate,content:U.content}))),...y.params.artifact.pages.flatMap(O=>O.materialization.files.map(U=>({path:U.pathTemplate,content:U.content})))],exists:O=>n.exists(O),readFile:O=>n.readFile(O)});if(!P.ok)return ie(y,G.MATERIALIZATION_REJECTED,P.message);let C=await lf({artifact:y.params.artifact,exists:O=>n.exists(O)});return C.ok?await Vr({request:y,filePlan:{operationId:y.id,kind:"source-edit",target:y.target,documentVersion:y.documentVersion,conflictPolicy:"overwrite",edits:C.files},output:{kind:"insert-page-resource",package_instance_id:C.packageInstanceId,pages:C.pages},historyPolicy:"none"}):ie(y,C.code==="MATERIALIZATION_CONFLICT"?G.MATERIALIZATION_CONFLICT:G.MATERIALIZATION_REJECTED,C.message,C.path?{path:C.path}:void 0)}catch(P){return ie(y,G.INTERNAL_ERROR,on(P))}finally{g-=1}}async function X(y){if(y.target.kind!=="project"||y.params.kind!=="delete-page-source")return ie(y,G.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return ie(y,G.PLAN_FAILED,"Complete project file listing is required for page deletion.");g+=1;try{let P=Av(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(P.truncated)return ie(y,G.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:P.truncated.reasons});let C=P.files.filter(({path:Y})=>/\.(?:tsx?|jsx?)$/.test(Y)),O=Object.fromEntries(await Promise.all(C.map(async({path:Y})=>[Y,await n.readFile(Y)]))),U=iE({expectedUrlPath:y.params.expectedUrlPath,files:O});if(!U.ok)return ie(y,U.code==="HOME_PAGE_LOCKED"?G.HOME_PAGE_LOCKED:U.code==="ROUTE_NOT_FOUND"?G.ROUTE_NOT_FOUND:G.PLAN_FAILED,U.message);let V=await Promise.all(U.edits.map(async Y=>({...Y,baseContentHash:je(await n.readFile(Y.file))})));return Vr({request:y,filePlan:{operationId:y.id,kind:"source-edit",target:y.target,documentVersion:y.documentVersion,conflictPolicy:"compare-and-swap",edits:V},output:{kind:"delete-page-source",deleted_files:U.deletedFiles,updated_files:U.updatedFiles,preserved_shared_files:U.preservedSharedFiles,warnings:U.warnings},historyPolicy:"none"})}catch(P){return ie(y,G.INTERNAL_ERROR,on(P))}finally{g-=1}}async function te(y,P){if(y.kind!=="insert-child"&&y.kind!=="replace-node")return ie(y,G.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(y.params.kind!=="insert-child"&&y.params.kind!=="replace-node"||y.kind!==y.params.kind)return ie(y,G.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(y.params.kind==="insert-child"){if(!("kind"in y.params.position)||y.params.position.kind!=="page-composition")return ie(y,G.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(y.params.position.documentVersion!==y.documentVersion)return ie(y,G.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let C=P.document,O=P.pageCompositionProjection;if(!C||C.pageComposition?.status!=="supported"||!O||O.status!=="supported")return ie(y,G.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(y.documentVersion!==C.version||O.documentVersion!==C.version)return ie(y,G.VERSION_STALE,`Document version ${y.documentVersion} is stale (current: ${C.version}).`);let U=y.params.node.kind==="component-call"?y.params.node.materialization:void 0;if(!U)return ie(y,G.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let V=y.params.kind==="insert-child"?y.params.position:null,Y=await cs({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:U.files.map(re=>({path:re.pathTemplate,content:re.content})),exists:re=>n.exists(re),readFile:re=>n.readFile(re)});if(!Y.ok)return ie(y,G.MATERIALIZATION_REJECTED,Y.message);let Q=await Sv(n,Object.keys(U.projectDependencies??{})),ce=await hf({manifest:U,generatedRoot:"components/site/generated",controlledFiles:U.files.map(re=>({pathTemplate:re.pathTemplate})),exists:re=>n.exists(re),availableHostDependencies:Q,hostCapabilities:rf(),commit:async re=>{let ne=await n.readFile(P.entryFile),fe=P.document,be=P.pageCompositionProjection;if(!fe||fe.pageComposition?.status!=="supported"||fe.version!==y.documentVersion||!be||be.status!=="supported"||be.documentVersion!==fe.version)return{ok:!0,data:ie(y,G.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Be=re.entry.path,me=rC(re.instanceName),Xe,Fe=[];if(y.params.kind==="insert-child"){if(!V||!("kind"in V)||V.kind!=="page-composition")return{ok:!0,data:ie(y,G.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let Ke=Ls({routeId:P.routeId,entryFile:P.entryFile,currentDocumentVersion:fe.version,expectedDocumentVersion:y.documentVersion,source:ne,projection:be,placementKey:V.placementKey,component:{source:Be,exportName:re.entry.export.kind==="default"?"default":re.entry.export.name,localName:me}});if(!Ke.ok)return{ok:!0,data:ie(y,zu(Ke.error.code),Ke.error.message,{diagnostics:Ke.error.diagnostics})};let He=Ke.plan.rewriteStep,St;switch(He.kind){case"insert-root-expression":St=Fs({source:ne,locator:He.locator,expectedSourceHash:He.sourceHash,action:{kind:"insert",jsx:He.node.jsx,placement:He.placement,replaceOriginal:He.replaceOriginal}});break;case"insert-child":St=Fn({source:ne,locator:He.parentLocator,node:He.node,placement:He.placement,...He.anchorLocator?{anchorLocator:He.anchorLocator}:{}});break;default:St={ok:!1,source:ne,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(He)}`}}}if(!St.ok)return{ok:!0,data:ie(y,G.AST_PARSE_ERROR,St.diagnostic.message)};Xe=St.source}else{let Ke=Lf({routeId:P.routeId,composition:P.composition,entryFile:P.entryFile,currentDocumentVersion:fe.version,expectedDocumentVersion:y.documentVersion,source:ne,projection:be,placementUnitKey:y.target.placementUnitKey,operation:"replace-node"});if(!Ke.ok)return{ok:!0,data:ie(y,zu(Ke.error.code),Ke.error.message,{diagnostics:Ke.error.diagnostics})};let He=Ke.plan.rewriteStep,St;switch(He.kind){case"replace-root-expression":St=Fs({source:ne,locator:He.locator,expectedSourceHash:He.sourceHash,action:{kind:"replace",jsx:`<${me} />`}});break;case"replace-node":St=ai({source:ne,locator:He.locator,node:{jsx:`<${me} />`}});break;default:St={ok:!1,source:ne,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${He.kind}`}}}if(!St.ok)return{ok:!0,data:ie(y,G.AST_PARSE_ERROR,St.diagnostic.message)};let Kr=await Jn({routeState:P,placementUnitKey:y.target.placementUnitKey,source:ne,mutatedSource:St.source});Xe=Kr.source,Fe=await Promise.all(Kr.files.map(async nr=>({operation:"delete",file:nr,baseContentHash:je(await n.readFile(nr))})))}let H=Dn({source:Xe,moduleSpecifier:E(P.entryFile,Be),imports:re.entry.export.kind==="default"?[{kind:"default",local:me}]:[{kind:"named",imported:re.entry.export.name,local:me}]});if(!H.ok)return{ok:!0,data:ie(y,G.AST_PARSE_ERROR,H.diagnostic.message)};let ae=re.files.map(Ke=>({operation:"create-only",file:Ke.path,content:Ke.content})),Pe=[{operation:"upsert",file:P.entryFile,content:H.source,baseContentHash:je(ne)},...ae,...Fe];g+=1;try{let Ke=await Vr({request:y,filePlan:{operationId:y.id,kind:"source-edit",target:{kind:"source-file",path:P.entryFile},documentVersion:y.documentVersion,conflictPolicy:"compare-and-swap",edits:Pe}});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{g-=1}}});return ce.ok?ce.data:ie(y,ce.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?G.MATERIALIZATION_CONFLICT:G.MATERIALIZATION_REJECTED,ce.error.message,{materializationCode:ce.error.code})}async function Re(y,P){if(y.kind!=="insert-child"&&y.kind!=="replace-node")return ie(y,G.UNSUPPORTED_OPERATION,"Only page-block insert-child and replace-node use this materialization transaction.");if(y.params.kind!==y.kind||y.kind==="replace-node"&&y.params.kind!=="replace-node"||y.kind==="insert-child"&&y.params.kind!=="insert-child")return ie(y,G.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let C=P.document,O=P.pageBlockIndex;if(!C||!O||O.diagnostics.length>0)return ie(y,G.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(y.documentVersion!==C.version||O.documentVersion!==C.version)return ie(y,G.VERSION_STALE,`Document version ${y.documentVersion} is stale (current: ${C.version}).`);let U=vi(O,y.target,y.documentVersion,y.selectionRef);if(!U.ok)return ie(y,pt(U.code),U.message);let V=U.binding;if(!(y.kind==="insert-child"?V.descriptor.capabilities.insert:V.descriptor.capabilities.replace)){let me=V.descriptor.unavailableReasons?.[y.kind==="insert-child"?"insert":"replace"]?.reason??"The selected page block does not permit this operation.";return ie(y,G.UNSUPPORTED_OPERATION,me)}let Q=(y.kind==="insert-child",y.params);if(Q.kind!==y.kind)return ie(y,G.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let ce=Q.node;if(ce.kind!=="component-call"||!ce.materialization)return ie(y,G.UNSUPPORTED_OPERATION,"Page-block materialization requires a static component manifest.");let re;if(Q.kind==="insert-child"){let me=Q.position;if(!("kind"in me&&me.kind==="block-boundary"))return ie(y,G.INVALID_PARAMS,"Page-block insert-child requires a block-boundary position.");if(me.documentVersion!==y.documentVersion)return ie(y,G.VERSION_STALE,"The block insertion boundary belongs to a different document version.");let Xe=al(O,me);if(!Xe.ok)return ie(y,pt(Xe.code),Xe.message);re=Xe.boundary}let ne=ce.materialization,fe=await cs({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:ne.files.map(me=>({path:me.pathTemplate,content:me.content})),exists:me=>n.exists(me),readFile:me=>n.readFile(me)});if(!fe.ok)return ie(y,G.MATERIALIZATION_REJECTED,fe.message);let be=await Sv(n,Object.keys(ne.projectDependencies??{})),Be=await hf({manifest:ne,generatedRoot:"components/site/generated",controlledFiles:ne.files.map(me=>({pathTemplate:me.pathTemplate})),exists:me=>n.exists(me),availableHostDependencies:be,hostCapabilities:rf(),commit:async me=>{let Xe=P.document,Fe=P.pageBlockIndex;if(!Xe||!Fe||Xe.version!==y.documentVersion||Fe.documentVersion!==Xe.version||!Fe.bindings.has(V.blockKey))return{ok:!0,data:ie(y,G.VERSION_STALE,"The route or selected block changed before materialization could commit.")};let H=Fe.bindings.get(V.blockKey);if(!H||H.ownerFile!==V.ownerFile||H.ownerSourceHash!==V.ownerSourceHash||H.sourceHash!==V.sourceHash)return{ok:!0,data:ie(y,G.VERSION_STALE,"The selected block owner or source changed before materialization could commit.")};let ae=new Set([V.ownerFile,V.descriptor.source.file,...re?[re.ownerFile,re.anchorLocator.file,...re.parentLocator?[re.parentLocator.file]:[]]:[]]),Pe=new Map;try{for(let He of ae)Pe.set(He,await n.readFile(He))}catch{return{ok:!0,data:ie(y,G.VERSION_STALE,"A selected owner, root, or boundary file is no longer readable.")}}let Ke=jb({operationId:y.id,documentVersion:y.documentVersion,target:y.target,binding:V,...re?{boundary:re}:{},operation:Q.kind,materialization:me,files:Pe});if(!Ke.ok){let He=cn(Ke.code);return{ok:!0,data:ie(y,He,Ke.message,{materializationCode:Ke.code})}}g+=1;try{let He=await Vr({request:y,filePlan:Ke.plan});return!He.ok&&He.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:He.error.message||"Static prefab instance conflicted during commit."}}:{ok:!0,data:He}}finally{g-=1}}});return Be.ok?Be.data:ie(y,Be.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?G.MATERIALIZATION_CONFLICT:G.MATERIALIZATION_REJECTED,Be.error.message,{materializationCode:Be.error.code})}async function Qe(y,P){if(y.kind!=="move-node"&&y.kind!=="remove-node")return ie(y,G.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let C=P.document,O=P.pageCompositionProjection;if(!C||C.pageComposition?.status!=="supported"||!O||O.status!=="supported")return ie(y,G.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(y.documentVersion!==C.version||O.documentVersion!==C.version)return ie(y,G.VERSION_STALE,`Document version ${y.documentVersion} is stale (current: ${C.version}).`);let U=await n.readFile(P.entryFile),V=Lf({routeId:P.routeId,composition:P.composition,entryFile:P.entryFile,currentDocumentVersion:C.version,expectedDocumentVersion:y.documentVersion,source:U,projection:O,placementUnitKey:y.target.placementUnitKey,operation:y.kind,targetPlacement:y.kind==="move-node"&&y.params.kind==="move-node"&&"kind"in y.params.target&&y.params.target.kind==="page-composition"?y.params.target:void 0});if(!V.ok)return ie(y,zu(V.error.code),V.error.message,{diagnostics:V.error.diagnostics});let Y=V.plan.rewriteStep,Q;switch(Y.kind){case"move-node":Q=Fo({source:U,locator:Y.locator,targetParentLocator:Y.targetParentLocator,placement:Y.placement,...Y.anchorLocator?{anchorLocator:Y.anchorLocator}:{}});break;case"remove-node":Q=Oo({source:U,locator:Y.locator});break;case"remove-root-expression":Q=Fs({source:U,locator:Y.locator,expectedSourceHash:Y.sourceHash,action:{kind:"remove"}});break;default:Q={ok:!1,source:U,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${Y.kind}`}}}if(!Q.ok)return ie(y,G.AST_PARSE_ERROR,Q.diagnostic.message);let ce=Q.source,re=[];if(y.kind==="remove-node"){let fe=await Jn({routeState:P,placementUnitKey:y.target.placementUnitKey,source:U,mutatedSource:ce});ce=fe.source,re=await Promise.all(fe.files.map(async be=>({operation:"delete",file:be,baseContentHash:je(await n.readFile(be))})))}let ne=[{operation:"upsert",file:P.entryFile,content:ce,baseContentHash:je(U)},...re];g+=1;try{return await Vr({request:y,filePlan:{operationId:y.id,kind:"source-edit",target:{kind:"source-file",path:P.entryFile},documentVersion:y.documentVersion,conflictPolicy:"compare-and-swap",edits:ne}})}finally{g-=1}}async function ue(y,P){if(y.kind!=="move-node"&&y.kind!=="remove-node")return ie(y,G.UNSUPPORTED_OPERATION,"Only page-block move-node and remove-node use this source transaction.");let C=P.document,O=P.pageBlockIndex;if(!C||!O||O.diagnostics.length>0)return ie(y,G.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(y.documentVersion!==C.version||O.documentVersion!==C.version)return ie(y,G.VERSION_STALE,`Document version ${y.documentVersion} is stale (current: ${C.version}).`);let U=vi(O,y.target,y.documentVersion,y.selectionRef);if(!U.ok)return ie(y,pt(U.code),U.message);let V=U.binding;if(V.documentVersion!==C.version)return ie(y,G.VERSION_STALE,"The resolved page-block binding is stale.");if(!(y.kind==="move-node"?V.descriptor.capabilities.move:V.descriptor.capabilities.remove)){let Fe=V.descriptor.unavailableReasons?.[y.kind==="move-node"?"move":"remove"]?.reason??"The selected block does not permit this operation.";return ie(y,G.UNSUPPORTED_OPERATION,Fe)}if(y.kind==="remove-node"){let Fe=[...i.values()].filter(H=>H.dependencyFiles.has(V.ownerFile));if(Fe.includes(P)||Fe.push(P),Fe.some(H=>!H.pageBlockIndex||H.pageBlockIndex.descriptors.length<=1))return ie(y,G.UNSUPPORTED_OPERATION,"The selected source is the last editable page block in an affected composition.")}let Q=null;if(y.kind==="move-node"){if(y.params.kind!=="move-node"||!("kind"in y.params.target)||y.params.target.kind!=="block-boundary")return ie(y,G.INVALID_PARAMS,"Page-block move requires a block-boundary target.");if(y.params.target.anchorBlockKey===V.blockKey)return ie(y,G.INVALID_TARGET,"A page block cannot be moved relative to itself.");let Fe=al(O,y.params.target);if(!Fe.ok)return ie(y,pt(Fe.code),Fe.message);let H=O.bindings.get(y.params.target.anchorBlockKey);if(!H||!V.descriptor.siblingBlockKeys.includes(H.blockKey)||!H.descriptor.siblingBlockKeys.includes(V.blockKey)||H.ownerFile!==V.ownerFile||H.root.ownerNode.kind!==V.root.ownerNode.kind||H.root.ownerNode.key!==V.root.ownerNode.key||H.root.parentStructuralPath!==V.root.parentStructuralPath)return ie(y,G.INVALID_TARGET,"The selected block and boundary anchor are not verified same-owner source siblings.");if(Q=Fe.boundary,Q.ownerFile!==V.ownerFile||Q.sourceHash!==V.ownerSourceHash||!Q.parentLocator)return ie(y,G.INVALID_TARGET,"The move boundary does not belong to the selected block's source owner.")}let ce=V.ownerFile,re=await n.readFile(ce);if(je(re)!==V.ownerSourceHash)return ie(y,G.VERSION_STALE,"The page-block owner source changed after resolution.");let ne=V.descriptor.source.file===ce?re:await n.readFile(V.descriptor.source.file);if(je(ne)!==V.descriptor.source.contentHash)return ie(y,G.VERSION_STALE,"The selected page-block source changed after resolution.");let fe=ve(V),be=y.kind==="remove-node"?Oo({source:re,locator:fe}):Fo({source:re,locator:fe,targetParentLocator:it(Q.parentLocator),anchorLocator:it(Q.anchorLocator),placement:Q.placement});if(!be.ok)return ie(y,G.AST_PARSE_ERROR,be.diagnostic.message);let Be=be.source,me=[];if(y.kind==="remove-node"&&V.root.ownerNode.kind==="route-member"&&V.root.callChain.length>0&&V.descriptor.placementUnitKey){let Fe=await Jn({routeState:P,placementUnitKey:V.descriptor.placementUnitKey,source:re,mutatedSource:Be});Be=Fe.source,me=Fe.files}let Xe=[{operation:"upsert",file:ce,content:Be,baseContentHash:V.ownerSourceHash},...await Promise.all(me.map(async Fe=>({operation:"delete",file:Fe,baseContentHash:je(await n.readFile(Fe))})))];g+=1;try{return await Vr({request:y,filePlan:{operationId:y.id,kind:"source-edit",target:y.target,documentVersion:y.documentVersion,conflictPolicy:"compare-and-swap",edits:Xe}})}finally{g-=1}}function ve(y){return it(y.ownerLocator)}function it(y){return{kind:"jsx-node",strategy:"source-range",sourceRange:y.sourceRange,...y.structuralPath&&y.componentName?{expectedIdentity:{file:y.file,component:y.componentName,structuralPath:y.structuralPath}}:{}}}function pt(y){return y==="VERSION_STALE"?G.VERSION_STALE:y==="INVALID_PARAMS"?G.INVALID_PARAMS:G.INVALID_TARGET}function cn(y){return y==="VERSION_STALE"?G.VERSION_STALE:y==="INVALID_PARAMS"?G.INVALID_PARAMS:y==="INVALID_TARGET"?G.INVALID_TARGET:y.startsWith("MATERIALIZATION_")?G.MATERIALIZATION_REJECTED:G.UNSUPPORTED_OPERATION}async function Jn(y){let P={source:y.mutatedSource,files:[]},C=y.routeState.graph,O=y.routeState.pageCompositionProjection;if(!C||!O||O.status!=="supported"||!n.listFiles)return P;let V=O.placementUnitByKey.get(y.placementUnitKey)?.sourceRange;if(!V)return P;let Y=[...C.elements.values()].find(H=>H.sourceFile===y.routeState.entryFile&&H.importedFrom&&S(H.sourceRange,V));if(!Y?.importedFrom||!Y.exportName)return P;let Q=b(Y.importedFrom),ce="components/site/generated/";if(!Q.startsWith(ce))return P;let re=Q.slice(ce.length).split("/")[0];if(!re||!/-[0-9a-f]{8}$/i.test(re))return P;let ne=`${ce}${re}`;if([...C.elements.values()].filter(H=>H.sourceFile===y.routeState.entryFile&&b(H.importedFrom??"")===Q).length!==1)return P;let be=await n.listFiles({maxFiles:5e3,maxDepth:32}),Be=Array.isArray(be)?be:be.files;if(!Array.isArray(be)&&be.truncated)return P;let me=Be.map(({path:H})=>H).filter(H=>H===ne||H.startsWith(`${ne}/`));if(me.length===0||!me.includes(Q))return P;for(let{path:H}of Be)if(!(H===y.routeState.entryFile||H===ne||H.startsWith(`${ne}/`)))try{if((await n.readFile(H)).includes(re))return P}catch{return P}let Xe=E(y.routeState.entryFile,Q),Fe=li({source:y.mutatedSource,moduleSpecifier:Xe,imports:Y.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:Y.exportName}]});return Fe.ok?Fe.source.includes(re)?{source:Fe.source,files:[]}:{source:Fe.source,files:me.sort((H,ae)=>H.localeCompare(ae))}:P}async function os(y){if(n.getFileInfo){for(let Y of y)if(await n.exists(Y.path)&&await n.getFileInfo(Y.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${Y.path}`,details:{path:Y.path}}}for(let Y of y){if(Y.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(Y.path))continue;let Q=await n.exists(Y.path)?await cd(n,Y.path):null;if(Q?.ok){let ce=gB(Q.content,Y.content);if(!ce.ok)return{ok:!1,errorCode:"invalid-params",message:ce.message,details:{path:Y.path,code:ce.code}}}}let P=$a(y);if(P.length===0)return{ok:!0};let C=BB(n,y),O=new Map,U=(Y,Q)=>{let ce=O.get(Y);if(ce?.source===Q)return ce.result;let re=Te(Y,Q);return O.set(Y,{source:Q,result:re}),re},V;try{V=await av(P,async Y=>{let Q=i.get(Y);return Q?[...(await W(Q.entryFile,await C.readFile(Q.entryFile),C,{validationOnly:!0,parseModule:U,validatedImports:f.getImports})).parsedModules.values()]:[]})}catch(Y){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${on(Y)}`,details:{compositionKeys:P}}}for(let Y of V)f.remember(Y);return{ok:!0}}function $a(y){return y.map(C=>C.path).some(Pv)?[...i.keys()]:[]}function is(y,P,C,O){let U=xa(P);return{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!1,resultVersion:Z(y),error:{code:U,message:C,...O?{details:O}:{}}}}async function Ju(y){let P=[];for(let C of new Set(y))P.push(await q_(C));return P}async function q_(y){if(!(typeof n.exists=="function"?await n.exists(y):!0))return{file:y,content:"",version:Math.max(0,$(y)),exists:!1};let C=await n.readFile(y);return{file:y,content:C,version:Math.max(1,$(y)),exists:!0,sha256:je(C)}}async function Zg(y,P,C,O){if(!e.historyStore)return null;let U=new Map(P.map(Q=>[Q.file,Q])),V=new Map(C.map(Q=>[Q.file,Q])),Y=[...new Set([...U.keys(),...V.keys()])].sort().map(Q=>{let ce=U.get(Q),re=V.get(Q);return{path:Q,preDigest:ce?.exists===!1||!ce?null:je(ce.content),postDigest:re?.exists===!1||!re?null:je(re.content)}});return{schemaVersion:2,transactionId:`${y}:${O.expectedIndexDigest}`,operationId:y,phase:"prepared",historyTransition:O,files:Y}}async function qg(y){return!y||!e.historyStore||await e.historyStore.writeTransactionJournal(y),y}async function oi(y){y&&e.historyStore&&await e.historyStore.clearTransactionJournal(y.transactionId)}async function Xu(y,P){let C=[];try{for(let O of y)await Qg(O),typeof n.bumpVersion=="function"&&n.bumpVersion(O.file),C.push(O.file)}catch(O){let U=await Q_(P.filter(V=>C.includes(V.file)));return U.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${on(O)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${U.failedFiles.join(", ")}: ${on(O)}`,rolledBack:!1}}return{ok:!0,snapshots:y.map(eC)}}async function Qg(y){if(y.exists===!1){await n.deleteFile(y.file);return}await n.writeFile(y.file,y.content)}async function Q_(y){let P=[];for(let C of y)try{await Qg(C),typeof n.bumpVersion=="function"&&n.bumpVersion(C.file)}catch{P.push(C.file)}return P.length===0?{ok:!0}:{ok:!1,failedFiles:P}}function eC(y){let P=y.exists!==!1;return{file:y.file,content:P?y.content:"",version:y.version,exists:P,...P?{sha256:je(y.content)}:{}}}async function Vr(y){return h.runExclusive(()=>tC(y))}async function tC(y){let P=y.filePlan.edits.map(H=>H.file),C=o.resolveSelector(y.request.composition),O=C.context,U=y.historyPolicy==="none"?void 0:{initiatingComposition:O,affectedCompositions:qe(P)},V=await Ju(P),Y=new Map(V.filter(H=>H.exists!==!1).map(H=>[H.file,H.content])),Q=th(),ce=new Map(d),re=new Set(m),ne=new Set([...i.values()].filter(H=>y.filePlan.edits.some(ae=>ae.operation==="delete"&&ae.file===H.entryFile)).map(H=>H.key)),fe=y.filePlan.edits.map(H=>H.operation==="delete"?{file:H.file,content:"",version:0,exists:!1}:{file:H.file,content:H.content,version:0,exists:!0,sha256:je(H.content)}),be={operationId:y.filePlan.operationId,intents:y.filePlan.edits.map(H=>H.operation==="delete"?{kind:"delete",path:H.file}:{kind:H.operation==="create-only"?"create-only":"upsert",path:H.file,content:H.content})},Be=null,me=!1,Xe=await iu({overlay:Y,exists:H=>n.exists(H),plan:be,buildCandidate:async({plan:H})=>({plan:H}),prepareHistory:async()=>{let H=y.historyPolicy==="none"?null:await c.prepareAppend({composition:o.resolveSelector(y.request.composition).context,operationId:y.request.id,kind:y.request.kind,target:y.request.target,preSnapshots:V,postSnapshots:fe,...y.selectionRef?{selectionRef:y.selectionRef}:{},...y.output?{output:y.output}:{},...U?{provenance:U}:{}}),ae=H?.historyTransition?H.historyTransition:e.historyStore?kB(await e.historyStore.readIndex()):null;if(e.historyStore&&!ae)throw new Error("Durable history did not provide an exact index transition.");return Be=await Zg(y.request.id,V,fe,ae),Be=await qg(Be),{history:H,historyTransition:ae}},reverify:async()=>{},writeCandidate:async()=>{let H=await u.executeFilePlan(y.filePlan);if(!H.ok)throw new fu(H);return{postSnapshots:await Ju(H.affectedFiles),affectedFiles:H.affectedFiles,internalResultVersion:H.resultVersion}},validateCandidate:async({candidate:H,receipt:ae})=>{let Pe=await F(ae.affectedFiles,{changed:!0,minimumVersion:ae.internalResultVersion,publish:!1,excludedCompositionKeys:ne});if(Pe.failedRoutes.length>0)throw new Zo(Pe.failedRoutes);let Ke=rh(Q,Pe.candidateRouteStates??[]),He=nh(Ke,C.key);return{...H,rebuild:Pe,routeSnapshots:Ke,resultVersion:He,...kv(y.selectionRef,Ke.map(St=>St.state.document))?{selectionRef:kv(y.selectionRef,Ke.map(St=>St.state.document))}:{}}},publishCandidate:async({candidate:H,history:ae,receipt:Pe})=>{ae?.history&&(await c.publishPrepared(ae.history),me=!0);let Ke=H.resultVersion??Pe.internalResultVersion;return{composition:O,requestId:y.request.id,kind:y.request.kind,target:y.request.target,ok:!0,resultVersion:Ke,affectedFiles:Pe.affectedFiles,fileChanges:Pe.postSnapshots.map(He=>({path:He.file,operation:He.exists===!1?"delete":"upsert"})),...y.output?{output:y.output}:{},...H.selectionRef?{selectionRef:H.selectionRef}:{}}},swapCandidate:({candidate:H,receipt:ae})=>{H.routeSnapshots&&Ua(H.routeSnapshots),H.rebuild?.candidateSourceCache&&ya(d,H.rebuild.candidateSourceCache),Io(ae.postSnapshots)},finalizeCandidate:async()=>{await oi(Be);for(let H of ne)i.delete(H)},emitCommitted:({candidate:H,published:ae})=>{tr(ae,H.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:H,receipt:ae})=>{if(me)throw new Error("history was published before transaction finalization failed");if(ae){let Pe=await Xu(V,ae.postSnapshots);if(!Pe.ok)throw new Error(Pe.reason)}Ua(Q),ya(d,ce),ns(re),H?.history&&await c.discardPrepared?.(H.history),await oi(Be)}});if(Xe.ok)return Xe.published;if(Xe.stage==="precheck"||Xe.stage==="build")try{await oi(Be)}catch(H){let ae=await Ka(on(H));return ie(y.request,ae,"Unable to clear an uncommitted transaction journal.")}if(Xe.recoveryRequired){let H=await Ka(Xe.reason);return ie(y.request,H===G.RECOVERY_PERSIST_FAILED?H:G.ROLLBACK_FAILED,Xe.reason)}let Fe=Xe.error;return Fe instanceof fu?{...ie(y.request,xa(Fe.result.errorCode),Fe.result.reason),...Fe.result.affectedFiles?{affectedFiles:Fe.result.affectedFiles}:{}}:Fe instanceof Zo?ie(y.request,G.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${wm(Fe.failedRoutes)}`,{failedRoutes:Fe.failedRoutes}):ie(y.request,ih(Xe.stage),on(Fe))}async function eh(y){return h.runExclusive(async()=>{let P=y==="undo"?await c.prepareUndo():await c.prepareRedo();return P?nC(y,P):{composition:o.entries[0].context,requestId:y,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:G.INTERNAL_ERROR,message:y==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function nC(y,P){let C=P.entry,O=y==="undo"?C.preSnapshots:C.postSnapshots,U=y==="undo"?C.postSnapshots:C.preSnapshots,V=O.map(ae=>ae.file),{context:Y,key:Q}=nn(C,V),ce=await Ju(V),re=new Map(ce.filter(ae=>ae.exists!==!1).map(ae=>[ae.file,ae.content])),ne=z(Q),fe=th(),be=new Map(d),Be=new Set(m),me=null,Xe=!1,Fe,H=await iu({overlay:re,plan:{operationId:`${y}:${C.operationId}`,intents:O.map(ae=>ae.exists===!1?{kind:"delete",path:ae.file}:{kind:"upsert",path:ae.file,content:ae.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(me=await Zg(`${y}:${C.operationId}`,ce,O,P.historyTransition),me=await qg(me),P),reverify:async()=>{},writeCandidate:async()=>{let ae=await Xu(O,U);if(!ae.ok)throw new Error(ae.reason);return{snapshots:ae.snapshots}},validateCandidate:async({candidate:ae})=>{Fe=ht(C,V);let Pe=await F(V,{changed:!0,minimumVersion:ne+1,publish:!1,affectedCompositionKeys:Fe});if(Pe.failedRoutes.length>0)throw new Zo(Pe.failedRoutes);let Ke=rh(fe,Pe.candidateRouteStates??[]),He=nh(Ke,Q);return{...ae,rebuild:Pe,routeSnapshots:Ke,resultVersion:He}},publishCandidate:async({candidate:ae,history:Pe,receipt:Ke})=>{if(!Pe)throw new Error("history cursor intent is missing");await c.publishPrepared(Pe),Xe=!0;let He=ae.resultVersion??ne+1;return{composition:Y,requestId:y,kind:C.kind,target:C.target,ok:!0,resultVersion:He,affectedFiles:V,fileChanges:Ke.snapshots.map(St=>({path:St.file,operation:St.exists===!1?"delete":"upsert"})),...C.output?{output:C.output}:{}}},swapCandidate:({candidate:ae,receipt:Pe})=>{ae.routeSnapshots&&Ua(ae.routeSnapshots),ae.rebuild?.candidateSourceCache&&ya(d,ae.rebuild.candidateSourceCache),Io(Pe.snapshots)},finalizeCandidate:async()=>{await oi(me)},emitCommitted:({candidate:ae,published:Pe})=>tr(Pe,ae.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:ae,receipt:Pe})=>{if(Xe)throw new Error("history cursor was published before transaction finalization failed");if(Pe){let Ke=await Xu(U,Pe.snapshots);if(!Ke.ok)throw new Error(Ke.reason)}Ua(fe),ya(d,be),ns(Be),ae&&await c.discardPrepared?.(ae),await oi(me)}});if(H.ok)return H.published;if(H.stage==="precheck"||H.stage==="build")try{await oi(me)}catch(ae){let Pe=await Ka(on(ae));return{composition:Y,requestId:y,kind:C.kind,target:C.target,ok:!1,resultVersion:ne,error:{code:Pe,message:"Unable to clear an uncommitted transaction journal."}}}if(H.recoveryRequired){let ae=await Ka(H.reason);return{composition:Y,requestId:y,kind:C.kind,target:C.target,ok:!1,resultVersion:ne,affectedFiles:V,error:{code:ae===G.RECOVERY_PERSIST_FAILED?ae:G.ROLLBACK_FAILED,message:H.reason}}}return{composition:Y,requestId:y,kind:C.kind,target:C.target,ok:!1,resultVersion:ne,affectedFiles:V,error:{code:H.error instanceof Zo?G.ROUTE_REBUILD_FAILED:ih(H.stage),message:on(H.error),...H.error instanceof Zo?{details:{failedRoutes:H.error.failedRoutes}}:{}}}}function th(){return[...i.values()].map(y=>({composition:y.composition,key:y.key,routeId:y.routeId,state:{...y,dependencyFiles:new Set(y.dependencyFiles),fileVersions:new Map(y.fileVersions)}}))}function nh(y,P){return y.find(O=>O.key===P)?.state.graph?.version??o.initialVersions.get(P)??0}function rh(y,P){let C=new Map(y.map(O=>[O.key,O]));for(let O of P)C.set(O.key,O);return[...C.values()]}function Ua(y){for(let P of i.values())_(P);for(let P of y){let C={...P.state,dependencyFiles:new Set(P.state.dependencyFiles),fileVersions:new Map(P.state.fileVersions)};i.set(P.key,C),I(C,C.dependencyFiles)}}async function Va(y){let P=i.get(y);if(!P)throw new Error(`Composition not found: ${y}`);if(P.graph)return;let C=await n.readFile(P.entryFile);await Ee(y,C)}function ii(y,P){let C=i.get(o.resolveSelector(P).key)??null;return!C||!oh(C,y)?null:C}function oh(y,P){if(y.documentIndex?.entriesByKey.has(P)||y.graph?.elements.has(P))return!0;let C=pn(P);return C&&C!==P?y.graph?.elements.has(C)===!0:!1}function ie(y,P,C,O){return{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!1,resultVersion:Z(y),error:{code:P,message:C,...O?{details:O}:{}}}}function ih(y){return y==="validate"?G.ROUTE_REBUILD_FAILED:y==="publish"?G.HISTORY_COMMIT_FAILED:G.WRITE_IO_ERROR}async function Ka(y){if(p=!0,!c.markRecoveryRequired)return G.RECOVERY_REQUIRED;try{return await c.markRecoveryRequired(y),G.RECOVERY_REQUIRED}catch{return G.RECOVERY_PERSIST_FAILED}}function rC(y){let C=y.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(O=>O.charAt(0).toUpperCase()+O.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return C?`Prefab${C}`:"GeneratedPrefab"}function zu(y){return y==="VERSION_STALE"?G.VERSION_STALE:y==="CROSS_PAGE_MOVE_UNSUPPORTED"?G.CROSS_PAGE_MOVE_UNSUPPORTED:G.UNSUPPORTED_OPERATION}async function sh(y){if(y.target.kind==="route"){let C=i.get(o.resolveSelector(y.target.composition).key)??null;return C?(C.graph||await Va(C.key),C):ie(y,G.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(y.target.kind==="page-unit"){let C=i.get(o.resolveSelector(y.target.composition).key)??null;return C?(C.graph||await Va(C.key),C):ie(y,G.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(y.target.kind==="page-block"){let C=i.get(o.resolveSelector(y.target.composition).key)??null;return C?(C.graph||await Va(C.key),C):ie(y,G.ROUTE_NOT_FOUND,"Composition not found for page-block target.")}if(y.target.kind!=="node")return ie(y,G.UNSUPPORTED_OPERATION,`${y.kind} source target execution is not implemented yet.`);let P=i.get(o.resolveSelector(y.composition).key)??null;return P?(P.graph||await Va(P.key),oh(P,y.target.key)?P:ie(y,G.NODE_NOT_FOUND,`Target key not found: ${y.target.key}`)):ie(y,G.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(),m.clear()},registerComposition(y,P){let C=o.register({context:y,entryFile:P}),O=i.get(C.key);if(O?.entryFile===P)return;O&&_(O);let U=vv(C.context,P);i.set(C.key,U),I(U,U.dependencyFiles),r.emit({type:"graph-invalidated",composition:C.context})},unregisterComposition(y){let P=o.resolveSelector(y),C=i.get(P.key);C&&(_(C),i.delete(P.key),o.unregister(P.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:P.context}))},getCompositionEntryFiles(){return[...i.values()].map(y=>y.entryFile)},getCompositionContext(y){return o.resolveSelector(y).context},async initializeComposition(y){let P=o.resolveSelector(y),C=i.get(P.key);if(!C)throw new Error(`Composition not registered: ${P.key}`);if(C.graph)t="ready";else{t="building";try{let O=await n.readFile(C.entryFile);await Ee(P.key,O),t="ready",r.emit({type:"graph-ready",composition:P.context,version:i.get(P.key)?.graph?.version??0})}catch(O){throw t="idle",r.emit({type:"graph-error",composition:P.context,message:on(O)}),O}}},getDocument(y){let P=o.resolveSelector(y),C=i.get(P.key);if(!C)throw new Error(`Composition not registered: ${P.key}`);if(!C.document)throw new Error(`Composition not built: ${P.key}`);return C.document},async getHistoryStatus(){await x;let y=await c.getStatus?.();return y?{...y,recoveryRequired:p}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:p}},getObjectEditContext(y,P,C){let O=ii(y,P),U=pn(y)??y;if(O?.graph&&O.topology&&O.capabilities&&O.detailProjections){let V=O.detailProjections.get(U);if(V){let Y=O.graph.elements.get(U);if(!Y)throw new Error(`Key not found: ${y}`);let Q=AB(y,U,C),ce=new Map;if(V.isRepeat&&Q?.instanceIndex!==void 0)for(let fe of Y.attributes??[])ce.set(fe.name,am({file:Y.sourceFile,source:d.get(Y.sourceFile)??"",element:Y,propertyName:fe.name,selectionRef:Q,graph:O.graph,sources:d}));let re=$I({element:Y,graph:O.graph,source:d.get(Y.sourceFile),documentVersion:O.graph.version,selectionRef:C,isRepeat:V.isRepeat,propertyProvenance:V.propertyProvenances,repeatTargets:ce}),ne=KI(U,O.graph,O.topology,O.capabilities,V.textSources,V.provenances,V.dynamicData,re);return y===U?ne:mv(ne,y,O.document??null,O.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${y}`)},getRenderDetail(y,P){let C=ii(y,P),O=pn(y)??y;if(C?.graph&&C.topology&&C.capabilities&&C.detailProjections){let U=C.detailProjections.get(O);if(U){let V=VI(O,C.graph,C.topology,C.capabilities,U.textSources,U.writeTarget,U.provenances,U.conditional,U.componentSemantic,U.styleSource,U.dynamicData);return y===O?V:pv(V,y,C.document??null,C.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${y}`)},getClassNameSource(y,P){let C=ii(y,P),O=pn(y)??y;if(!C?.graph)throw new Error(`Key not found: ${y}`);let U=C.graph.elements.get(O);if(!U)throw new Error(`Key not found: ${y}`);let V=d.get(U.sourceFile);if(V===void 0)throw new Error(`Source not loaded: ${U.sourceFile}`);return Rd({key:O,route:{composition:C.composition,routeId:C.routeId,graph:C.graph,source:V}})},refreshSourceForKey:ja,async execute(y){if(await x,p)return ie(y,G.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(y.kind==="source-edit")return B(y);if(y.kind==="insert-page-resource")return K(y);if(y.kind==="delete-page-source")return X(y);let P=await sh(y);if("ok"in P)return P;await N(y);let C=await sh(y);if("ok"in C)return C;let O=C;if(y.target.kind==="page-unit"){let ne=y;return y.kind==="insert-child"||y.kind==="replace-node"?te(ne,O):y.kind==="move-node"||y.kind==="remove-node"?Qe(ne,O):ie(y,G.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}if(y.target.kind==="page-block"){let ne=y;return y.kind==="insert-child"||y.kind==="replace-node"?Re(ne,O):y.kind==="move-node"||y.kind==="remove-node"?ue(ne,O):ie(y,G.UNSUPPORTED_OPERATION,"Page-block operation is not supported by the current structural transaction.")}let V=y.params,Y=y.target.kind==="node"?y.target.key:null;if(V.kind==="move-node"&&"kind"in V.target&&V.target.kind==="source-sibling"){let ne=V.target,fe=Y?O.document?.entries.find(ae=>ae.key===Y):null,be=O.document?.entries.find(ae=>ae.key===ne.anchorKey),Be=fe?.pageCompositionActionScope,me=Be?.kind==="source-siblings"?Be.siblingKeys:null,Xe=me?.indexOf(fe?.key??"")??-1,Fe=me?.indexOf(ne.anchorKey)??-1,H=ne.relation==="before"?Xe-1:Xe+1;if(!fe||!be||!me||Xe<0||Fe!==H||be.pageCompositionActionScope?.kind!=="source-siblings"||be.pageCompositionActionScope.siblingKeys.length!==me.length||be.pageCompositionActionScope.siblingKeys.some((ae,Pe)=>ae!==me[Pe])||!fe.operationSummary.canMove)return ie(y,G.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!O.graph||!O.topology||!O.capabilities)return{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!1,resultVersion:Z(y),error:{code:y.target.kind==="route"?G.ROUTE_NOT_FOUND:G.NODE_NOT_FOUND,message:y.target.kind==="route"?"Composition not ready for route target.":y.target.kind==="node"?`Target key not found: ${y.target.key}`:`${y.kind} source target execution is not implemented yet.`}};let Q=WB(O,O.graph,O.capabilities,d,i),ce=await new Ol(Q).plan(y);if(!ce.ok)return{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!1,resultVersion:Z(y),error:{code:xa(ce.errorCode),message:ce.reason}};let re=ce.plan;if(re.steps.length===0)return y.kind==="set-props"?{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!0,resultVersion:Z(y),affectedFiles:[]}:{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!1,resultVersion:Z(y),error:{code:G.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};g+=1;try{if(re.steps.some(fe=>fe.type==="invoke-external-adapter")){let fe=await u.execute(re);if(!fe.ok)return ie(y,xa(fe.errorCode),fe.reason);let be={composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!0,resultVersion:Math.max(Z(y),fe.resultVersion),affectedFiles:fe.affectedFiles,...fe.selectionRef?{selectionRef:fe.selectionRef}:{}};return tr(be,{rebuiltRoutes:[],failedRoutes:[]}),be}let ne=await u.prepareRewritePlan(re);return ne.ok?await Vr({request:y,filePlan:ne.filePlan,...ne.selectionRef?{selectionRef:ne.selectionRef}:{}}):ie(y,xa(ne.errorCode),ne.reason)}catch(ne){return{composition:o.resolveSelector(y.composition).context,requestId:y.id,kind:y.kind,target:y.target,ok:!1,resultVersion:Z(y),error:{code:G.INTERNAL_ERROR,message:on(ne)}}}finally{g-=1}},async undo(y){if(await x,p)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:z(o.entries[0].key),error:{code:G.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};g+=1;try{return await eh("undo")}finally{g-=1}},async redo(y){if(await x,p)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:z(o.entries[0].key),error:{code:G.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};g+=1;try{return await eh("redo")}finally{g-=1}},notifyFileChanged(y){_r([y])},getAffectedCompositions(y){return ee(y)},subscribe(y){return r.subscribe(y)}}}function UB(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function VB(e,t,n,r){let o=new Map,i=new Map,s=(d,f,m)=>{let g=d.get(f)??new Set,p=g.size;return g.add(m),d.set(f,g),g.size!==p},a=(d,f)=>{if(!d.importedFrom)return!1;if(d.exportName==="default")return s(i,d.importedFrom,f);let m=s(o,`${d.importedFrom}#${d.tag}`,f);return d.exportName&&d.exportName!==d.tag&&(m=s(o,`${d.importedFrom}#${d.exportName}`,f)||m),m},l=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(g=>g.members.some(p=>p.sourceRange!==null&&ba(d.sourceRange,p.sourceRange)));if(!f)continue;let m=f.placementUnitKey;a(d,m)}let c=!0;for(;c;){c=!1;for(let d of t.elements.values()){if(d.sourceFile===n.entryFile||!d.importedFrom||!/^[A-Z]/.test(d.tag))continue;let f=l(d);if(f)for(let m of f)c=a(d,m)||c}}let u=n.placements.find(d=>d.placementKey===n.container.placementKey&&d.relation==="append");for(let d of e.entries){let f=pn(d.key)??d.key,m=t.elements.get(d.key)??t.elements.get(f);if(!m)continue;if(m.sourceFile===n.entryFile){if(n.container.sourceRange&&ba(m.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let h=n.placements.find(x=>x.members.some(b=>b.sourceRange!==null&&(ba(m.sourceRange,b.sourceRange)||HB(b.sourceRange,m.sourceRange))));if(h){d.pageCompositionUnitKey=h.placementUnitKey;continue}}let g=o.get(`${m.sourceFile}#${m.componentName}`);if(g){g.size===1&&(d.pageCompositionUnitKey=g.values().next().value);continue}let p=i.get(m.sourceFile);p?.size===1&&(d.pageCompositionUnitKey=p.values().next().value)}KB(e,t,n,r)}function KB(e,t,n,r){let o=new Map(e.entries.map(f=>[f.key,f])),i=e.entries.filter(f=>{let m=f.pageCompositionUnitKey;return m?f.parentKey?o.get(f.parentKey)?.pageCompositionUnitKey!==m:!0:!1}),s=new Map,a=(f,m)=>{s.set(f,Math.min(2,(s.get(f)??0)+m))},l=f=>n.placements.some(m=>m.members.some(g=>g.sourceRange!==null&&ba(f.sourceRange,g.sourceRange)));for(let f of t.elements.values())f.sourceFile!==n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag)||!l(f)||a(`${f.importedFrom}#${f.exportName??f.tag}`,1);let c=[...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<=c.length;f+=1){let m=!1;for(let g of c){let p=s.get(g.owner)??s.get(g.ownerDefault)??0;if(!p)continue;let h=s.get(g.target)??0,x=Math.min(2,h+p);x!==h&&(s.set(g.target,x),m=!0)}if(!m)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 m=t.elements.get(f.key);f.pageCompositionUnitKey&&m?.sourceFile===n.entryFile&&(f.pageCompositionActionScope={kind:"route-unit"})}let d=new Map;for(let f of i){let m=t.elements.get(f.key);if(!m||m.sourceFile===n.entryFile||f.key!==(pn(f.key)??f.key))continue;let g=r.get(m.sourceFile);if(!g)continue;let p=De(g.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:m.sourceRange});if(!p.ok||!p.match.path.isJSXElement())continue;let h=p.match.path,x=h.parentPath;if(!x||!x.isJSXFragment()&&!(x.isJSXElement()&>(x))){u(m)===1&&Cv(h)&&(f.pageCompositionActionScope={kind:"route-unit"});continue}if(!Cv(x))continue;let b=d.get(x.node)??[];b.push({entry:f,element:m,parentPath:x}),d.set(x.node,b)}for(let f of d.values()){let m=f[0];if(!m)continue;let g=m.entry.pageCompositionUnitKey,p=[],h=!!(g&&u(m.element)===1);for(let b of m.parentPath.node.children){if(JB(b))continue;if(!XB(b)){h=!1;break}let E=[...t.elements.values()].find(v=>v.sourceFile===m.element.sourceFile&&v.componentName===m.element.componentName&&ba(v.sourceRange,zB(b))),S=E?o.get(E.identity.key):null;if(!E||!S||S.parentKey||S.pageCompositionUnitKey!==g||u(E)!==1){h=!1;break}p.push(S)}if(!h||p.length!==f.length||f.some(({entry:b})=>!p.some(E=>E.key===b.key)))continue;if(p.length===1){p[0].pageCompositionActionScope={kind:"route-unit"};continue}if(p.length<2)continue;let x=p.map(b=>b.key);for(let b of p)b.pageCompositionActionScope={kind:"source-siblings",siblingKeys:x}}}function Cv(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function JB(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function XB(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function zB(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 ba(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function HB(e,t){return Rv(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Rv(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Rv(e,t,n,r){return e!==n?e-n:t-r}function WB(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 m of f?.childKeys??[])a(m,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=l(u),f=t.elements.get(d.baseKey);return f?c(u,f):null},getChildNodes(u){let d=l(u),m=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(m)return m.map(p=>{let h=pn(p)??p,x=t.elements.get(h);return x?c(p,x):null}).filter(p=>p!==null);let g=t.elements.get(d.baseKey);return g?g.childKeys.map(p=>{let h=t.elements.get(p);return h?c(p,h):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=l(u),f=n.get(d.baseKey);return f?{...f,key:u,constraints:f.constraints.map(m=>({...m})),...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=l(u);return e.detailProjections?.get(d.baseKey)?.componentSemantic??null},getClassNameSource(u){let d=l(u),f=t.elements.get(d.baseKey),m=f?r.get(f.sourceFile):void 0;return!f||m===void 0?null:Rd({key:d.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:m}})},getEditableTextSegmentIndex(u){let d=l(u),m=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return m&&!m.done?m.value:null},async getTextWriteTarget(u,d){let f=l(u);return Tm(e.detailProjections?.get(f.baseKey)?.textTargets.get(d)??null,f.repeatIndex)},async getElementPropertyWriteTarget(u,d){let f=l(u);return Tm(e.detailProjections?.get(f.baseKey)?.elementPropertyTargets.get(d)??null,f.repeatIndex)},getPropertyState(u,d,f){let m=l(u),g=t.elements.get(m.baseKey);if(!g)return null;let h=e.detailProjections?.get(m.baseKey)?.propertyProvenances.get(d);if(h)return h;let x=g.attributes?.find(b=>b.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:g.sourceFile,sourceRange:x.sourceRange}}:(g.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 m=l(u),g=t.elements.get(m.baseKey);if(!g)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let p=f?{...f,key:m.baseKey}:m.repeatIndex!==null?{key:m.baseKey,instanceIndex:m.repeatIndex}:void 0;return am({file:g.sourceFile,source:r.get(g.sourceFile)??"",element:g,propertyName:d,selectionRef:p,graph:t,sources:r})},getTextProvenance(u,d){let f=l(u);return e.detailProjections?.get(f.baseKey)?.provenances.get(d)??null}};function l(u){let d=bB(u);return d?{baseKey:d.baseKey,repeatIndex:fv(e.document??null,u,d.baseKey,e.documentIndex)??dv(d)}:{baseKey:u,repeatIndex:null}}function c(u,d){let f=pn(u)??u,m=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:m?.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(g=>({name:g.name,value:g.value,source:g.source?{expression:g.source.expression,base:g.source.base,path:g.source.path.map(p=>({...p}))}:null,resolvedValue:g.resolvedValue}))}}}var GB={"stale-version":G.VERSION_STALE,"capability-denied":G.CAPABILITY_REJECTED,"invalid-params":G.INVALID_PARAMS,"locator-miss":G.LOCATOR_FAILED,"route-not-found":G.ROUTE_NOT_FOUND,"unsupported-operation":G.UNSUPPORTED_OPERATION,"invalid-target":G.INVALID_TARGET,"ast-error":G.AST_PARSE_ERROR,"writeback-failed":G.WRITE_IO_ERROR,"rollback-failed":G.RECOVERY_REQUIRED,unknown:G.INTERNAL_ERROR};function xa(e){return GB[e]}function on(e){return e instanceof Error&&e.message?e.message:String(e)}function Pv(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function YB(e){let t=qo(e);if(!IB.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=>vB.map(a=>`${s}/${a}`))}function ZB(e){let n=qo(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function qB(e){return Tv(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function QB(e){return Tv(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Tv(e,t){let n=[];for(let r of e.matchAll(t)){let o=wv(r[1]??"");o&&n.push(o)}return n}function Nv(e,t){let n=wv(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?qo(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?qo(`${ej(e)}/${n}`):n.startsWith("/")?qo(n.slice(1)):Lm(n)?qo(n):null}function wv(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Lm(e){return/\.css$/i.test(e)}function ej(e){let t=qo(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function tj(e){return Array.from(new Set(e))}function qo(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 nj(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 mu=class{constructor(t){this.options=t,this.fileSystem=new ls(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Ya(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 Za(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return ec(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return tc(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return nc(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=oj.safeParse(t);if(!n.success)return{result:Ga(t,n.error.issues.map(i=>i.message))};let r=new ls(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 l=ij.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(c=>sj(c,t.kind==="source-edit")),changedCompositions:o.getAffectedCompositions(a.map(c=>c.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:l.patches.map(c=>c.path),composition:i.composition,at:new Date().toISOString()}),{result:s,patchPlan:l}}finally{o.dispose()}}dispose(){this.engine.dispose()}createEngine(t,n={}){let r=n.emitEvents??!0;return pu({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=qa(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 sj(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:je(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:je(e.before)},fullContent:e.after}}function aj(e){return new mu(e)}import{SiteEditOperationRequestSchema as uj}from"@vcp-dev/contracts";import er from"node:fs/promises";import sn from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as cj,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as lj}from"@vcp-dev/contracts";var gu=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=pu({...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 ec(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return tc(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return nc(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 er.readFile(sn.join(n,r),"utf8")},async readFileBytes(r){return er.readFile(sn.join(n,r))},async getFileInfo(r){let o=sn.join(n,...r.split("/"));try{let i=await er.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 er.mkdir(sn.dirname(i),{recursive:!0});let s=await er.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await er.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await er.rm(sn.join(n,r),{force:!0});let o=r.replace(/\\/g,"/"),i=["components/site/generated","src/components/site/generated"].find(l=>o.startsWith(`${l}/`));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 er.rmdir(a)}catch(l){if(l instanceof Error&&"code"in l&&l.code==="ENOENT"){a=sn.dirname(a);continue}break}a=sn.dirname(a)}},async exists(r){try{return await er.access(sn.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...lj,...cj],i=[],s=new Set,a=new Set,l=0;for(let d of o)await u(d,i,1);let c=i.sort((d,f)=>d.path.localeCompare(f.path));return a.size>0?{files:c,truncated:{reasons:[...a]}}:{files:c};async function u(d,f,m){if(r.maxDepth!==void 0&&m>r.maxDepth){a.add("max-depth");return}let g=sn.join(n,...d.split("/")),p;try{p=await er.lstat(g)}catch{return}if(p.isSymbolicLink())return;if(p.isFile()){let x=p.ino>0?`${String(p.dev)}:${String(p.ino)}`:null;if(x&&s.has(x))return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&l+p.size>r.maxTotalBytes){a.add("max-total-bytes");return}x&&s.add(x),f.push({path:d,sizeBytes:p.size}),l+=p.size;return}if(!p.isDirectory())return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}let h=await er.readdir(g,{withFileTypes:!0});for(let x of h)x.isSymbolicLink()||await u(`${d}/${x.name}`,f,m+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function Fm(e){return new gu(e)}var hu=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Fm({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=qa(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:Ya(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:Za(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=uj.safeParse(r);if(!o.success)return Ga(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 dj(e){return new hu(e)}import{GeneratedSiteCapabilitiesSchema as yj}from"@vcp-dev/contracts";import{GeneratedSiteCapabilitiesSchema as fj}from"@vcp-dev/contracts";function Vi(e){let t=mj(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?gj(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"):Ov(e.node.path,n)?Br(e.node,"platform-managed","controlled platform path"):t?Fv(e.node.path,t.generated_sections_path)?Br(e.node,"private","site-generated section path"):Ov(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 pj(e){return e.nodes.map(t=>Vi({...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 mj(e){let t=fj.safeParse(e);return t.success?t.data:null}function gj(e,t){return t.runtime_dependencies.some(({name:n})=>e===n||e.startsWith(`${n}/`))}function Ov(e,t){return t.some(n=>Fv(e,n))}function Fv(e,t){let n=hj(t),r=Dv(e);return n.endsWith("/*")?r.startsWith(n.slice(0,-1)):Lv(r)===Lv(n)}function hj(e){return Dv(e.split("#",1)[0]??e)}function Dv(e){return e.replace(/^@\//u,"").replace(/\\/g,"/").replace(/^\.\//u,"")}function Lv(e){return e.replace(/\.(?:jsx?|tsx?|json)$/iu,"")}function yu(e){let t=yj.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=Vi({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=xj(n).sort(bj);return{complete:o.length===0,nodes:r.sort(Ej),edges:[...e.closure.edges].sort(Sj),errors:o}}function xj(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function bj(e,t){return Nn(e.path,t.path)||Nn(e.code,t.code)||Nn(e.specifier??"",t.specifier??"")||Nn(e.message,t.message)}function Ej(e,t){return Nn(e.path,t.path)||Nn(e.kind,t.kind)||Nn(e.ownership,t.ownership)||Nn(e.status,t.status)}function Sj(e,t){return Nn(e.from,t.from)||Nn(e.target??"",t.target??"")||Nn(e.specifier??"",t.specifier??"")||Nn(e.kind,t.kind)||Nn(e.resolution,t.resolution)}function Nn(e,t){return e<t?-1:e>t?1:0}var Mv={helper:"text",tsType:"string"},Dm={helper:"images",tsType:"MediaItem[]",importName:"MediaItem"},Bv={helper:"image",tsType:"MediaItem | null",importName:"MediaItem"},jv=/(gallery|galleries|images|photos|pics|pictures|album|attachments|files|media)$/i;function Ij(e,t,n){switch(e){case"text":case"date":return Mv;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"||jv.test(n)?Dm:Bv;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 Mm(e,t,n){if(n){let r=Ij(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{...jv.test(t)?Dm:Bv};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{...Mv}}}function Bm(e,t,n={}){let r=`${kj(e)}View`,o=t.filter(c=>c.front_display!=="forbidden").map(c=>{let u={key:vj(c.name)?`${c.name}_field`:c.name,source:c.name,...Mm(c.cms_type,c.name,c.value_shape)};return n.forceMultiMedia?.has(c.name)?{...u,helper:"images",tsType:"MediaItem[]",importName:"MediaItem"}:u}),i=[...new Set(o.map(c=>c.importName).filter(Boolean))],s=i.length?n.inferFieldTypesFromCms?i.map(c=>`type ${c} = ReturnType<typeof cms.field.${c==="MediaItem"?"images":"category"}>[number];`).join(`
|
|
15
15
|
`)+`
|
|
16
16
|
`:`import type { ${i.join(", ")} } from "@/lib/cms/field";
|
|
17
17
|
`:"",a=o.map(c=>` ${c.key}: ${c.tsType};`).join(`
|
|
@@ -36,18 +36,22 @@ export function to${r}(rec: CollectionRecord): ${r} {
|
|
|
36
36
|
${l}
|
|
37
37
|
};
|
|
38
38
|
}
|
|
39
|
-
`}function sj(e){return e==="id"||e==="url"||e==="seo"}function aj(e){return e.replace(/(^|[-_])([a-z0-9])/g,(t,n,r)=>r.toUpperCase())}import{createHash as du}from"node:crypto";import{BlockRenderRefSchema as z$,GeneratedSiteCapabilitiesSchema as H$,PORTABLE_AUDITED_PLACEHOLDER_SVG as mg,PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as o_,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as W$,SiteEditPageBlockTargetSchema as G$,SiteEditPortableExportResultSchema as Y$}from"@vcp-dev/contracts";import{SiteEditPageBlockTargetSchema as cj,SiteIdSchema as lj,SnapshotIdSchema as uj}from"@vcp-dev/contracts";async function mm(e){if(!lj.safeParse(e.site_id).success||!uj.safeParse(e.base_snapshot_id).success||!cj.safeParse(e.target).success)return ir("INVALID_PARAMS","Invalid site, snapshot, or page block identity.");if(!fj(e.composition,e.target.composition))return ir("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(!pm(u))return ir("INVALID_PARAMS","Snapshot contains an unsafe source path.");let f=typeof d=="string"?d:dj(u,d);f!==null&&(n.set(u,f),/\.(?:[cm]?[jt]sx?)$/i.test(u)&&t.set(u,f))}let r;try{r=wc({files:n})}catch{return ir("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 ir("INVALID_TARGET","The requested route/template is absent from this snapshot.");let i=t.get(o.entryFile);if(i===void 0)return ir("INVALID_TARGET","The selected composition entry is unavailable.");let s=await zo(o.entryFile,i,async u=>{if(!pm(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=>pm(u)&&t.has(u),{version:e.document_version});if(s.diagnostics.length>0||!s.entryModule)return ir("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=On({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 ir("INVALID_TARGET","The selected snapshot page composition is unsupported.");let l=_c({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection});if(l.diagnostics.length>0)return ir("INVALID_TARGET","The selected snapshot has unproven page block roots.");let c=ps({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection,documentVersion:e.document_version,roots:l.roots});return c.diagnostics.length>0?{...ir("INVALID_TARGET","The selected snapshot block index is incomplete."),index:c}:{...ni(c,e.target,e.document_version,e.selection_ref),index:c}}function dj(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 pm(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function fj(e,t){return e.routeId===t.routeId&&e.templateId===t.templateId}function ir(e,t){return{ok:!1,code:e,message:t}}import{createHash as Rj}from"node:crypto";import zs from"node:path";import xm from"@babel/generator";import{parse as Pj}from"@babel/parser";import Cj from"@babel/traverse";import*as F from"@babel/types";import{SiteEditSourcePathSchema as Nj}from"@vcp-dev/contracts";import*as Gt from"@babel/types";var bI=[".tsx",".ts",".jsx",".js"],pj=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 ar(e){let t=hj(e.files),n=SI(e.max_depth??32,"max_depth"),r=SI(e.max_nodes??512,"max_nodes"),o=[...new Set(e.entry_files.map(kI).filter(Boolean))],i=new Map,s=[],a=[],l=new Set,c=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||c.has(p))){if(!vi(p,l,r)){a.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:p,message:"Portable source closure node budget was exhausted."});continue}c.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 h=t.get(p.path);if(h===void 0){let P=o.includes(p.path)?"SOURCE_ENTRY_UNRESOLVED":Ii(p.path)?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED";Zr(i,{path:p.path,kind:Ii(p.path)?"asset":"source",depth:p.depth,status:"unresolved"}),a.push({code:P,path:p.path,message:`Portable source closure could not read ${p.path}.`});continue}let x=Ii(p.path)?"asset":"source";if(x==="asset"){let P=yj(p.path,h);Zr(i,{path:p.path,kind:x,depth:p.depth,status:P?"parse-failed":"complete"}),P&&a.push(P);continue}let E=hm(h),b=Ee(p.path,E);if(!b.ok){Zr(i,{path:p.path,kind:x,depth:p.depth,status:"parse-failed"}),a.push({code:"SOURCE_PARSE_FAILED",path:p.path,message:b.diagnostic.message});continue}let S=gj(b.module.ast),v=!1;for(let P of S){let I=mj({from:p.path,depth:p.depth,reference:P,files:t,nodes:i,errors:a,maxDepth:n,maxNodes:r,visited:u,queued:c,discovered:l});s.push(I.edge),I.next&&(I.next.depth>n?v=!0:!u.has(I.next.path)&&!c.has(I.next.path)&&(c.add(I.next.path),d.push(I.next))),I.depthExhausted&&(v=!0)}Zr(i,{path:p.path,kind:x,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(Ij),g=Sj(s).sort(kj),m=vj(a).sort(_j);return{entry_files:o.sort(sr),nodes:f,edges:g,errors:m,complete:m.length===0,budget:{max_depth:n,max_nodes:r}}}function mj(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=bj(t.specifier);return vi(o,e.discovered,e.maxNodes)?(Zr(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=ym(e.from,t.specifier);if(_I(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}.`}),vi(n,e.discovered,e.maxNodes)?Zr(e.nodes,{path:n,kind:Ii(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=II(e.from,t.specifier,e.files);if(!r){let o=Ii(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}.`}),vi(n,e.discovered,e.maxNodes)?Zr(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=Ii(r)?"asset":"source";return vi(r,e.discovered,e.maxNodes)?Zr(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 vi(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 gj(e){let t=[];for(let n of e.program.body)Gt.isImportDeclaration(n)?t.push({specifier:n.source.value,kind:n.importKind==="type"?"type":"import"}):Gt.isExportNamedDeclaration(n)&&n.source?t.push({specifier:n.source.value,kind:"export"}):Gt.isExportAllDeclaration(n)&&t.push({specifier:n.source.value,kind:"export"});return gm(e.program,n=>{if(Gt.isCallExpression(n)&&Gt.isImport(n.callee)){let r=n.arguments[0];Gt.isStringLiteral(r)?t.push({specifier:r.value,kind:"dynamic"}):t.push({specifier:null,kind:"dynamic"})}Gt.isTSImportType(n)&&t.push({specifier:Gt.isStringLiteral(n.argument)?n.argument.value:null,kind:"type"})}),Ej(t)}function gm(e,t){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let r of n)vI(r)&&gm(r,t);else vI(n)&&gm(n,t)}function ht(e,t,n){let r=ym(e,t);return!mt(t)||_I(e,t,r)?null:II(e,t,n)}function II(e,t,n){let r=ym(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(xj(o))return null;for(let i of bI){let s=`${o}${i}`;if(n.has(s))return s}for(let i of bI){let s=`${o}/index${i}`;if(n.has(s))return s}return null}function ym(e,t){let n=Kn(e,t);return kI(n)}function kI(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 hj(e){return e instanceof Map?e:new Map(Object.entries(e))}function hm(e){return typeof e=="string"?e:Buffer.from(e).toString("utf8")}function yj(e,t){if(e.toLowerCase().endsWith(".css")&&/[@\\]|url\s*\(/iu.test(hm(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(hm(t))}catch{return{code:"SOURCE_ASSET_INVALID",path:e,message:`Portable source closure found invalid JSON asset: ${e}.`}}return null}function Zr(e,t){let n=e.get(t.path);(!n||EI(t.status)>EI(n.status))&&e.set(t.path,t)}function vi(e,t,n){return t.has(e)?!0:t.size>=n?!1:(t.add(e),!0)}function EI(e){return e==="complete"?1:0}function Ii(e){let n=e.replace(/[?#].*$/u,"").split(".").pop()?.toLowerCase();return n!==void 0&&pj.has(n)}function xj(e){return/\.[a-z0-9]+$/iu.test(e)}function bj(e){return e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0]??e}function Ej(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 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 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 Ij(e,t){return sr(e.path,t.path)||sr(e.kind,t.kind)}function kj(e,t){return sr(e.from,t.from)||sr(e.target??"",t.target??"")||sr(e.specifier??"",t.specifier??"")||sr(e.kind,t.kind)}function _j(e,t){return sr(e.path,t.path)||sr(e.code,t.code)||sr(e.specifier??"",t.specifier??"")}function sr(e,t){return e<t?-1:e>t?1:0}function SI(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`Portable source closure ${t} must be a positive safe integer.`);return e}function vI(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function _I(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 bm=Cj,km=typeof bm=="function"?bm:bm.default,Aj=typeof xm=="function"?xm:xm.default,RI=new Set(["Array","Boolean","Infinity","JSON","Math","NaN","Number","Object","String","undefined"]),TI=new Map([["JSON",new Set(["stringify"])],["Object",new Set(["keys","values","entries","getOwnPropertyNames"])],["Array",new Set(["isArray"])]]),wI=new Set(["Boolean","Number","String"]),Tj=new Set(["assign","values","entries"]);function _m(e){let{selection:t,files:n}=e,r=t.strategy==="extract-jsx"||t.strategy==="collection-container"?t.entry_file:t.source_file;if(!Im(r))return Bt("SOURCE_INPUT_INVALID",r,"The selected Portable entry path is not safe.");if(!Nj.safeParse(t.source_file).success)return Bt("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 Bt("SOURCE_NOT_PORTABLE",t.source_file,"Nested component invocation bindings are not yet a proven independent entry.");if(t.invocation&&!t.invocation.complete)return Bt("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 Bt("SOURCE_INPUT_INVALID",t.entry_file,"A reusable entry must point at the proven selected component source.");let i=Ul(n,t.source_file);return i===null||!AI(t,i)?Bt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The reusable selected source is missing or does not match its pinned hash."):Bl({entryFile:r,entryContent:i,files:n,selection:t})}let o=Ul(n,t.source_file);if(o===null||!AI(t,o))return Bt("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 Bl({entryFile:r,entryContent:o,files:n,selection:t,sourceMapping:i})}if(t.strategy==="collection-container"){let i=t.collection_container_file;if(!i||!Im(i)||!n.has(i)||n.has(r)||!t.invocation?.complete)return Bt("SOURCE_INPUT_INVALID",r,"The proven collection container or isolated entry is unavailable.");let s=Dr({component:"PortableCollection",bindings:t.invocation.bindings,targetBlockId:"portable-captured-collection"});if(!s.ok)return Bt("SOURCE_NOT_PORTABLE",r,"The collection invocation has unsupported bindings.");let a=s.plan.requiresRouteSearchParams?"{searchParams}: {searchParams?: Promise<Record<string, string | string[] | undefined>>}":"",l=`import PortableCollection from ${JSON.stringify(`@/${i.replace(/\.[cm]?[jt]sx?$/u,"")}`)};
|
|
39
|
+
`}function vj(e){return e==="id"||e==="url"||e==="seo"}function kj(e){return e.replace(/(^|[-_])([a-z0-9])/g,(t,n,r)=>r.toUpperCase())}import{createHash as Bu}from"node:crypto";import{BlockRenderRefSchema as sU,GeneratedSiteCapabilitiesSchema as aU,PORTABLE_AUDITED_PLACEHOLDER_SVG as Da,PORTABLE_AUDITED_SAFE_IMAGE as cU,PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as P_,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as lU,SiteEditPageBlockTargetSchema as uU,SiteEditPortableExportResultSchema as dU}from"@vcp-dev/contracts";import{SiteEditPageBlockTargetSchema as _j,SiteIdSchema as Cj,SnapshotIdSchema as Rj}from"@vcp-dev/contracts";async function $m(e){if(!Cj.safeParse(e.site_id).success||!Rj.safeParse(e.base_snapshot_id).success||!_j.safeParse(e.target).success)return Sr("INVALID_PARAMS","Invalid site, snapshot, or page block identity.");if(!Nj(e.composition,e.target.composition))return Sr("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(!jm(u))return Sr("INVALID_PARAMS","Snapshot contains an unsafe source path.");let f=typeof d=="string"?d:Pj(u,d);f!==null&&(n.set(u,f),/\.(?:[cm]?[jt]sx?)$/i.test(u)&&t.set(u,f))}let r;try{r=fl({files:n})}catch{return Sr("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 Sr("INVALID_TARGET","The requested route/template is absent from this snapshot.");let i=t.get(o.entryFile);if(i===void 0)return Sr("INVALID_TARGET","The selected composition entry is unavailable.");let s=await pi(o.entryFile,i,async u=>{if(!jm(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=>jm(u)&&t.has(u),{version:e.document_version});if(s.diagnostics.length>0||!s.entryModule)return Sr("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=Hn({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 Sr("INVALID_TARGET","The selected snapshot page composition is unsupported.");let l=il({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection});if(l.diagnostics.length>0)return Sr("INVALID_TARGET","The selected snapshot has unproven page block roots.");let c=Us({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection,documentVersion:e.document_version,roots:l.roots});return c.diagnostics.length>0?{...Sr("INVALID_TARGET","The selected snapshot block index is incomplete."),index:c}:{...vi(c,e.target,e.document_version,e.selection_ref),index:c}}function Pj(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 jm(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function Nj(e,t){return e.routeId===t.routeId&&e.templateId===t.templateId}function Sr(e,t){return{ok:!1,code:e,message:t}}import{createHash as zj}from"node:crypto";import Ea from"node:path";import Km from"@babel/generator";import{parse as Hj}from"@babel/parser";import Wj from"@babel/traverse";import*as j from"@babel/types";import{SiteEditSourcePathSchema as Gj}from"@vcp-dev/contracts";import*as an from"@babel/types";import{tokenize as Aj,isTokenAtKeyword as Tj,isTokenCloseParen as $v,isTokenFunction as Uv,isTokenString as Vv,isTokenURL as Kv,isTokenWhiteSpaceOrComment as Jv,isTokenBadURL as wj}from"@csstools/css-tokenizer";import Oj from"postcss";function Ki(e,t={}){try{if(Buffer.byteLength(e)>1024*1024)return{complete:!1};t.value_only||Oj.parse(e,{from:void 0});let n=!1,r=Aj({css:e},{onParseError:()=>{n=!0}}),o=r.some(u=>Kv(u)||wj(u)||Uv(u)&&["url","image-set","-webkit-image-set"].includes(u[4].value.toLowerCase()));if(n)return{complete:!1,resource_syntax:o};let i=[],s=[],a=!1,l=(u,d,f)=>{if(!u)throw new Error("Empty resource");i.push({kind:a?"stylesheet":"asset",value:u,start_offset:d,end_offset:f,original_text:e.slice(d,f)}),a=!1},c=u=>{for(;u<r.length&&Jv(r[u]);)u++;return u};for(let u=0;u<r.length;u++){let d=r[u];if(!Jv(d)){if(Tj(d)&&d[4].value.toLowerCase()==="import"){a=!0;continue}if(Kv(d)){l(d[4].value,d[2],d[3]+1);continue}if(Uv(d)){let f=d[4].value.toLowerCase();if(f==="url"){let m=c(u+1),g=r[m],p=c(m+1),h=r[p];if(!Vv(g)||!$v(h))return{complete:!1,resource_syntax:o};l(g[4].value,d[2],h[3]+1),u=p;continue}s.push(f)}else if($v(d))s.pop();else if(Vv(d)&&(a||["image-set","-webkit-image-set"].includes(s.at(-1)??"")))l(d[4].value,d[2],d[3]+1);else if(a)return{complete:!1}}}return a?{complete:!1,resource_syntax:o}:{complete:!0,references:i,resource_syntax:o}}catch{return{complete:!1}}}var Xv=[".tsx",".ts",".jsx",".js"],Lj=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 vr(e){let t=Dj(e.files),n=Wv(e.max_depth??32,"max_depth"),r=Wv(e.max_nodes??512,"max_nodes"),o=[...new Set(e.entry_files.map(Zv).filter(Boolean))],i=new Map,s=[],a=[],l=new Set,c=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||c.has(p))){if(!Ji(p,l,r)){a.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:p,message:"Portable source closure node budget was exhausted."});continue}c.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 h=t.get(p.path);if(h===void 0){let A=o.includes(p.path)?"SOURCE_ENTRY_UNRESOLVED":Xi(p.path)?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED";yo(i,{path:p.path,kind:Xi(p.path)?"asset":"source",depth:p.depth,status:"unresolved"}),a.push({code:A,path:p.path,message:`Portable source closure could not read ${p.path}.`});continue}let x=Xi(p.path)?"asset":"source";if(x==="asset"){let A=Mj(p.path,h);if(yo(i,{path:p.path,kind:x,depth:p.depth,status:A?"parse-failed":"complete"}),A&&a.push(A),!A&&p.path.toLowerCase().endsWith(".css")){let I=Ki(xu(h));if(I.complete)for(let _ of I.references){if(/^https?:\/\//iu.test(_.value)||_.value.startsWith("#"))continue;let k=_.value.startsWith("/")?`@/public${_.value}`:kt(_.value)?_.value:`./${_.value}`,T=zv({from:p.path,depth:p.depth,reference:{specifier:k,kind:"import"},files:t,nodes:i,errors:a,maxDepth:n,maxNodes:r,visited:u,queued:c,discovered:l});s.push(T.edge),T.depthExhausted&&a.push({code:"SOURCE_DEPTH_EXHAUSTED",path:p.path,message:"Stylesheet dependencies exceed the source graph depth budget."}),T.next&&T.next.depth<=n&&!u.has(T.next.path)&&!c.has(T.next.path)&&(c.add(T.next.path),d.push(T.next))}}continue}let b=xu(h),E=Te(p.path,b);if(!E.ok){yo(i,{path:p.path,kind:x,depth:p.depth,status:"parse-failed"}),a.push({code:"SOURCE_PARSE_FAILED",path:p.path,message:E.diagnostic.message});continue}let S=Fj(E.module.ast),v=!1;for(let A of S){let I=zv({from:p.path,depth:p.depth,reference:A,files:t,nodes:i,errors:a,maxDepth:n,maxNodes:r,visited:u,queued:c,discovered:l});s.push(I.edge),I.next&&(I.next.depth>n?v=!0:!u.has(I.next.path)&&!c.has(I.next.path)&&(c.add(I.next.path),d.push(I.next))),I.depthExhausted&&(v=!0)}yo(i,{path:p.path,kind:x,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(Kj),m=Uj(s).sort(Jj),g=Vj(a).sort(Xj);return{entry_files:o.sort(Ir),nodes:f,edges:m,errors:g,complete:g.length===0,budget:{max_depth:n,max_nodes:r}}}function zv(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(!kt(t.specifier)){let o=jj(t.specifier);return Ji(o,e.discovered,e.maxNodes)?(yo(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=Vm(e.from,t.specifier);if(qv(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)?yo(e.nodes,{path:n,kind:Xi(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=Yv(e.from,t.specifier,e.files);if(!r){let o=Xi(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)?yo(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=Xi(r)?"asset":"source";return Ji(r,e.discovered,e.maxNodes)?yo(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 Um(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 Um(e,t){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let r of n)Gv(r)&&Um(r,t);else Gv(n)&&Um(n,t)}function At(e,t,n){let r=Vm(e,t);return!kt(t)||qv(e,t,r)?null:Yv(e,t,n)}function Yv(e,t,n){let r=Vm(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 Xv){let s=`${o}${i}`;if(n.has(s))return s}for(let i of Xv){let s=`${o}/index${i}`;if(n.has(s))return s}return null}function Vm(e,t){let n=rr(e,t);return Zv(n)}function Zv(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 xu(e){return typeof e=="string"?e:Buffer.from(e).toString("utf8")}function Mj(e,t){if(e.toLowerCase().endsWith(".css")&&!Ki(xu(t)).complete)return{code:"SOURCE_ASSET_INVALID",path:e,message:"A stylesheet dependency is invalid or requires a finite resource declaration."};if(e.replace(/[?#].*$/u,"").toLowerCase().endsWith(".json"))try{JSON.parse(xu(t))}catch{return{code:"SOURCE_ASSET_INVALID",path:e,message:`Portable source closure found invalid JSON asset: ${e}.`}}return null}function yo(e,t){let n=e.get(t.path);(!n||Hv(t.status)>Hv(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 Hv(e){return e==="complete"?1:0}function Xi(e){let n=e.replace(/[?#].*$/u,"").split(".").pop()?.toLowerCase();return n!==void 0&&Lj.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 Kj(e,t){return Ir(e.path,t.path)||Ir(e.kind,t.kind)}function Jj(e,t){return Ir(e.from,t.from)||Ir(e.target??"",t.target??"")||Ir(e.specifier??"",t.specifier??"")||Ir(e.kind,t.kind)}function Xj(e,t){return Ir(e.path,t.path)||Ir(e.code,t.code)||Ir(e.specifier??"",t.specifier??"")}function Ir(e,t){return e<t?-1:e>t?1:0}function Wv(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`Portable source closure ${t} must be a positive safe integer.`);return e}function Gv(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function qv(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,Gm=typeof Jm=="function"?Jm:Jm.default,Yj=typeof Km=="function"?Km:Km.default,Qv=new Set(["Array","Boolean","Infinity","JSON","Math","NaN","Number","Object","String","undefined"]),ok=new Map([["JSON",new Set(["stringify"])],["Object",new Set(["keys","values","entries","getOwnPropertyNames"])],["Array",new Set(["isArray"])]]),ik=new Set(["Boolean","Number","String"]),Zj=new Set(["assign","values","entries"]);function Ym(e){let{selection:t,files:n}=e,r=t.strategy==="extract-jsx"||t.strategy==="collection-container"?t.entry_file:t.source_file;if(!Wm(r))return Gt("SOURCE_INPUT_INVALID",r,"The selected Portable entry path is not safe.");if(!Gj.safeParse(t.source_file).success)return Gt("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 Gt("SOURCE_NOT_PORTABLE",t.source_file,"Nested component invocation bindings are not yet a proven independent entry.");if(t.invocation&&!t.invocation.complete)return Gt("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 Gt("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||!rk(t,i)?Gt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The reusable selected source is missing or does not match its pinned hash."):bu({deferClosure:e.defer_module_closure,entryFile:r,entryContent:i,files:n,selection:t})}let o=Iu(n,t.source_file);if(o===null||!rk(t,o))return Gt("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 bu({deferClosure:e.defer_module_closure,entryFile:r,entryContent:o,files:n,selection:t,sourceMapping:i})}if(t.strategy==="collection-container"){let i=t.collection_container_file;if(!i||!Wm(i)||!n.has(i)||n.has(r)||!t.invocation?.complete)return Gt("SOURCE_INPUT_INVALID",r,"The proven collection container or isolated entry is unavailable.");let s=to({component:"PortableCollection",bindings:t.invocation.bindings,targetBlockId:"portable-captured-collection"});if(!s.ok)return Gt("SOURCE_NOT_PORTABLE",r,"The collection invocation has unsupported bindings.");let a=s.plan.requiresRouteSearchParams?"{searchParams}: {searchParams?: Promise<Record<string, string | string[] | undefined>>}":"",l=`import PortableCollection from ${JSON.stringify(`@/${i.replace(/\.[cm]?[jt]sx?$/u,"")}`)};
|
|
40
40
|
export default function PortableCollectionEntry(${a}) { return ${s.plan.jsx}; }
|
|
41
|
-
`;return Bl({entryFile:r,entryContent:l,files:n,selection:t,sourceMapping:{generated_path:t.source_file,source_file:t.source_file,structural_path:t.structural_path}})}return n.has(r)?Bt("SOURCE_INPUT_INVALID",r,"The deterministic extracted entry path collides with the fixed Snapshot map."):wj(t,o,n)}function wj(e,t,n){let r;try{r=Pj(t,{sourceType:"module",sourceFilename:e.source_file,plugins:["jsx","typescript"]})}catch(N){return Bt("SOURCE_PARSE_FAILED",e.source_file,N instanceof Error?N.message:String(N))}let o=Oj(r,e);if(o.length!==1)return Bt("SOURCE_NOT_PORTABLE",e.source_file,"The pinned source range must identify exactly one current JSX root.");let i=o[0],s=i.findParent(N=>N.isFunction());if(!s||!$I(s.node))return Bt("SOURCE_NOT_PORTABLE",e.source_file,"The selected JSX root is not inside one statically bounded component function.");let a=s,l=Zj(a);if(!l.ok)return Bt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component has hook calls whose order cannot be proven for an isolated root.");let c={imports:new Set,moduleDeclarations:new Set,functionDeclarations:new Set,props:new Map,propsObjectName:null,errors:[]},u=new Set;for(let N of r.program.body){if(!F.isImportDeclaration(N)||N.specifiers.length||N.importKind==="type")continue;let w=N.source.value,L=w.startsWith(".")||w.startsWith("@/")?Vl(e.source_file,w,n):null;if(!L?.endsWith(".css"))return Bt("SOURCE_NOT_PORTABLE",e.source_file,"A bare module effect is not a proven portable stylesheet dependency.");u.has(L)||c.imports.add(N),u.add(L)}let d=Fj(a,e);if(!d.ok)return{complete:!1,errors:[d.error]};if(Lj(i,i.node,a,d.value,e,l.translationBinding??null,c,n),c.errors.length>0)return{complete:!1,errors:c.errors};if(l.translationBinding&&![...c.functionDeclarations].some(N=>F.isVariableDeclaration(N)&&N.declarations.some(w=>F.isIdentifier(w.id,{name:l.translationBinding}))))return Bt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component's i18n hook is not part of the selected dependency closure.");let f=t0(r,"__vcpPortableProps"),g=F.cloneNode(i.node,!0),m=[];for(let N of[...c.imports].sort(Em)){let w=Gj(N,e.source_file,e.entry_file,n);if(!w.ok)return{complete:!1,errors:[w.error]};m.push(w.node)}let p=[...c.moduleDeclarations].sort(Em).map(N=>F.cloneNode(N,!0)),h=[...c.functionDeclarations].sort(Em).map(N=>F.cloneNode(N,!0)),x=F.returnStatement(g),E=[...c.props].filter(([N])=>!N.startsWith("@")).map(([N,w])=>F.variableDeclaration("const",[F.variableDeclarator(F.identifier(N),F.memberExpression(F.identifier(f),F.identifier(w)))]));c.propsObjectName&&E.push(F.variableDeclaration("const",[F.variableDeclarator(F.identifier(c.propsObjectName),F.identifier(f))]));let b=F.blockStatement([...E,...h,x]),S=c.props.size?[Wj(f)]:[],v=F.functionDeclaration(F.identifier("PortableBlockEntry"),S,b),P=F.program([...m,...p,v,F.exportDefaultDeclaration(F.identifier("PortableBlockEntry"))]);P.directives=r.program.directives.map(N=>F.cloneNode(N,!0));let I=Aj(F.file(P),{jsescOption:{minimal:!0}}).code,C={generated_path:e.entry_file,source_file:e.source_file,structural_path:e.structural_path};return Bl({entryFile:e.entry_file,entryContent:I,files:n,selection:e,sourceMapping:C,invocationBindings:e0(e,c.props)})}function Oj(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 Fj(e,t){let n=e.node.params;if(n.length>1)return{ok:!1,error:St("SOURCE_NOT_PORTABLE",t.source_file,"Multiple component parameters are not a proven portable invocation surface.")};let r=new Map,o=n[0];if(!o)return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}};if(F.isIdentifier(o))return{ok:!0,value:{bindingByLocalName:r,propsParameter:o}};if(!F.isObjectPattern(o))return{ok:!1,error:St("SOURCE_NOT_PORTABLE",t.source_file,"Component props must use one identifier or a static object pattern.")};for(let i of o.properties){if(!F.isObjectProperty(i)||i.computed||!(F.isIdentifier(i.key)||F.isStringLiteral(i.key))||!(F.isIdentifier(i.value)||F.isAssignmentPattern(i.value)&&F.isIdentifier(i.value.left)))return{ok:!1,error:St("SOURCE_NOT_PORTABLE",t.source_file,"Rest, computed, or nested component prop destructuring is not supported.")};let s=F.isIdentifier(i.key)?i.key.name:i.key.value,a=i.value,l=F.isIdentifier(a)?a.name:F.isAssignmentPattern(a)&&F.isIdentifier(a.left)?a.left.name:"";r.set(l,s)}return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}}}function Lj(e,t,n,r,o,i,s,a){let l=new Set,c=new Map,u=m=>{let p=c.get(m);if(p!==void 0)return p;let h=Mj(n,r,m,o,a);return c.set(m,h),h||s.errors.push(St("SOURCE_NOT_PORTABLE",o.source_file,`Selected prop ${m} is mutated or escapes its proven invocation value.`)),h},d=m=>{let p=m.node.name,h=m.scope.getBinding(p);if(!h){RI.has(p)||s.errors.push(St("SOURCE_NOT_PORTABLE",o.source_file,`The selected root references unbound identifier ${p}.`));return}if(!$l(h.path.node,t)){if(r.bindingByLocalName.has(p)&&h.scope===n.scope){let x=r.bindingByLocalName.get(p);CI(o,x)?u(x)&&s.props.set(p,x):s.errors.push(St("SOURCE_NOT_PORTABLE",o.source_file,`The selected root prop ${x} has no proven invocation binding.`));return}if(r.propsParameter&&h.path.node===r.propsParameter&&m.parentPath?.isMemberExpression()&&m.parentPath.node.object===m.node){let x=m.parentPath.node,E=!x.computed&&F.isIdentifier(x.property)?x.property.name:x.computed&&F.isStringLiteral(x.property)?x.property.value:null;E&&CI(o,E)?u(E)&&(s.propsObjectName=p,s.props.set(`@${p}.${E}`,E)):s.errors.push(St("SOURCE_NOT_PORTABLE",o.source_file,`The selected root reads an unproven dynamic prop through ${p}.`));return}l.has(h)||(l.add(h),PI(h,n,o,s,d,f,a))}},f=(m,p)=>{let h=jI(m);if(!h||/^[a-z]/u.test(h.name))return;let x=p.scope.getBinding(h.name);if(!x){RI.has(h.name)||s.errors.push(St("SOURCE_NOT_PORTABLE",o.source_file,`The selected root component ${h.name} has no proven import or declaration.`));return}l.has(x)||$l(x.path.node,t)||(l.add(x),PI(x,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){BI(p,i)||s.errors.push(St("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(St("SOURCE_NOT_PORTABLE",o.source_file,"Assignments inside a selected root are not a closed Portable dependency.")),p.stop()},UpdateExpression(p){s.errors.push(St("SOURCE_NOT_PORTABLE",o.source_file,"Updates inside a selected root are not a closed Portable dependency.")),p.stop()},NewExpression(p){s.errors.push(St("SOURCE_NOT_PORTABLE",o.source_file,"Dynamic object construction inside a selected root is not proven portable.")),p.stop()}})})(e)}function PI(e,t,n,r,o,i,s){let a=e.path;if(Qj(a,t)||a.isFunctionDeclaration()&&a.node===t.node){r.errors.push(St("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(St("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is rebound outside its declaration.`));return}if(Uj(e)){r.errors.push(St("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} has a member write outside its declaration.`));return}let l=new jl(s),c=new Map,u=a.parentPath,d=u?.isImportDeclaration(),f=!1;if(d&&(u.node.source.value.startsWith(".")||u.node.source.value.startsWith("@/"))){let h=Vl(n.source_file,u.node.source.value,s),x=h?l.get(h):void 0,E=a.isImportDefaultSpecifier()?"default":a.isImportSpecifier()&&a.node.importKind!=="type"?ln(a.node.imported,!1):null,b=x&&E&&u.node.importKind!=="type"?xo(x,E,l):null,S=b?cn(b):null;if(!S?.length){r.errors.push(St("SOURCE_NOT_PORTABLE",n.source_file,"The imported value has no bounded unique Snapshot source."));return}c.set(e.identifier,S),f=S.every(v=>v.isFunctionDeclaration()||v.isFunctionExpression()||v.isArrowFunctionExpression())}else d&&(f=e.referencePaths.every(h=>h.parentPath?.isJSXOpeningElement()||h.parentPath?.isJSXClosingElement()||h.parentPath?.isCallExpression()&&h.parentPath.node.callee===h.node));if((d&&!f||Dj(e))&&!Ws(e,{bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:c,files:s,modules:l},!1)){r.errors.push(St("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(h=>h.isImportDeclaration());if(g?.isImportDeclaration()){r.imports.add(g.node);return}let m=a.isVariableDeclarator()?a:a.findParent(h=>h.isVariableDeclarator());if(m?.isVariableDeclarator()){let h=m.parentPath,x=m.get("init");if(!h?.isVariableDeclaration()||h.node.kind!=="const"||!x.node||!xr(m.node.id)||!xr(x.node)&&!qj(x)){r.errors.push(St("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a side-effect-free const.`));return}let b=h.findParent(v=>v.isFunction())===t?r.functionDeclarations:r.moduleDeclarations,S=F.variableDeclaration("const",[F.cloneNode(m.node,!0)]);NI(b,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(h=>h.isFunction());if(p?.isFunctionDeclaration()&&Ec(p.node)){let x=p.findParent(E=>E.isFunction())===t?r.functionDeclarations:r.moduleDeclarations;NI(x,F.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(St("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a statically portable declaration.`))}function Dj(e){let t=e.path;if(!t.isVariableDeclarator())return!1;let n=t.get("init");if(!n.node)return!0;let r=Hj(n.node);return F.isFunctionExpression(r)||F.isArrowFunctionExpression(r)||F.isCallExpression(r)&&Sc(r)?!1:!Sf(e)?.every(i=>i.isFunctionExpression()||i.isArrowFunctionExpression()||vf(i,new Map))}var jl=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=Ul(this.files,t);if(r===null)return;let o=Ee(t,r);if(o.ok)return super.set(t,o.module),o.module}};function Mj(e,t,n,r,o){let i=r.invocation?.bindings.find(c=>c.propName===n);if(!i)return!1;let s=[];if(i.value.kind==="json-literal"){let c=F.file(F.program([F.expressionStatement(F.valueToNode(i.value.value))]));km(c,{ExpressionStatement(u){s.push(u.get("expression")),u.stop()}})}let a=new Map,l={bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:a,files:o,modules:new jl(o)};if(t.propsParameter)return Sm(e,n,s,l);for(let[c,u]of t.bindingByLocalName){if(u!==n)continue;let d=e.scope.getBinding(c);if(!d||(a.set(d.identifier,s),!Ws(d,l,!0)))return!1}return!0}function Bj(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(F.isJSXIdentifier(i)&&/^[a-z]/u.test(i.name))return!0;if(!F.isJSXIdentifier(i)||t.jsxCalls.has(o.node)||t.jsxCalls.size>=32)return!1;let s=jj(o,t);if(!s)return!1;let a={...t,bindings:new Set(t.bindings),jsxCalls:new Set(t.jsxCalls).add(o.node)},l=cn(e,t.inputs);if(!l)return!1;if(r.isJSXSpreadAttribute()){let u=new Set;for(let d of l){if(!d.isObjectExpression())return!1;for(let f of d.node.properties){if(!F.isObjectProperty(f)||f.computed)return!1;let g=ln(f.key,!1);if(g===null)return!1;u.add(g)}}return[...u].every(d=>{let f=vc(l,d,t.inputs);return f!==null&&Sm(s,d,f,a)})}let c=r.isJSXAttribute()&&F.isJSXIdentifier(r.node.name)?r.node.name.name:"children";return Sm(s,c,l,a)}function jj(e,t){let n=e.node.name;if(!F.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=Vl(s,i,t.files);if(!a)return null;let l=t.modules.get(a);if(!l)return null;let c=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()?ln(r.path.node.imported,!1):null;if(!c)return null;let u=Ut({module:l,exportName:c,parsedModules:t.modules});return u.ok?u.roots[0]?.getFunctionParent()??null:null}function Sm(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 l of o.get("properties")){if(!l.isObjectProperty()||l.node.computed){if(Object.keys(l.getBindingIdentifiers()).some(f=>l.scope.getBinding(f)?.referencePaths.length))return!1;continue}if(ln(l.node.key,!1)!==t)continue;let c=l.get("value");if(!c.isIdentifier())return!1;let u=c.scope.getBinding(c.node.name);if(!u)return!1;i.set(u.identifier,n),a=Ws(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 l=a.parentPath;if(!(l?.isMemberExpression()||l?.isOptionalMemberExpression())||l.node.object!==a.node)return!1;let c=ln(l.node.property,l.node.computed);return c===null?!1:c!==t?!0:(i.set(l.node,n),LI(l,{...r,inputs:i},!0))})}function Ws(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=>LI(i,r,n));return o&&t.bindings.add(e),o}function Rm(e,t,n){let r=e.node.id;if(F.isIdentifier(r)){let o=e.scope.getBinding(r.name);return o?Ws(o,t,n):!1}if(F.isObjectPattern(r)||F.isArrayPattern(r)){let o=[];return ki(r,o)?$j(o,e,t):!1}return!1}function ki(e,t){if(F.isRestElement(e))return ki(e.argument,t);if(F.isIdentifier(e))return t.push(e.name),!0;if(F.isAssignmentPattern(e))return ki(e.left,t);if(F.isObjectPattern(e)){for(let n of e.properties){if(F.isRestElement(n)){if(!ki(n.argument,t))return!1;continue}if(!F.isObjectProperty(n)||n.computed||!(F.isIdentifier(n.key)||F.isStringLiteral(n.key)||F.isNumericLiteral(n.key))||!ki(n.value,t))return!1}return!0}if(F.isArrayPattern(e)){for(let n of e.elements)if(n&&!ki(n,t))return!1;return!0}return!1}function $j(e,t,n){return e.every(r=>{let o=t.scope.getBinding(r);return o?Ws(o,n,!0):!1})}function Uj(e){return e.referencePaths.some(t=>{let{current:n,memberAccess:r}=FI(t);if(!r)return!1;let o=n.parentPath;return!!(OI(n)||o?.isUpdateExpression()||o?.isUnaryExpression({operator:"delete"}))})}function OI(e){let t=e.findParent(n=>n.isAssignmentExpression()||n.isForXStatement());return t&&(t.isAssignmentExpression()||t.isForXStatement())?$l(e.node,t.node.left):!1}function FI(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 LI(e,t,n){if(!Jj(e,t))return!1;let{current:r,memberAccess:o}=FI(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:Rm(i,t,o||n)}return OI(r)||i.isUpdateExpression()||i.isUnaryExpression({operator:"delete"})?!1:i.isCallExpression()||i.isOptionalCallExpression()?i.node.callee===r.node?!1:Vj(i,r,t):i.isNewExpression()?!1:i.isExportSpecifier()||i.isExportNamedDeclaration()||i.isExportDefaultDeclaration()||i.isTSTypeQuery()||n&&(i.isJSXOpeningElement()||i.isJSXClosingElement())?!0:i.isJSXExpressionContainer()||i.isJSXSpreadAttribute()?Bj(r,t):i.isSpreadElement()||i.isArrayExpression()||i.isObjectExpression()||i.isObjectProperty()||i.isConditionalExpression()||i.isLogicalExpression()||i.isSequenceExpression()||i.isAwaitExpression()?Kj(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 Vj(e,t,n){if(!e.node.arguments.some(i=>i===t.node))return!1;let r=e.node.callee;if(F.isIdentifier(r)){if(wI.has(r.name))return e.scope.getBinding(r.name)===void 0;let i=e.scope.getBinding(r.name);return!i||!ei(i)?!1:Hs(e,n,new Set)}if(!F.isMemberExpression(r)&&!F.isOptionalMemberExpression(r)||!F.isIdentifier(r.property))return!1;let o=Pm(r);return!o||e.scope.getBinding(o.name)?!1:o.name==="Object"&&r.property.name==="assign"?e.node.arguments[0]===t.node?!1:Hs(e,n,new Set):TI.get(o.name)?.has(r.property.name)??!1?MI(e)?Hs(e,n,new Set):!0:!1}function Kj(e,t,n,r){let o=DI(e);return o.kind==="declarator"?Rm(o.declarator,r,o.directValue):o.kind==="escape"||o.kind==="call"?!1:t||n}function DI(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 Hs(e,t,n){if(n.has(e.node))return!0;n.add(e.node);let r=DI(e);return r.kind==="declarator"?Rm(r.declarator,t,r.directValue):r.kind==="escape"?!1:r.kind==="call"?r.call.node.callee===e.node?!1:MI(r.call)?Hs(r.call,t,n):zj(r.call):!0}function Jj(e,t){let n=e.findParent(o=>o.isFunction());if(!n||!$I(n.node))return!0;let r=Xj(n);return!r||!ei(r)?!0:r.referencePaths.every(o=>{let i=o.parentPath;return!i?.isCallExpression()||i.node.callee!==o.node?!0:Hs(i,t,new Set)})}function Xj(e){let t=e.node,n=null;if(F.isFunctionDeclaration(t)?n=t.id?.name??null:(F.isArrowFunctionExpression(t)||F.isFunctionExpression(t))&&e.parentPath?.isVariableDeclarator()&&F.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 MI(e){let t=e.node.callee;if(F.isIdentifier(t)){let r=e.scope.getBinding(t.name);return!!(r&&ei(r))}if(!F.isMemberExpression(t)&&!F.isOptionalMemberExpression(t)||!F.isIdentifier(t.property))return!1;let n=Pm(t);return!n||e.scope.getBinding(n.name)?!1:n.name==="Object"&&Tj.has(t.property.name)}function zj(e){let t=e.node.callee;if(F.isIdentifier(t))return wI.has(t.name)&&e.scope.getBinding(t.name)===void 0;if(!F.isMemberExpression(t)&&!F.isOptionalMemberExpression(t)||!F.isIdentifier(t.property))return!1;let n=Pm(t);return!n||e.scope.getBinding(n.name)||n.name==="Object"&&t.property.name==="assign"?!1:TI.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 Hj(e){let t=e;for(;t&&(F.isTSAsExpression(t)||F.isTSTypeAssertion(t)||F.isTSNonNullExpression(t)||F.isTSSatisfiesExpression(t)||F.isParenthesizedExpression(t));)t=t.expression;return t&&F.isExpression(t)?t:null}function Pm(e){return!e.computed&&F.isIdentifier(e.object)?e.object:null}function Wj(e){let t=F.identifier(e);return t.typeAnnotation=F.tsTypeAnnotation(F.tsTypeReference(F.identifier("Record"),F.tsTypeParameterInstantiation([F.tsStringKeyword(),F.tsAnyKeyword()]))),t}function Bl(e){let t=new Map(e.files);t.set(e.entryFile,e.entryContent);let n=ar({entry_files:[e.entryFile],files:t});if(!n.complete)return{complete:!1,errors:n.errors.map(i=>St(n0(i.code),i.path,i.message))};let r=[];for(let i of n.nodes){if(i.kind!=="source"&&i.kind!=="asset")continue;let s=Ul(t,i.path);if(s===null)return Bt("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 Gj(e,t,n,r){let o=F.cloneNode(e,!0),i=e.source.value;if(i.startsWith("./")||i.startsWith("../")){let s=Vl(t,i,r);if(!s)return{ok:!1,error:St("SOURCE_IMPORT_UNRESOLVED",t,`The selected import ${i} cannot be resolved in the fixed Snapshot map.`)};o.source.value=Yj(n,s)}return{ok:!0,node:o}}function Vl(e,t,n){let r=t.startsWith("@/")?t.slice(2):zs.posix.normalize(zs.posix.join(zs.posix.dirname(e),t));if(!Im(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 Yj(e,t){let n=zs.posix.relative(zs.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function Zj(e){let t=null,n=0,r=!1;return e.traverse({CallExpression(o){let i=o.node.callee;if(!F.isIdentifier(i)||!/^use[A-Z0-9]/u.test(i.name))return;if(i.name!=="useTranslations"||o.node.arguments.length!==1||!F.isStringLiteral(o.node.arguments[0])){r=!0,o.stop();return}let s=o.scope.getBinding(i.name),a=s?.path.findParent(c=>c.isImportDeclaration());if(!s?.path.isImportSpecifier()||!a?.isImportDeclaration()||a.node.source.value!=="next-intl"||!F.isIdentifier(s.path.node.imported,{name:"useTranslations"})){r=!0,o.stop();return}n+=1;let l=o.findParent(c=>c.isVariableDeclarator());if(!l?.isVariableDeclarator()||!F.isIdentifier(l.node.id)){r=!0,o.stop();return}t=l.node.id.name}}),r||n>1?{ok:!1}:t?{ok:!0,translationBinding:t}:{ok:!0}}function BI(e,t){let n=e.node.callee;if(F.isImport(n))return!1;if(t&&F.isIdentifier(n,{name:t})&&e.node.arguments.length>0&&e.node.arguments.every(o=>F.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!!(F.isCallExpression(s)&&Sc(s))}if(!F.isIdentifier(n))return!1;let r=e.scope.getBinding(n.name);return r?ei(r):!1}function qj(e){return e.isCallExpression()&&BI(e,null)&&F.isIdentifier(e.node.callee)&&e.scope.getBinding(e.node.callee.name)?.constantViolations.length===0&&e.node.arguments.every(t=>F.isExpression(t)&&xr(t))}function jI(e){return F.isJSXIdentifier(e)?F.isValidIdentifier(e.name)?F.identifier(e.name):null:F.isJSXMemberExpression(e)?jI(e.object):null}function Qj(e,t){return e.scope===t.scope&&(t.node.params.some(n=>n===e.node)||e.isIdentifier()&&t.node.params.some(n=>F.isObjectPattern(n)&&n.properties.some(r=>F.isObjectProperty(r)&&F.isIdentifier(r.value,{name:e.node.name}))))}function $l(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 F.isFunction(e)}function CI(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 t0(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 NI(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 Em(e,t){return(e.start??0)-(t.start??0)}function Ul(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 AI(e,t){let n=Rj("sha256").update(t).digest("hex");return e.content_hash===`sha256:${n}`}function Im(e){return!!e&&!e.startsWith("/")&&!e.includes("\\")&&e.split("/").every(t=>t&&t!=="."&&t!==".."&&!t.startsWith("."))}function n0(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 Bt(e,t,n){return{complete:!1,errors:[St(e,t,n)]}}function St(e,t,n){return{code:e,path:t,message:n}}import{createHash as WI}from"node:crypto";import Am from"@babel/generator";import Tm from"@babel/traverse";import*as Ke from"@babel/types";function yt(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 zI from"@babel/types";import{createHash as Cm}from"node:crypto";var r0="sha256:cdea4bd5eec1d29e9a9693e6545fb0ac81b67b3260d5c957eee827c9f869842f",o0="sha256:89b8fde9bf5ca807e238c3f5f6229e5f107b76a45d4972d245ec842ba3f6f6f5",i0=new Set(["sha256:3cf25df4601562d673864ea135b8808cae2819ca315b16af5ad07a6afbb5d31c","sha256:7ad1062c59fabb7d584691e905919c84ddd0035f7b1ccd7cf58f2ba0b3fdde12"]),s0=new Set(["sha256:64f26e7284e844de65cfeaf268974aeb4a612ae796638fe219587f1d3e46b429"]),a0=new Map([["sha256:3b952ddc14778008dac157346c997cdea06844d890f1e5280ea08d38fbf03776","sha256:061e4143d12a22f4256157df2824144ac8fb86744f456afa50ff963278ddb263"],["sha256:92f7425b0f1eb031ef47470adb2b777fe863234c268504287323ff06cd4f91cc","sha256:4b5aa33d4bbf4e895e0186ee7049a7f9606b5d85ee6e045b8eed084cee458646"]]);function Kl(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:${Cm("sha256").update(s).digest("hex")}`;return a&&t.get(i)===a?a:""},o=r(n);return!!o&&a0.get(o)===r(n.replace("jsonld.tsx","metadata-fields.ts"))}function c0(e){return e.index===r0&&e.client===o0&&i0.has(e.collections)}function _i(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:${Cm("sha256").update(i).digest("hex")}`;return t.get(`${n}${o}.ts`)===s?s:""};return c0({index:r("index"),collections:r("collections"),client:r("client")})&&s0.has(r("field"))}function UI(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:${Cm("sha256").update(r).digest("hex")}`;return o==="sha256:6e1c0d0af2938dc4e74d4a35b185bec0ad1fd6d16fd2323ee0cd72eaa05c836f"&&t.get(n)===o&&_i(e,t)}import*as tn from"@babel/types";var ct={kind:"primitive"},cr={kind:"json"},Nm=new Set(["__proto__","prototype","constructor","then","toString","valueOf","toLocaleString"]),Jl=e=>({kind:"object",properties:new Map(Object.entries(e))}),Oo=e=>({kind:"array",item:e});function KI(e){let t=new Map;for(let n of e.split("/")){let r=/^\[(\[)?(\.\.\.)?([^\[\]/]+)\]\]?$/u.exec(n);r&&t.set(r[3],r[2]?Oo(ct):ct)}return{kind:"object",properties:t}}function Xt(e){return!!e&&e.kind!=="promise"&&e.kind!=="jsx"}function JI(e){let t=Jl({id:ct,url:ct,seo:cr,fields:cr}),n=["list","listStrict"].includes(e)?Jl({items:Oo(t),total:ct,page:ct,pageSize:ct}):["get","getStrict","getByUrl","getByUrlStrict"].includes(e)?t:e==="categories"?Oo(Jl({id:ct,label:ct,children:cr})):e==="schema"?cr:null;return n?{kind:"promise",value:e.endsWith("Strict")?Jl({kind:ct,data:n,error:cr}):n}:null}function VI(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 l=a.node.key,c=tn.isIdentifier(l)?l.name:tn.isStringLiteral(l)?l.value:null;c&&!Nm.has(c)&&o(a.get("value"),s.properties.get(c)??null)}else i.isAssignmentPattern()&&o(i.get("left"),s)};return e.get("params").forEach((i,s)=>o(i,t[s]??null)),r}function XI(e){let t=(o,i,s,a)=>{if(a.has(o.node)||a.size>=48)return null;let l=new Set(a).add(o.node),c=VI(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"),c,l):ct)}}):d.push(n(u,c,l));let f=Gs(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),l=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 l(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?l(p):g.path.isVariableDeclarator()&&g.path.parentPath.isVariableDeclaration({kind:"const"})?l(g.path.get("init")):null}if(o.isAwaitExpression()){let g=l(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 p=m.node.key,h=tn.isIdentifier(p)?p.name:tn.isStringLiteral(p)?p.value:null,x=n(m.get("value"),i,a);if(!h||Nm.has(h)||g.has(h)||!Xt(x))return null;g.set(h,x)}return{kind:"object",properties:g}}if(o.isArrayExpression()){if(!o.node.elements.length)return{kind:"array",item:cr,empty:!0};let g=Gs(o.get("elements").map(m=>l(m)));return Xt(g)?Oo(g):null}if(o.isMemberExpression()||o.isOptionalMemberExpression()){let g=l0(o);if(!g||Nm.has(g))return null;let m=l(o.get("object"));return m?.kind==="object"?m.properties.get(g)??null:m?.kind==="json"?cr:m?.kind==="array"?g==="length"?ct:/^\d+$/u.test(g)?m.item:null:m?.kind==="primitive"&&g==="length"?ct:null}if(o.isConditionalExpression())return Gs([l(o.get("consequent")),l(o.get("alternate"))]);if(o.isLogicalExpression())return Gs([l(o.get("left")),l(o.get("right"))]);if(o.isUnaryExpression())return["typeof","!","void"].includes(o.node.operator)||Xt(l(o.get("argument")))?ct:null;if(o.isBinaryExpression())return["in","instanceof"].includes(o.node.operator)?null:["===","!=="].includes(o.node.operator)||Xt(l(o.get("left")))&&Xt(l(o.get("right")))?ct:null;if(o.isTemplateLiteral())return o.get("expressions").every(g=>Xt(l(g)))?ct:null;if(!o.isCallExpression())return null;let c=e.cms_value(o,i,a);if(c)return c;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(l(g)))?ct:null;let d=r(o,i,a);if(d)return d.result;if(u.isMemberExpression()&&!u.node.computed){if(tn.isIdentifier(u.node.object,{name:"Object"})&&!u.scope.getBinding("Object")&&tn.isIdentifier(u.node.property,{name:"keys"})&&o.node.arguments.length===1&&Xt(l(o.get("arguments")[0])))return Oo(ct);let g=l(u.get("object")),m=tn.isIdentifier(u.node.property)?u.node.property.name:"";if(g?.kind==="array"&&m==="slice"&&o.node.arguments.length<=2&&o.get("arguments").every(p=>l(p)?.kind==="primitive"))return g;if(g?.kind==="primitive"&&["includes","startsWith","endsWith","trim","toLowerCase","toUpperCase","replace","split"].includes(m)&&o.get("arguments").every(p=>Xt(l(p))))return m==="split"?Oo(ct):ct}let f=e.resolve_function(u);return f?t(f,o.get("arguments").map(g=>l(g)),i,a):null};function r(o,i,s=new Set){let a=o.get("callee");if(!a.isMemberExpression()||a.node.computed||!tn.isIdentifier(a.node.property))return null;let l=a.node.property.name;if(!["map","filter","some","every","find"].includes(l)||o.node.arguments.length!==1)return null;let c=n(a.get("object"),i,s);if(c?.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=[c.item,ct,c];if(c.empty)return{target:d,args:f,result:["map","filter"].includes(l)?c:ct,empty:!0};let g=t(d,f,i,s);return g?{target:d,args:f,result:l==="map"?Oo(g):l==="filter"?c:l==="find"?c.item:ct}:null}return{value:n,arrayCall:r,bind:VI}}function l0(e){let t=e.node.property;return!e.node.computed&&tn.isIdentifier(t)?t.name:tn.isStringLiteral(t)?t.value:tn.isNumericLiteral(t)?String(t.value):null}function Gs(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:Gs(n.map(r=>r?.kind==="array"?r.item:null))??cr}:{kind:"array",item:cr,empty:!0}}return e.every(n=>n?.kind==="primitive")?ct:e.every(n=>n?.kind==="jsx")?t:e.every(Xt)?cr:null}function HI(e){if(!_i(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=yt(e.files.get(d)),m=g===null?null:Ee(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=ht(g.file,f.node.source.value,e.files);if(!m)return null;let p=d.path.node.imported;return{module:g,file:m,name:zI.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?xo(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&&Kl(e.files,e.trusted_host_file_hashes,m.file))},l=XI({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(h=>Xt(l.value(h,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)||tr(m.module.ast,m.local))return null;let p=br(u.node,{file:m.module.file,imports:new Map([[m.local,{source:m.file,importedName:m.name}]])})?.operation;return p?JI(p):null}}),c=l.bind(e.owner,[{kind:"object",properties:new Map([["params",{kind:"promise",value:KI(e.route_id)}],["searchParams",{kind:"promise",value:{kind:"json"}}]])}]);return u=>{if(!u.node||!Xt(l.value(u,c)))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)||!Xt(l.value(g,c)))&&(d=!1)}else g.isMemberExpression()||g.isOptionalMemberExpression()?Xt(l.value(g,c))||(d=!1):!xr(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 u0=typeof Tm=="function"?Tm:Tm.default,d0=typeof Am=="function"?Am:Am.default;function GI(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=yt(n.get(o.sourceFile));if(i===null||`sha256:${WI("sha256").update(i).digest("hex")}`!==t.ownerSourceHash)return{complete:!1};let s=Ee(o.sourceFile,i);if(!s.ok)return{complete:!1};let a=null;u0(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 l=a,c=l?.getFunctionParent();if(!l||!c?.isFunctionDeclaration()||!c.parentPath.isExportDefaultDeclaration()||!c.get("body").isBlockStatement())return{complete:!1};let u=l.findParent(K=>K.isReturnStatement());if(!u?.isReturnStatement()||u.parentPath!==c.get("body"))return{complete:!1};let d=new Set,f=new Map,g=new Set,m=new Set,p=new Set,h=!1,x=K=>{if(!K||d.has(K))return;if(d.add(K),!K.constant||K.constantViolations.length){h=!0;return}let ge=K.path;if(ge.isImportSpecifier()||ge.isImportDefaultSpecifier()||ge.isImportNamespaceSpecifier()){let Me=ge.parentPath;if(!Me.isImportDeclaration()){h=!0;return}let He=f.get(Me.node)??new Set;He.add(ge.node),f.set(Me.node,He);return}if(K.kind==="param"){let Me=c.node.params[0];if(!Ke.isObjectPattern(Me)){h=!0;return}let He=Me.properties.filter(st=>Ke.isObjectProperty(st)&&!st.computed&&Ke.isIdentifier(st.value,{name:K.identifier.name})),pt=He[0];if(He.length!==1||!Ke.isObjectProperty(pt)){h=!0;return}let xe=Ke.isIdentifier(pt.key)?pt.key.name:Ke.isStringLiteral(pt.key)?pt.key.value:"";if(!["params","searchParams"].includes(xe)){h=!0;return}p.add(xe);return}let oe=ge.getStatementParent();if(!oe||oe.node===c.node){h=!0;return}if(ge.isVariableDeclarator()){if(!oe.isVariableDeclaration({kind:"const"})||oe.node.declarations.length!==1){h=!0;return}}else if(!ge.isFunctionDeclaration()&&!ge.isTSTypeAliasDeclaration()&&!ge.isTSInterfaceDeclaration()){h=!0;return}if(oe.parentPath===c.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{h=!0;return}E(oe)},E=K=>{let ge=oe=>x(oe.scope.getBinding(oe.node.name));K.isReferencedIdentifier()&&ge(K),K.traverse({ReferencedIdentifier(oe){ge(oe)},JSXOpeningElement(oe){Ke.isJSXIdentifier(oe.node.name)&&!/^[a-z]/u.test(oe.node.name.name)&&x(oe.scope.getBinding(oe.node.name.name))}})};E(l);let b=c.get("body").get("body").filter(K=>(K.node.start??1/0)<(u.node.start??-1)),S=HI({module:s.module,owner:c,files:n,trusted_host_file_hashes:e.trusted_host_file_hashes,route_id:e.target.composition.routeId}),v=new Set,P=(K,ge)=>{let oe=ge.path.parentPath;if(!ge.path.isImportSpecifier()||!Ke.isIdentifier(ge.path.node.imported,{name:"cms"})||!oe?.isImportDeclaration())return!1;let Me=ht(o.sourceFile,oe.node.source.value,n);if(!Me||!/^(?:src\/)?lib\/cms\/index\.ts$/u.test(Me))return!1;let He=K;for(;He.parentPath?.isMemberExpression()&&He.parentPath.node.object===He.node&&!He.parentPath.node.computed;)He=He.parentPath;let pt=He.parentPath;return!!(pt?.isCallExpression()&&pt.node.callee===He.node&&br(pt.node,{file:o.sourceFile,imports:new Map([[ge.identifier.name,{source:Me,importedName:"cms"}]])}))},I=!0;for(;I&&!h;){I=!1;for(let K of b){if(m.has(K.node))continue;let ge=!1;if(K.traverse({ReferencedIdentifier(Me){let He=Me.scope.getBinding(Me.node.name);He&&(d.has(He)||v.has(He))&&!P(Me,He)&&(ge=!0)}}),!ge)continue;if(K.isVariableDeclaration({kind:"const"})&&K.node.declarations.length===1){let Me=K.get("declarations")[0];if(Me.get("id").isIdentifier()&&S(Me.get("init"))){let He=Me.node.id.name,pt=K.scope.getBinding(He);pt&&!v.has(pt)&&(v.add(pt),I=!0);continue}}let oe=!1;if(K.traverse({Function(Me){Me.skip()},ReturnStatement(Me){Me.node.argument&&(oe=!0)}}),oe){h=!0;break}m.add(K.node),E(K);for(let Me of Object.keys(Ke.getBindingIdentifiers(K.node)))x(K.scope.getBinding(Me));I=!0}}if(h||!d.size)return{complete:!1};let C=WI("sha256").update(JSON.stringify([t.sourceHash,t.ownerSourceHash,o.callLocator.sourceRange])).digest("hex"),N=`components/site/portable/${C.slice(0,24)}/page.tsx`;if(n.has(N))return{complete:!1};let w=[];for(let[K,ge]of f){let oe=Ke.cloneNode(K,!0);if(oe.specifiers=K.specifiers.filter(Me=>ge.has(Me)||Ke.isImportSpecifier(Me)&&Me.importKind==="type").map(Me=>Ke.cloneNode(Me,!0)),oe.source.value.startsWith(".")){let Me=ht(o.sourceFile,oe.source.value,n);if(!Me)return{complete:!1};oe.source=Ke.stringLiteral(`@/${Me.replace(/\.[cm]?[jt]sx?$/u,"")}`)}w.push(oe)}let L=Ke.functionDeclaration(Ke.identifier(`PortableCmsDataEntry_${C.slice(0,8)}`),c.node.params.map(K=>Ke.cloneNode(K,!0)),Ke.blockStatement([...[...m].sort(wm).map(K=>Ke.cloneNode(K,!0)),Ke.returnStatement(Ke.cloneNode(l.node,!0))]));L.async=c.node.async;let D=Ke.program([...w.sort(wm),...[...g].sort(wm).map(K=>Ke.cloneNode(K,!0)),Ke.exportDefaultDeclaration(L)]),U=d0(Ke.file(D)).code,M=l.node.loc;if(!M||l.node.start==null||l.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:l.node.start,end_offset:l.node.end,start_line:M.start.line,start_column:M.start.column,end_line:M.end.line,end_column:M.end.column},owner:t.descriptor.owner,call_chain:[],strategy:"extract-jsx",entry_file:N,entry_export:{kind:"default"},invocation:null},extracted:{complete:!0,entry_file:N,source_files:[{path:N,content:U}],source_mapping:[],invocation_bindings:G,selected_root_ref:t.root.rootRef}}}function wm(e,t){return(e.start??0)-(t.start??0)}import Om from"@babel/traverse";import*as We from"@babel/types";import{createHash as YI}from"node:crypto";var ZI=typeof Om=="function"?Om:Om.default,f0=/^[a-z0-9][a-z0-9_-]{0,123}$/u;function qI(e){let t=ar({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=yt(e.files.get(i.path)),a=s===null?null:Ee(i.path,s);a?.ok&&ZI(a.module.ast,{ImportDeclaration(l){if(l.node.importKind==="type")return;let c=ht(i.path,l.node.source.value,e.files);if(c)for(let u of l.node.specifiers){if(We.isImportSpecifier(u)&&u.importKind==="type"||!l.scope.getBinding(u.local.name)?.referencePaths.length)continue;let d=o.get(c)??new Set;d.add(We.isImportDefaultSpecifier(u)?"default":We.isImportSpecifier(u)?We.isIdentifier(u.imported)?u.imported.name:u.imported.value:"*"),o.set(c,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=yt(e.files.get(i.path));if(s===null)continue;let a=Ee(i.path,s);if(!a.ok){r.push({code:"CMS_BINDING_SOURCE_INVALID",source_path:i.path,message:a.diagnostic.message});continue}let l=new Map;for(let c of a.module.ast.program.body)if((We.isExportNamedDeclaration(c)||We.isExportAllDeclaration(c))&&c.source&&c.exportKind!=="type"){let u=ht(i.path,c.source.value,e.files);u&&Fm(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 c of a.module.ast.program.body){if(!We.isImportDeclaration(c)||c.importKind==="type")continue;let u=ht(i.path,c.source.value,e.files);if(u)for(let d of c.specifiers)u&&Fm(u)&&!We.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."}),!(!We.isImportSpecifier(d)||d.importKind==="type")&&l.set(d.local.name,{source:u,importedName:We.isIdentifier(d.imported)?d.imported.name:d.imported.value})}ZI(a.module.ast,{FunctionDeclaration(c){let u=c.parentPath.isExportDefaultDeclaration()?"default":c.parentPath.isExportNamedDeclaration()?c.node.id?.name:void 0;u&&!o.get(i.path)?.has(u)&&!o.get(i.path)?.has("*")&&(!c.node.id||!c.scope.getBinding(c.node.id.name)?.referencePaths.some(d=>!d.isExportDeclaration()))&&c.skip()},ReferencedIdentifier(c){let u=l.get(c.node.name);if(!u||!Fm(u.source)||!c.scope.getBinding(c.node.name)?.path.isImportSpecifier()||!["cms","collections","cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(u.importedName))return;let f=c;for(;f.parentPath?.isMemberExpression()&&f.parentPath.node.object===f.node;)f=f.parentPath;if(!We.isExpression(f.node))return;let g=br(We.callExpression(f.node,[]),{file:i.path,imports:l}),m=u.importedName==="cms"&&f.isMemberExpression()&&!f.node.computed&&f.get("object").isMemberExpression()&&We.isMemberExpression(f.node.object)&&!f.node.object.computed&&We.isIdentifier(f.node.object.object,{name:c.node.name})&&We.isIdentifier(f.node.object.property,{name:"field"});(!g||!Lm(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.",...c.node.loc?{call_site:{line:c.node.loc.start.line,column:c.node.loc.start.column}}:{}})},CallExpression(c){let u=c.get("callee"),d=new Set;for(;u.isIdentifier()&&!l.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(!We.isExpression(u.node))return;let f=u;for(;f.isMemberExpression()&&!f.node.computed;)f=f.get("object");if(f.isIdentifier()&&["cms","collections"].includes(l.get(f.node.name)?.importedName??"")){let S=f.scope.getBinding(f.node.name);if(!S?.path.isImportSpecifier())return;if(tr(a.module.ast,f.node.name)||!QI(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=br(We.callExpression(u.node,[]),{file:i.path,imports:l});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=c.get("arguments")[1];if(S?.isObjectExpression()){let v=S.get("properties").find(I=>I.isObjectProperty()&&!I.node.computed&&(We.isIdentifier(I.node.key,{name:"buildSample"})||We.isStringLiteral(I.node.key,{value:"buildSample"}))),P=v?.isObjectProperty()?v.get("value"):void 0;if(P?.isIdentifier()){let I=P.scope.getBinding(P.node.name);P=I?.constant&&I.referencePaths.length===1&&I.path.isVariableDeclarator()?I.path.get("init"):void 0}for(;P?.isTSAsExpression()||P?.isTSSatisfiesExpression();)P=P.get("expression");P?.isObjectExpression()&&P.node.start!=null&&P.node.end!=null&&e.on_build_only_value({file_path:i.path,start:P.node.start,end:P.node.end,source_hash:`sha256:${YI("sha256").update(s).digest("hex")}`})}}let p=c.get("arguments")[0];if(p?.isObjectExpression()&&m.startsWith("cmsFetch")){let S=p.get("properties").find(v=>v.isObjectProperty()&&!v.node.computed&&(We.isIdentifier(v.node.key,{name:"path"})||We.isStringLiteral(v.node.key,{value:"path"})));p=S?.isObjectProperty()?S.get("value"):void 0}let h=m.startsWith("getByUrl")||m.startsWith("cmsFetch"),x=p?Ri(p,h,new Set):null,E=x&&h?nl(x):x;if(!E||!f0.test(E)){r.push({code:"CMS_BINDING_UNRESOLVED",source_path:i.path,message:"The CMS application identity cannot be determined from its request binding.",...c.node.loc?{call_site:{line:c.node.loc.start.line,column:c.node.loc.start.column}}:{}});return}h&&!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:c.node.loc?.start.line??1,column:c.node.loc?.start.column??0}}),n.set(E,b)},JSXOpeningElement(c){if(!e.on_host_call||!We.isJSXIdentifier(c.node.name)||c.node.start==null||c.node.end==null)return;let u=l.get(c.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:c.node.start,end:c.node.end,source_hash:`sha256:${YI("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 Fm(e){return/^(?:src\/)?lib\/cms(?:\/index)?\.[cm]?[jt]s$/u.test(e)||/^(?:src\/)?lib\/cms\/(?:collections|client)\.[cm]?[jt]s$/u.test(e)}function Lm(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 Lm(r,n);if(r?.isVariableDeclarator()&&r.node.init===e.node&&We.isIdentifier(r.node.id)){let o=r.scope.getBinding(r.node.id.name);return!!o?.constant&&o.referencePaths.length>0&&o.referencePaths.every(i=>Lm(i,n))}return!1}function QI(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&&We.isIdentifier(o.node.id)){let i=o.scope.getBinding(o.node.id.name);return!!i?.constant&&QI(i,n)}return!1})}function Ri(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 Ri(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 Ri(i,t,r)}return null}if(e.isBinaryExpression({operator:"+"})){let o=Ri(e.get("left"),t,r),i=Ri(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 l=Ri(a,t,r);if(l===null&&!t)return null;o+=(l??":record")+(e.node.quasis[s+1]?.value.cooked??"")}return o}return null}import{createHash as Tk}from"node:crypto";import Ym from"node:path";import Zm from"@babel/traverse";import*as et from"@babel/types";import{GeneratedSiteCapabilitiesSchema as m$,SiteEditSourcePathSchema as g$}from"@vcp-dev/contracts";import{parse as Hm}from"@babel/parser";import*as Y from"@babel/types";import{PortableCollectionRecipeFactsSchema as Y0}from"@vcp-dev/contracts";import{parse as Qr}from"@babel/parser";import Dm from"@babel/traverse";import*as O from"@babel/types";import{createHash as p0}from"node:crypto";import{GeneratedSiteCapabilitiesSchema as m0,generateDetailBreadcrumb as g0,ResolvedFieldSchema as h0}from"@vcp-dev/contracts";import*as xt from"@babel/types";function ek(e){if(!xt.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(!xt.isObjectPattern(o)||o.properties.length!==1||!xt.isObjectProperty(o.properties[0])||o.properties[0].computed||!xt.isIdentifier(o.properties[0].key,{name:"children"})||!xt.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=xt.isBlockStatement(s)?s.body.length===1&&xt.isReturnStatement(s.body[0])?s.body[0].argument:null:s,l=new Set(["article","aside","div","footer","header","li","main","nav","ol","p","section","span","ul"]),c=(u,d)=>{if(!u||d>32)return!1;if(xt.isJSXExpressionContainer(u))return u.expression===i.referencePaths[0].node;if(!xt.isJSXElement(u)&&!xt.isJSXFragment(u)||xt.isJSXElement(u)&&(!xt.isJSXIdentifier(u.openingElement.name)||!l.has(u.openingElement.name.name)||u.openingElement.attributes.length>0))return!1;let f=u.children.filter(g=>!xt.isJSXText(g)||g.value.trim()!=="");return f.length===1&&c(f[0],d+1)};return c(a,0)}var Zs=typeof Dm=="function"?Dm:Dm.default;function $m(e){return ok(e,!1)}function y0(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=ok({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 ok(e,t){let n=Km(e.files),r=(g,m,p)=>({complete:!1,relation:null,errors:[{code:g,path:m,message:p}]}),o=sk(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(mk),l=a.find(g=>typeof n.get(g)!="string");if(l)return r("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",l,"A candidate detail route is not valid UTF-8 source, so uniqueness cannot be proven.");let c=a.flatMap(g=>{let m=n.get(g);if(typeof m!="string")return[];let p=Fo(g,m,i,"getByUrlStrict",n,e.detail_prefix??`/${i}`);return p&&Wl(p.ast,e.detail_prefix??`/${i}`)!==null?[p]:[]});if(c.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=c[0];if(!D0(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=Cn(u.source,{filePath:u.path,exportName:"default"}).components.flatMap(g=>{let m=nn(u.path,g.source,n),p=m?n.get(m):void 0;return!m||typeof p!="string"||!lk(p,g.export_name)||!zl(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 ik(e){let t=sk(e,Km(e.files));return t.complete&&t.consumer!==null}function sk(e,t,n=!1){let r=(l,c)=>({complete:!1,errors:[{code:"RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",path:l,message:c}]}),o=nn(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(!C0(i,o,"listStrict"))return{complete:!0,slug:null,consumer:null};if(!n&&!Hl(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=P0(i,o),a=s?Fo(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 Hl(e,t,n,r=!1,o="default"){let i=yt(n.get(e));if(i===null)return!1;let s=Ee(e,i);if(!s.ok)return!1;let a=Ut({module:s.module,exportName:o,allowNonRenderingGuards:r});if(!a.ok||a.metadataOnly)return!1;let l=Cn(i,{filePath:e,exportName:o}),c=new Set(l.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"),h=p.node.name;if(!O.isJSXIdentifier(h))return;if(!/^[a-z]/u.test(h.name)){let x=p.scope.getBinding(h.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"&&O.isIdentifier(x.path.node.imported,{name:"default"}))&&typeof p.node.start=="number"&&c.has(p.node.start)&&nn(e,E.node.source.value,n)===t){f++;return}if(!ek(p))return}if(x0(p.node))return}for(let p of m.get("children"))if(p.isJSXElement()||p.isJSXFragment())g(p);else if(p.isJSXExpressionContainer()){let h=p.get("expression");(h.isJSXElement()||h.isJSXFragment())&&g(h)}};for(let m of d)g(m);return f};return a.returnAlternatives?a.returnAlternatives.every(d=>u([d])===1):u(a.roots)===1}function x0(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 Um(e){let t=Km(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."});Mm(t,e.collection.list_entry_file,"RELATED_LIST_ENTRY_MISSING",n),Mm(t,e.collection.detail_entry_file,"RELATED_DETAIL_ENTRY_MISSING",n),Mm(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 l=e.list_route_required??!i,c=l&&pk(e.collection.list_entry_file);l&&!c&&n.push({code:"RELATED_LIST_ROUTE_UNPROVEN",path:e.collection.list_entry_file,message:"The collection caller is not a Next App Router page."}),c&&Bm(o,{path:e.collection.list_entry_file,kind:"route",requirementKey:e.collection.requirement_key}),mk(e.collection.detail_entry_file)?Bm(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=ar({entry_files:[e.collection.detail_entry_file],files:t}),d=new Set;if(i)if(!m0.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"||Si({node:b,host_capabilities:e.host_capabilities}).ownership!=="host-public"&&!M0(b.path))continue;d.add(b.path);let v=s.get(b.path),P=v===void 0?null:`sha256:${p0("sha256").update(v).digest("hex")}`;(!P||e.trusted_host_file_hashes?.get(b.path)!==P)&&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 f=u.nodes.find(b=>b.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?E0(e.collection,t,s):null,m=e.trusted_schema===void 0?null:S0(e,t,n,e.trusted_schema),p=i&&m&&e.trusted_schema?b0(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)&&!(!c&&b.path===e.collection.list_entry_file)){if(L0(b.path,e.collection)){if(i&&b.path!==g&&b.path!==p){n.push({code:"RELATED_MANAGED_SOURCE_UNPROVEN",path:b.path,message:"A related generated source cannot be omitted based on its pathname alone."});continue}Bm(o,{path:b.path,kind:b.path.includes("/page.")?"route":"adapter",requirementKey:e.collection.requirement_key});continue}B0(b.path,e.collection.detail_view_file,e.collection.slug)&&r.push({path:b.path,export:{kind:"default"},purpose:"i18n-companion"})}let h=t.get(e.collection.detail_view_file);typeof h=="string"&&O0(h,e.collection.detail_view_file,u.nodes,t,r,d),e.page_template&&(a=F0(e.page_template,t,n));let x=U0(r).map((b,S)=>({key:K0(b,S),pathTemplate:b.path,export:b.export,purpose:b.purpose,requirementKey:e.collection.requirement_key})),E=J0(n).sort(X0);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(V0),thin_entry_plan:a,collection_wiring:m,errors:E}}function b0(e,t,n,r,o){let i=h0.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,l=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(l.has(b))return null;l.add(b)}let c=new Set(t.force_multi_media??[]);for(let E of c){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=yt(r.get(t.list_container_file)),d=yt(r.get(e.detail_entry_file)),f=Vm(e.detail_entry_file);if(u===null||d===null||!f)return null;let g=Fo(t.list_container_file,u,e.slug,"listStrict",r),m=Fo(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||nn(g.path,g.adapter_source,r)!==p||nn(m.path,m.adapter_source,r)!==p)return null;let h=o.get(p);if(h===void 0)return null;let x=fm(e.slug,s,{forceMultiMedia:c});return typeof h=="string"?h===x?p:null:Buffer.from(h).equals(Buffer.from(x))?p:null}function E0(e,t,n){let r=t.get(e.detail_entry_file),o=Vm(e.detail_entry_file);if(typeof r!="string"||!o)return null;let i=Fo(e.detail_entry_file,r,e.slug,"getByUrlStrict",t,o);if(!i)return null;let s=Wl(i.ast,o),a=uk(i,t,s);if(!s||!a||a==="unproven")return null;let l=`components/site/generated/${e.slug}-breadcrumb.tsx`;if(!Hl(i.path,l,t,!0))return null;let c=n.get(l);return c===void 0?null:[void 0,{variant:"floating",shape:"bar"},{variant:"floating",shape:"island"}].some(d=>{let f=g0({slug:e.slug,detailPrefix:s,...a,headerShell:d});return typeof c=="string"?c===f:Buffer.from(c).equals(Buffer.from(f))})?l:null}function S0(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 P=t.get(v.path);if(typeof P!="string")return[];let I=Fo(v.path,P,e.collection.slug,"listStrict",t);return I?[I]:[]});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,l=a?tk(a,t,v=>v!==e.collection.detail_view_file):null;l?a&&!zl(t.get(l.source_path),a.adapter_source,a.interface_name)&&n.push({code:"RELATED_COLLECTION_LIST_VIEW_UNPROVEN",path:l.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 c=t.get(e.collection.detail_entry_file),u=Vm(e.collection.detail_entry_file),d=typeof c=="string"&&u?Fo(e.collection.detail_entry_file,c,e.collection.slug,"getByUrlStrict",t,u):null,f=d?tk(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."}):zl(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?nn(a.path,a.adapter_source,t):null,p=m?t.get(m):null,h=[...e.required_fields??i.filter(v=>v.required).map(v=>v.name)].sort(jm),x=[...e.force_multi_media??(typeof p=="string"?dk(p):[])].sort(jm);for(let v of[...h,...x])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&&x.length)for(let v of x)(typeof p!="string"||!w0(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?Wl(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?T0(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?uk(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||!l||!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:{...l,interface_name:a.interface_name},detail_view:{...f,interface_name:d.interface_name},...b?{title:b}:{},...S&&S!=="unproven"?{breadcrumb:S}:{},...h.length>0?{required_fields:h}:{},...x.length>0?{force_multi_media:x}:{}}}function Fo(e,t,n,r,o,i=`/${n}`){let s;try{s=Qr(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch{return null}let a=qr(s,u=>O.isCallExpression(u)&&Lo(u.callee,r));if(!R0(s,e,o,r)||r==="listStrict"&&(a.length!==1||!O.isStringLiteral(a[0]?.arguments[0],{value:n}))||r==="getByUrlStrict"&&(a.length===0||Wl(s,i)===null))return null;let c=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=>qr(s,d=>O.isIdentifier(d,{name:u.local_name})).length>1);return c.length!==1||!v0(s,e,o,c[0],r,n)?null:{path:e,source:t,ast:s,adapter_source:c[0].source,interface_name:c[0].interface_name}}function v0(e,t,n,r,o,i){let s=!1;return Zs(e,{JSXOpeningElement(a){let l=a.getFunctionParent();if(!l?.isFunctionDeclaration()||!l.parentPath.isExportDefaultDeclaration()||!O.isJSXIdentifier(a.node.name)||a.node.attributes.some(x=>O.isJSXSpreadAttribute(x)))return;let c=a.parentPath;for(;c&&!c.isReturnStatement()&&!c.isFunction();){if(c.isVariableDeclarator()||c.isJSXAttribute()||c.isConditionalExpression()||c.isLogicalExpression()||c.isCallExpression()||c.isJSXElement()&&c.node!==a.parentPath.node&&(!O.isJSXIdentifier(c.node.openingElement.name)||!/^[a-z]/u.test(c.node.openingElement.name.name)))return;c=c.parentPath}if(!c?.isReturnStatement()||c.getFunctionParent()!==l||c.parentPath!==l.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=nn(t,f.node.source.value,n);if(!g||!zl(n.get(g),r.source,r.interface_name))return;let m=a.get("attributes").filter(x=>x.isJSXAttribute()&&O.isJSXIdentifier(x.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 h={opening:a,attribute:o==="listStrict"?"records":"record",file:t,files:n};(o==="listStrict"?ak(p.get("expression"),l,r,i,h,new Set):ck(p.get("expression"),l,r,h,new Set))&&(s=!0)}}),s}function ak(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"})||Ys(m.referencePaths,n,o)?!1:ak(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||!Xl(a,n))return!1;let l=s.get("object");if(l.isConditionalExpression()){let m=l.get("consequent"),p=l.get("alternate"),h=x=>x.isArrayExpression()&&x.node.elements.length===0;if(h(m))l=p;else if(h(p))l=m;else return!1}if(!l.isMemberExpression()||l.node.computed||!O.isIdentifier(l.node.property,{name:"items"}))return!1;let c=l.get("object");if(!c.isMemberExpression()||c.node.computed||!O.isIdentifier(c.node.property,{name:"data"}))return!1;let u=c.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"})||Ys(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()&&Lo(g.node.callee,"listStrict")&&O.isStringLiteral(g.node.arguments[0],{value:r})}function ck(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"})||Ys(d.referencePaths,n,r)?!1:ck(d.path.get("init"),t,n,r,o)}if(!e.isCallExpression()||e.node.arguments.length!==1)return!1;let i=e.get("callee");if(!Xl(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 l=a.scope.getBinding(a.node.name);if(!l?.constant||!l.path.isVariableDeclarator()||l.path.getFunctionParent()!==t||!l.path.parentPath.isVariableDeclaration({kind:"const"})||Ys(l.referencePaths,n,null))return!1;let c=l.path.get("init");if(!c.isAwaitExpression())return!1;let u=c.get("argument");return u.isCallExpression()&&Lo(u.node.callee,"getByUrlStrict")}function Xl(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 Ys(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),Ys(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 l=s.get("callee"),c=s.get("arguments")[0];return!(l.isMemberExpression()&&!l.node.computed&&O.isIdentifier(l.node.property,{name:"map"})&&c&&Xl(c,t))}let a=s.get("callee");return!(i.isMemberExpression()&&!i.node.computed&&O.isIdentifier(i.node.property,{name:"data"})&&Xl(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()&&I0(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 I0(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=nn(r.file,s.node.source.value,r.files),l=nn(r.file,n.source,r.files),c=a?r.files.get(a):void 0,u=l?r.files.get(l):void 0;return typeof c!="string"||typeof u!="string"?!1:k0(c,a)&&_0(u,l,`to${n.interface_name}`,t)}function k0(e,t){let n=Ee(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 Zs(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 _0(e,t,n,r){let o=Ee(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(Zs(o.module.ast,{Program(d){let f=d.scope.getBinding(n);a=!!(f?.constant&&f.path.node===s),d.stop()}}),!a)return!1;let l=qr(s.body,d=>O.isReturnStatement(d)),c=s.body.body.at(-1);if(l.length!==1||!O.isReturnStatement(c)||c!==l[0]||!O.isObjectExpression(c.argument))return!1;let u=new Set;for(let d of c.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 R0(e,t,n,r){let o=0,i=tr(e,"cms");for(let s of e.program.body){if(!O.isImportDeclaration(s)||s.importKind==="type")continue;let a=nn(t,s.source.value,n);!a||!/^(?:src\/)?lib\/cms(?:\/index|\/collections)?\.[cm]?[jt]s$/u.test(a)||s.specifiers.some(l=>{if(O.isImportSpecifier(l)&&l.importKind==="type")return!1;if(!O.isImportSpecifier(l))return!0;let c=O.isIdentifier(l.imported)?l.imported.name:l.imported.value;return c==="collections"||c==="cms"&&l.local.name!=="cms"})&&(i=!0)}return Zs(e,{CallExpression(s){if(!Lo(s.node.callee,r))return;o+=1;let a=s.scope.getBinding("cms"),l=a?.path,c=l?.parentPath;if(!a?.constant||!l?.isImportSpecifier()||l.node.importKind==="type"||!O.isIdentifier(l.node.imported,{name:"cms"})||!c?.isImportDeclaration()||c.node.importKind==="type"){i=!0;return}let u=nn(t,c.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 P0(e,t){let n;try{n=Qr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let r=qr(n,o=>O.isCallExpression(o)&&Lo(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 C0(e,t,n){let r;try{r=Qr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return!1}return qr(r,o=>O.isCallExpression(o)&&Lo(o.callee,n)).length>0}function tk(e,t,n){let r=Cn(e.source,{filePath:e.path,exportName:"default"});if(r.diagnostics.length>0)return null;let o=r.components.flatMap(i=>{let s=nn(e.path,i.source,t),a=s?t.get(s):null;return!s||!n(s)||typeof a!="string"||!lk(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 lk(e,t){let n;try{n=Qr(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 zl(e,t,n){if(typeof e!="string")return!1;let r;try{r=Qr(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=>qr(r,s=>O.isIdentifier(s,{name:i})).length>1)}function Lo(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 Wl(e,t){let n=[];return Zs(e,{CallExpression(r){Lo(r.node.callee,"getByUrlStrict")&&n.push(N0(r.node.arguments[0],o=>A0(r,o)))}}),n.length===0?null:n.every(r=>r===t)?t:null}function N0(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 A0(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&&Gl(a.key)==="slug"&&O.isIdentifier(a.value,{name:t}))&&nk(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)&&nk(n.path,s.object.argument.name)}function nk(e,t){let n=e.scope.getBinding(t);if(!n?.constant||n.kind!=="param")return!1;let r=n.path.getFunctionParent();if(!r||!r.isFunctionDeclaration())return!1;let o=r.parentPath;return!o.isExportDefaultDeclaration()&&!(o.isExportNamedDeclaration()&&r.node.id?.name==="generateMetadata")?!1:r.node.params.some(i=>O.isObjectPattern(i)&&i.properties.some(s=>O.isObjectProperty(s)&&!s.computed&&Gl(s.key)==="params"&&O.isIdentifier(s.value,{name:t})))}function T0(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=fk(n.init);if(!O.isObjectExpression(r))return null;let o=r.properties.find(i=>O.isObjectProperty(i)&&!i.computed&&Gl(i.key)==="title");return o&&O.isStringLiteral(o.value)?o.value.value:null}return null}function uk(e,t,n){let o=Cn(e.source,{filePath:e.path,exportName:"default"}).components.filter(l=>/(?:^|\/)components\/site\/generated\/[A-Za-z0-9_-]+-breadcrumb$/u.test(l.source));if(o.length===0)return null;if(o.length!==1||!n)return"unproven";let i=nn(e.path,o[0].source,t),s=i?t.get(i):null;if(typeof s!="string")return"unproven";let a;try{a=Qr(s,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return"unproven"}for(let l of qr(a,c=>O.isArrayExpression(c))){let c=l.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=Gl(m.key);p&&O.isStringLiteral(m.value)&&g.set(p,m.value.value)}return g.has("name")&&g.has("href")?[g]:[]}),u=c.find(f=>f.get("href")==="/"),d=c.find(f=>f.get("href")===n);if(u&&d)return{homeLabel:u.get("name"),collectionLabel:d.get("name")}}return"unproven"}function dk(e){let t;try{t=Qr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return[]}return[...new Set(qr(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(jm)}function w0(e,t){return dk(e).includes(t)}function qr(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)rk(s)&&r(s);else rk(i)&&r(i)};return r(e),n}function rk(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function fk(e){return e?O.isTSAsExpression(e)||O.isTSTypeAssertion(e)||O.isTSNonNullExpression(e)?fk(e.expression):e:null}function Gl(e){return O.isIdentifier(e)?e.name:O.isStringLiteral(e)?e.value:null}function jm(e,t){return e.localeCompare(t)}function O0(e,t,n,r,o,i){let s=Cn(e,{filePath:t,exportName:"default"});for(let a of s.components){let l=nn(t,a.source,r);if(!l||i.has(l))continue;let c=n.find(d=>d.path===l),u=r.get(l);!c||c.kind==="external"||typeof u!="string"||j0(u)&&o.push({path:l,export:a.export_name==="default"?{kind:"default"}:{kind:"named",name:a.export_name},purpose:"client-importer"})}}function F0(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=Cn(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 Mm(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 L0(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 pk(e){return/^(?:src\/)?app\/(?:[^/.][^/]*\/)*page\.[cm]?[jt]sx?$/u.test(e)}function mk(e){return pk(e)&&/\/\[slug\]\/page\.[cm]?[jt]sx?$/u.test(e)}function D0(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 Vm(e){let t=/^(?:src\/)?app\/([A-Za-z0-9_-]+)\/\[slug\]\/page\.[cm]?[jt]sx?$/u.exec(e);return t?`/${t[1]}`:null}function M0(e){return/^(?:src\/)?lib\/cms(?:\.[cm]?[jt]sx?$|\/(?!generated\/))/u.test(e)}function B0(e,t,n){let r=e.replace(/\\/g,"/"),o=t.replace(/\.(?:tsx?|jsx?)$/u,""),i=gk(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 j0(e){try{return Qr(e,{sourceType:"module",plugins:["jsx","typescript"]}).program.directives.some(n=>n.value.value==="use client")}catch{return!1}}function nn(e,t,n){if(!mt(t))return null;let r=t.startsWith("@/")?t.slice(2):$0(`${gk(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 gk(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function $0(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 Km(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=yt(r);return o!==null?(super.set(n,o),o):typeof r=="string"?new TextEncoder().encode(r):r}}(t)}function U0(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 Bm(e,t){e.some(r=>r.path===t.path&&r.kind===t.kind)||e.push(t)}function V0(e,t){return e.path.localeCompare(t.path)||e.kind.localeCompare(t.kind)||e.requirementKey.localeCompare(t.requirementKey)}function K0(e,t){return`${`related.${e.purpose}.${e.path.replace(/[^A-Za-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}`.slice(0,112)}.${t}`}function J0(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function X0(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 Jm from"@babel/traverse";import*as Re from"@babel/types";var z0=typeof Jm=="function"?Jm:Jm.default,H0=Ek(`
|
|
41
|
+
`;return bu({deferClosure:e.defer_module_closure,entryFile:r,entryContent:l,files:n,selection:t,sourceMapping:{generated_path:t.source_file,source_file:t.source_file,structural_path:t.structural_path}})}return n.has(r)?Gt("SOURCE_INPUT_INVALID",r,"The deterministic extracted entry path collides with the fixed Snapshot map."):qj(t,o,n,e.defer_module_closure)}function qj(e,t,n,r){let o;try{o=Hj(t,{sourceType:"module",sourceFilename:e.source_file,plugins:["jsx","typescript"]})}catch(T){return Gt("SOURCE_PARSE_FAILED",e.source_file,T instanceof Error?T.message:String(T))}let i=Qj(o,e);if(i.length!==1)return Gt("SOURCE_NOT_PORTABLE",e.source_file,"The pinned source range must identify exactly one current JSX root.");let s=i[0],a=s.findParent(T=>T.isFunction());if(!a||!pk(a.node))return Gt("SOURCE_NOT_PORTABLE",e.source_file,"The selected JSX root is not inside one statically bounded component function.");let l=a,c=y0(l);if(!c.ok)return Gt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component has hook calls whose order cannot be proven for an isolated root.");let u={imports:new Set,moduleDeclarations:new Set,functionDeclarations:new Set,props:new Map,propsObjectName:null,errors:[]},d=new Set;for(let T of o.program.body){if(!j.isImportDeclaration(T)||T.specifiers.length||T.importKind==="type")continue;let L=T.source.value,$=L.startsWith(".")||L.startsWith("@/")?vu(e.source_file,L,n):null;if(!$?.endsWith(".css"))return Gt("SOURCE_NOT_PORTABLE",e.source_file,"A bare module effect is not a proven portable stylesheet dependency.");d.has($)||u.imports.add(T),d.add($)}let f=e0(l,e);if(!f.ok)return{complete:!1,errors:[f.error]};if(t0(s,s.node,l,f.value,e,c.translationBinding??null,u,n),u.errors.length>0)return{complete:!1,errors:u.errors};if(c.translationBinding&&![...u.functionDeclarations].some(T=>j.isVariableDeclaration(T)&&T.declarations.some(L=>j.isIdentifier(L.id,{name:c.translationBinding}))))return Gt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component's i18n hook is not part of the selected dependency closure.");let m=S0(o,"__vcpPortableProps"),g=j.cloneNode(s.node,!0),p=[];for(let T of[...u.imports].sort(Xm)){let L=g0(T,e.source_file,e.entry_file,n);if(!L.ok)return{complete:!1,errors:[L.error]};p.push(L.node)}let h=[...u.moduleDeclarations].sort(Xm).map(T=>j.cloneNode(T,!0)),x=[...u.functionDeclarations].sort(Xm).map(T=>j.cloneNode(T,!0)),b=j.returnStatement(g),E=[...u.props].filter(([T])=>!T.startsWith("@")).map(([T,L])=>j.variableDeclaration("const",[j.variableDeclarator(j.identifier(T),j.memberExpression(j.identifier(m),j.identifier(L)))]));u.propsObjectName&&E.push(j.variableDeclaration("const",[j.variableDeclarator(j.identifier(u.propsObjectName),j.identifier(m))]));let S=j.blockStatement([...E,...x,b]),v=u.props.size?[m0(m)]:[],A=j.functionDeclaration(j.identifier("PortableBlockEntry"),v,S),I=j.program([...p,...h,A,j.exportDefaultDeclaration(j.identifier("PortableBlockEntry"))]);I.directives=o.program.directives.map(T=>j.cloneNode(T,!0));let _=Yj(j.file(I),{jsescOption:{minimal:!0}}).code,k={generated_path:e.entry_file,source_file:e.source_file,structural_path:e.structural_path};return bu({deferClosure:r,entryFile:e.entry_file,entryContent:_,files:n,selection:e,sourceMapping:k,invocationBindings:E0(e,u.props)})}function Qj(e,t){let n=[];return Gm(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:Tt("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(j.isIdentifier(o))return{ok:!0,value:{bindingByLocalName:r,propsParameter:o}};if(!j.isObjectPattern(o))return{ok:!1,error:Tt("SOURCE_NOT_PORTABLE",t.source_file,"Component props must use one identifier or a static object pattern.")};for(let i of o.properties){if(!j.isObjectProperty(i)||i.computed||!(j.isIdentifier(i.key)||j.isStringLiteral(i.key))||!(j.isIdentifier(i.value)||j.isAssignmentPattern(i.value)&&j.isIdentifier(i.value.left)))return{ok:!1,error:Tt("SOURCE_NOT_PORTABLE",t.source_file,"Rest, computed, or nested component prop destructuring is not supported.")};let s=j.isIdentifier(i.key)?i.key.name:i.key.value,a=i.value,l=j.isIdentifier(a)?a.name:j.isAssignmentPattern(a)&&j.isIdentifier(a.left)?a.left.name:"";r.set(l,s)}return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}}}function t0(e,t,n,r,o,i,s,a){let l=new Set,c=new Map,u=g=>{let p=c.get(g);if(p!==void 0)return p;let h=r0(n,r,g,o,a);return c.set(g,h),h||s.errors.push(Tt("SOURCE_NOT_PORTABLE",o.source_file,`Selected prop ${g} is mutated or escapes its proven invocation value.`)),h},d=g=>{let p=g.node.name,h=g.scope.getBinding(p);if(!h){Qv.has(p)||s.errors.push(Tt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root references unbound identifier ${p}.`));return}if(!Su(h.path.node,t)){if(r.bindingByLocalName.has(p)&&h.scope===n.scope){let x=r.bindingByLocalName.get(p);tk(o,x)?u(x)&&s.props.set(p,x):s.errors.push(Tt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root prop ${x} has no proven invocation binding.`));return}if(r.propsParameter&&h.path.node===r.propsParameter&&g.parentPath?.isMemberExpression()&&g.parentPath.node.object===g.node){let x=g.parentPath.node,b=!x.computed&&j.isIdentifier(x.property)?x.property.name:x.computed&&j.isStringLiteral(x.property)?x.property.value:null;b&&tk(o,b)?u(b)&&(s.propsObjectName=p,s.props.set(`@${p}.${b}`,b)):s.errors.push(Tt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root reads an unproven dynamic prop through ${p}.`));return}l.has(h)||(l.add(h),ek(h,n,o,s,d,f,a))}},f=(g,p)=>{let h=fk(g);if(!h||/^[a-z]/u.test(h.name))return;let x=p.scope.getBinding(h.name);if(!x){Qv.has(h.name)||s.errors.push(Tt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root component ${h.name} has no proven import or declaration.`));return}l.has(x)||Su(x.path.node,t)||(l.add(x),ek(x,n,o,s,d,f,a))};(g=>{g.isIdentifier()&&g.isReferencedIdentifier()&&d(g),g.isJSXElement()&&f(g.node.openingElement.name,g),g.traverse({ReferencedIdentifier(p){d(p)},JSXOpeningElement(p){f(p.node.name,p)},CallExpression(p){dk(p,i)||s.errors.push(Tt("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(Tt("SOURCE_NOT_PORTABLE",o.source_file,"Assignments inside a selected root are not a closed Portable dependency.")),p.stop()},UpdateExpression(p){s.errors.push(Tt("SOURCE_NOT_PORTABLE",o.source_file,"Updates inside a selected root are not a closed Portable dependency.")),p.stop()},NewExpression(p){s.errors.push(Tt("SOURCE_NOT_PORTABLE",o.source_file,"Dynamic object construction inside a selected root is not proven portable.")),p.stop()}})})(e)}function ek(e,t,n,r,o,i,s){let a=e.path;if(b0(a,t)||a.isFunctionDeclaration()&&a.node===t.node){r.errors.push(Tt("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(Tt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is rebound outside its declaration.`));return}if(a0(e)){r.errors.push(Tt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} has a member write outside its declaration.`));return}let l=new Eu(s),c=new Map,u=a.parentPath,d=u?.isImportDeclaration(),f=!1;if(d&&(u.node.source.value.startsWith(".")||u.node.source.value.startsWith("@/"))){let h=vu(n.source_file,u.node.source.value,s),x=h?l.get(h):void 0,b=a.isImportDefaultSpecifier()?"default":a.isImportSpecifier()&&a.node.importKind!=="type"?In(a.node.imported,!1):null,E=x&&b&&u.node.importKind!=="type"?Bo(x,b,l):null,S=E?Sn(E):null;if(!S?.length){r.errors.push(Tt("SOURCE_NOT_PORTABLE",n.source_file,"The imported value has no bounded unique Snapshot source."));return}c.set(e.identifier,S),f=S.every(v=>v.isFunctionDeclaration()||v.isFunctionExpression()||v.isArrowFunctionExpression())}else d&&(f=e.referencePaths.every(h=>h.parentPath?.isJSXOpeningElement()||h.parentPath?.isJSXClosingElement()||h.parentPath?.isCallExpression()&&h.parentPath.node.callee===h.node));if((d&&!f||n0(e))&&!Ia(e,{bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:c,files:s,modules:l},!1)){r.errors.push(Tt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is mutated or escapes its static object shape.`));return}let m=a.isImportDeclaration()?a:a.findParent(h=>h.isImportDeclaration());if(m?.isImportDeclaration()){r.imports.add(m.node);return}let g=a.isVariableDeclarator()?a:a.findParent(h=>h.isVariableDeclarator());if(g?.isVariableDeclarator()){let h=g.parentPath,x=g.get("init");if(!h?.isVariableDeclaration()||h.node.kind!=="const"||!x.node||!Fr(g.node.id)||!Fr(x.node)&&!x0(x)){r.errors.push(Tt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a side-effect-free const.`));return}let E=h.findParent(v=>v.isFunction())===t?r.functionDeclarations:r.moduleDeclarations,S=j.variableDeclaration("const",[j.cloneNode(g.node,!0)]);nk(E,S,g.node),g.traverse({ReferencedIdentifier(v){v.isIdentifier()&&o(v)},JSXOpeningElement(v){i(v.node.name,v)}});return}let p=a.isFunctionDeclaration()?a:a.findParent(h=>h.isFunction());if(p?.isFunctionDeclaration()&&el(p.node)){let x=p.findParent(b=>b.isFunction())===t?r.functionDeclarations:r.moduleDeclarations;nk(x,j.cloneNode(p.node,!0),p.node),p.traverse({ReferencedIdentifier(b){b.isIdentifier()&&o(b)},JSXOpeningElement(b){i(b.node.name,b)}});return}r.errors.push(Tt("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 j.isFunctionExpression(r)||j.isArrowFunctionExpression(r)||j.isCallExpression(r)&&tl(r)?!1:!Hf(e)?.every(i=>i.isFunctionExpression()||i.isArrowFunctionExpression()||Wf(i,new Map))}var Eu=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=Te(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(c=>c.propName===n);if(!i)return!1;let s=[];if(i.value.kind==="json-literal"){let c=j.file(j.program([j.expressionStatement(j.valueToNode(i.value.value))]));Gm(c,{ExpressionStatement(u){s.push(u.get("expression")),u.stop()}})}let a=new Map,l={bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:a,files:o,modules:new Eu(o)};if(t.propsParameter)return zm(e,n,s,l);for(let[c,u]of t.bindingByLocalName){if(u!==n)continue;let d=e.scope.getBinding(c);if(!d||(a.set(d.identifier,s),!Ia(d,l,!0)))return!1}return!0}function o0(e,t){if(Wf(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(j.isJSXIdentifier(i)&&/^[a-z]/u.test(i.name))return!0;if(!j.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)},l=Sn(e,t.inputs);if(!l)return!1;if(r.isJSXSpreadAttribute()){let u=new Set;for(let d of l){if(!d.isObjectExpression())return!1;for(let f of d.node.properties){if(!j.isObjectProperty(f)||f.computed)return!1;let m=In(f.key,!1);if(m===null)return!1;u.add(m)}}return[...u].every(d=>{let f=nl(l,d,t.inputs);return f!==null&&zm(s,d,f,a)})}let c=r.isJSXAttribute()&&j.isJSXIdentifier(r.node.name)?r.node.name.name:"children";return zm(s,c,l,a)}function i0(e,t){let n=e.node.name;if(!j.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=vu(s,i,t.files);if(!a)return null;let l=t.modules.get(a);if(!l)return null;let c=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()?In(r.path.node.imported,!1):null;if(!c)return null;let u=En({module:l,exportName:c,parsedModules:t.modules});return u.ok?u.roots[0]?.getFunctionParent()??null:null}function zm(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 l of o.get("properties")){if(!l.isObjectProperty()||l.node.computed){if(Object.keys(l.getBindingIdentifiers()).some(f=>l.scope.getBinding(f)?.referencePaths.length))return!1;continue}if(In(l.node.key,!1)!==t)continue;let c=l.get("value");if(!c.isIdentifier())return!1;let u=c.scope.getBinding(c.node.name);if(!u)return!1;i.set(u.identifier,n),a=Ia(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 l=a.parentPath;if(!(l?.isMemberExpression()||l?.isOptionalMemberExpression())||l.node.object!==a.node)return!1;let c=In(l.node.property,l.node.computed);return c===null?!1:c!==t?!0:(i.set(l.node,n),ck(l,{...r,inputs:i},!0))})}function Ia(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=>ck(i,r,n));return o&&t.bindings.add(e),o}function Zm(e,t,n){let r=e.node.id;if(j.isIdentifier(r)){let o=e.scope.getBinding(r.name);return o?Ia(o,t,n):!1}if(j.isObjectPattern(r)||j.isArrayPattern(r)){let o=[];return zi(r,o)?s0(o,e,t):!1}return!1}function zi(e,t){if(j.isRestElement(e))return zi(e.argument,t);if(j.isIdentifier(e))return t.push(e.name),!0;if(j.isAssignmentPattern(e))return zi(e.left,t);if(j.isObjectPattern(e)){for(let n of e.properties){if(j.isRestElement(n)){if(!zi(n.argument,t))return!1;continue}if(!j.isObjectProperty(n)||n.computed||!(j.isIdentifier(n.key)||j.isStringLiteral(n.key)||j.isNumericLiteral(n.key))||!zi(n.value,t))return!1}return!0}if(j.isArrayPattern(e)){for(let n of e.elements)if(n&&!zi(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?Ia(o,n,!0):!1})}function a0(e){return e.referencePaths.some(t=>{let{current:n,memberAccess:r}=ak(t);if(!r)return!1;let o=n.parentPath;return!!(sk(n)||o?.isUpdateExpression()||o?.isUnaryExpression({operator:"delete"}))})}function sk(e){let t=e.findParent(n=>n.isAssignmentExpression()||n.isForXStatement());return t&&(t.isAssignmentExpression()||t.isForXStatement())?Su(e.node,t.node.left):!1}function ak(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 ck(e,t,n){if(!u0(e,t))return!1;let{current:r,memberAccess:o}=ak(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 sk(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(j.isIdentifier(r)){if(ik.has(r.name))return e.scope.getBinding(r.name)===void 0;let i=e.scope.getBinding(r.name);return!i||!Si(i)?!1:Sa(e,n,new Set)}if(!j.isMemberExpression(r)&&!j.isOptionalMemberExpression(r)||!j.isIdentifier(r.property))return!1;let o=qm(r);return!o||e.scope.getBinding(o.name)?!1:o.name==="Object"&&r.property.name==="assign"?e.node.arguments[0]===t.node?!1:Sa(e,n,new Set):ok.get(o.name)?.has(r.property.name)??!1?uk(e)?Sa(e,n,new Set):!0:!1}function l0(e,t,n,r){let o=lk(e);return o.kind==="declarator"?Zm(o.declarator,r,o.directValue):o.kind==="escape"||o.kind==="call"?!1:t||n}function lk(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 Sa(e,t,n){if(n.has(e.node))return!0;n.add(e.node);let r=lk(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:uk(r.call)?Sa(r.call,t,n):f0(r.call):!0}function u0(e,t){let n=e.findParent(o=>o.isFunction());if(!n||!pk(n.node))return!0;let r=d0(n);return!r||!Si(r)?!0:r.referencePaths.every(o=>{let i=o.parentPath;return!i?.isCallExpression()||i.node.callee!==o.node?!0:Sa(i,t,new Set)})}function d0(e){let t=e.node,n=null;if(j.isFunctionDeclaration(t)?n=t.id?.name??null:(j.isArrowFunctionExpression(t)||j.isFunctionExpression(t))&&e.parentPath?.isVariableDeclarator()&&j.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 uk(e){let t=e.node.callee;if(j.isIdentifier(t)){let r=e.scope.getBinding(t.name);return!!(r&&Si(r))}if(!j.isMemberExpression(t)&&!j.isOptionalMemberExpression(t)||!j.isIdentifier(t.property))return!1;let n=qm(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(j.isIdentifier(t))return ik.has(t.name)&&e.scope.getBinding(t.name)===void 0;if(!j.isMemberExpression(t)&&!j.isOptionalMemberExpression(t)||!j.isIdentifier(t.property))return!1;let n=qm(t);return!n||e.scope.getBinding(n.name)||n.name==="Object"&&t.property.name==="assign"?!1:ok.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 p0(e){let t=e;for(;t&&(j.isTSAsExpression(t)||j.isTSTypeAssertion(t)||j.isTSNonNullExpression(t)||j.isTSSatisfiesExpression(t)||j.isParenthesizedExpression(t));)t=t.expression;return t&&j.isExpression(t)?t:null}function qm(e){return!e.computed&&j.isIdentifier(e.object)?e.object:null}function m0(e){let t=j.identifier(e);return t.typeAnnotation=j.tsTypeAnnotation(j.tsTypeReference(j.identifier("Record"),j.tsTypeParameterInstantiation([j.tsStringKeyword(),j.tsAnyKeyword()]))),t}function bu(e){let t=new Map(e.files);t.set(e.entryFile,e.entryContent);let n=e.deferClosure?null:vr({entry_files:[e.entryFile],files:t});if(n&&!n.complete)return{complete:!1,errors:n.errors.map(i=>Tt(I0(i.code),i.path,i.message))};let r=[];for(let i of n?.nodes??[{path:e.entryFile,kind:"source"}]){if(i.kind!=="source"&&i.kind!=="asset")continue;let s=Iu(t,i.path);if(s===null)return Gt("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=j.cloneNode(e,!0),i=e.source.value;if(i.startsWith("./")||i.startsWith("../")){let s=vu(t,i,r);if(!s)return{ok:!1,error:Tt("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 vu(e,t,n){let r=t.startsWith("@/")?t.slice(2):Ea.posix.normalize(Ea.posix.join(Ea.posix.dirname(e),t));if(!Wm(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=Ea.posix.relative(Ea.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(!j.isIdentifier(i)||!/^use[A-Z0-9]/u.test(i.name))return;if(i.name!=="useTranslations"||o.node.arguments.length!==1||!j.isStringLiteral(o.node.arguments[0])){r=!0,o.stop();return}let s=o.scope.getBinding(i.name),a=s?.path.findParent(c=>c.isImportDeclaration());if(!s?.path.isImportSpecifier()||!a?.isImportDeclaration()||a.node.source.value!=="next-intl"||!j.isIdentifier(s.path.node.imported,{name:"useTranslations"})){r=!0,o.stop();return}n+=1;let l=o.findParent(c=>c.isVariableDeclarator());if(!l?.isVariableDeclarator()||!j.isIdentifier(l.node.id)){r=!0,o.stop();return}t=l.node.id.name}}),r||n>1?{ok:!1}:t?{ok:!0,translationBinding:t}:{ok:!0}}function dk(e,t){let n=e.node.callee;if(j.isImport(n))return!1;if(t&&j.isIdentifier(n,{name:t})&&e.node.arguments.length>0&&e.node.arguments.every(o=>j.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!!(j.isCallExpression(s)&&tl(s))}if(!j.isIdentifier(n))return!1;let r=e.scope.getBinding(n.name);return r?Si(r):!1}function x0(e){return e.isCallExpression()&&dk(e,null)&&j.isIdentifier(e.node.callee)&&e.scope.getBinding(e.node.callee.name)?.constantViolations.length===0&&e.node.arguments.every(t=>j.isExpression(t)&&Fr(t))}function fk(e){return j.isJSXIdentifier(e)?j.isValidIdentifier(e.name)?j.identifier(e.name):null:j.isJSXMemberExpression(e)?fk(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=>j.isObjectPattern(n)&&n.properties.some(r=>j.isObjectProperty(r)&&j.isIdentifier(r.value,{name:e.node.name}))))}function Su(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 pk(e){return j.isFunction(e)}function tk(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;Gm(e,{Identifier(o){n.add(o.node.name)}});let r=t;for(;n.has(r);)r+="_";return r}function nk(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 Xm(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 rk(e,t){let n=zj("sha256").update(t).digest("hex");return e.content_hash===`sha256:${n}`}function Wm(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 Gt(e,t,n){return{complete:!1,errors:[Tt(e,t,n)]}}function Tt(e,t,n){return{code:e,path:t,message:n}}import{createHash as Sk}from"node:crypto";import tg from"@babel/generator";import ng from"@babel/traverse";import*as Ze from"@babel/types";function Ft(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 bk from"@babel/types";import{createHash as Qm}from"node:crypto";var v0="sha256:cdea4bd5eec1d29e9a9693e6545fb0ac81b67b3260d5c957eee827c9f869842f",k0="sha256:89b8fde9bf5ca807e238c3f5f6229e5f107b76a45d4972d245ec842ba3f6f6f5",_0=new Set(["sha256:3cf25df4601562d673864ea135b8808cae2819ca315b16af5ad07a6afbb5d31c","sha256:7ad1062c59fabb7d584691e905919c84ddd0035f7b1ccd7cf58f2ba0b3fdde12"]),C0=new Set(["sha256:64f26e7284e844de65cfeaf268974aeb4a612ae796638fe219587f1d3e46b429"]),R0=new Map([["sha256:3b952ddc14778008dac157346c997cdea06844d890f1e5280ea08d38fbf03776","sha256:061e4143d12a22f4256157df2824144ac8fb86744f456afa50ff963278ddb263"],["sha256:92f7425b0f1eb031ef47470adb2b777fe863234c268504287323ff06cd4f91cc","sha256:4b5aa33d4bbf4e895e0186ee7049a7f9606b5d85ee6e045b8eed084cee458646"]]);function ku(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:${Qm("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 P0(e){return e.index===v0&&e.client===k0&&_0.has(e.collections)}function Qo(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:${Qm("sha256").update(i).digest("hex")}`;return t.get(`${n}${o}.ts`)===s?s:""};return P0({index:r("index"),collections:r("collections"),client:r("client")})&&C0.has(r("field"))}function mk(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:${Qm("sha256").update(r).digest("hex")}`;return o==="sha256:6e1c0d0af2938dc4e74d4a35b185bec0ad1fd6d16fd2323ee0cd72eaa05c836f"&&t.get(n)===o&&Qo(e,t)}import*as mn from"@babel/types";var xt={kind:"primitive"},kr={kind:"json"},eg=new Set(["__proto__","prototype","constructor","then","toString","valueOf","toLocaleString"]),_u=e=>({kind:"object",properties:new Map(Object.entries(e))}),ei=e=>({kind:"array",item:e});function hk(e){let t=new Map;for(let n of e.split("/")){let r=/^\[(\[)?(\.\.\.)?([^\[\]/]+)\]\]?$/u.exec(n);r&&t.set(r[3],r[2]?ei(xt):xt)}return{kind:"object",properties:t}}function tn(e){return!!e&&e.kind!=="promise"&&e.kind!=="jsx"}function yk(e){let t=_u({id:xt,url:xt,seo:kr,fields:kr}),n=["list","listStrict"].includes(e)?_u({items:ei(t),total:xt,page:xt,pageSize:xt}):["get","getStrict","getByUrl","getByUrlStrict"].includes(e)?t:e==="categories"?ei(_u({id:xt,label:xt,children:kr})):e==="schema"?kr:null;return n?{kind:"promise",value:e.endsWith("Strict")?_u({kind:xt,data:n,error:kr}):n}:null}function gk(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 l=a.node.key,c=mn.isIdentifier(l)?l.name:mn.isStringLiteral(l)?l.value:null;c&&!eg.has(c)&&o(a.get("value"),s.properties.get(c)??null)}else i.isAssignmentPattern()&&o(i.get("left"),s)};return e.get("params").forEach((i,s)=>o(i,t[s]??null)),r}function xk(e){let t=(o,i,s,a)=>{if(a.has(o.node)||a.size>=48)return null;let l=new Set(a).add(o.node),c=gk(o,i,s),u=o.get("body"),d=[];u.isBlockStatement()?u.traverse({Function(m){m.skip()},ReturnStatement(m){d.push(m.node.argument?n(m.get("argument"),c,l):xt)}}):d.push(n(u,c,l));let f=va(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),l=m=>n(m,i,a);if(o.isStringLiteral()||o.isNumericLiteral()||o.isBooleanLiteral()||o.isNullLiteral())return xt;if(o.isJSXElement()||o.isJSXFragment())return{kind:"jsx"};if(o.isJSXExpressionContainer()||o.isTSAsExpression()||o.isTSSatisfiesExpression()||o.isTSNonNullExpression()||o.isParenthesizedExpression())return l(o.get("expression"));if(o.isIdentifier()){let m=o.scope.getBinding(o.node.name);if(!m)return["undefined","NaN","Infinity"].includes(o.node.name)?xt:null;if(!m.constant||m.constantViolations.length)return null;let g=i.get(m.identifier);if(g)return g;let p=e.resolve_value?.(o);return p?l(p):m.path.isVariableDeclarator()&&m.path.parentPath.isVariableDeclaration({kind:"const"})?l(m.path.get("init")):null}if(o.isAwaitExpression()){let m=l(o.get("argument"));return m?.kind==="promise"?m.value:tn(m)?m:null}if(o.isObjectExpression()){let m=new Map;for(let g of o.get("properties")){if(!g.isObjectProperty()||g.node.computed)return null;let p=g.node.key,h=mn.isIdentifier(p)?p.name:mn.isStringLiteral(p)?p.value:null,x=n(g.get("value"),i,a);if(!h||eg.has(h)||m.has(h)||!tn(x))return null;m.set(h,x)}return{kind:"object",properties:m}}if(o.isArrayExpression()){if(!o.node.elements.length)return{kind:"array",item:kr,empty:!0};let m=va(o.get("elements").map(g=>l(g)));return tn(m)?ei(m):null}if(o.isMemberExpression()||o.isOptionalMemberExpression()){let m=N0(o);if(!m||eg.has(m))return null;let g=l(o.get("object"));return g?.kind==="object"?g.properties.get(m)??null:g?.kind==="json"?kr:g?.kind==="array"?m==="length"?xt:/^\d+$/u.test(m)?g.item:null:g?.kind==="primitive"&&m==="length"?xt:null}if(o.isConditionalExpression())return va([l(o.get("consequent")),l(o.get("alternate"))]);if(o.isLogicalExpression())return va([l(o.get("left")),l(o.get("right"))]);if(o.isUnaryExpression())return["typeof","!","void"].includes(o.node.operator)||tn(l(o.get("argument")))?xt:null;if(o.isBinaryExpression())return["in","instanceof"].includes(o.node.operator)?null:["===","!=="].includes(o.node.operator)||tn(l(o.get("left")))&&tn(l(o.get("right")))?xt:null;if(o.isTemplateLiteral())return o.get("expressions").every(m=>tn(l(m)))?xt:null;if(!o.isCallExpression())return null;let c=e.cms_value(o,i,a);if(c)return c;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(m=>tn(l(m)))?xt:null;let d=r(o,i,a);if(d)return d.result;if(u.isMemberExpression()&&!u.node.computed){if(mn.isIdentifier(u.node.object,{name:"Object"})&&!u.scope.getBinding("Object")&&mn.isIdentifier(u.node.property,{name:"keys"})&&o.node.arguments.length===1&&tn(l(o.get("arguments")[0])))return ei(xt);let m=l(u.get("object")),g=mn.isIdentifier(u.node.property)?u.node.property.name:"";if(m?.kind==="array"&&g==="slice"&&o.node.arguments.length<=2&&o.get("arguments").every(p=>l(p)?.kind==="primitive"))return m;if(m?.kind==="primitive"&&["includes","startsWith","endsWith","trim","toLowerCase","toUpperCase","replace","split"].includes(g)&&o.get("arguments").every(p=>tn(l(p))))return g==="split"?ei(xt):xt}let f=e.resolve_function(u);return f?t(f,o.get("arguments").map(m=>l(m)),i,a):null};function r(o,i,s=new Set){let a=o.get("callee");if(!a.isMemberExpression()||a.node.computed||!mn.isIdentifier(a.node.property))return null;let l=a.node.property.name;if(!["map","filter","some","every","find"].includes(l)||o.node.arguments.length!==1)return null;let c=n(a.get("object"),i,s);if(c?.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=[c.item,xt,c];if(c.empty)return{target:d,args:f,result:["map","filter"].includes(l)?c:xt,empty:!0};let m=t(d,f,i,s);return m?{target:d,args:f,result:l==="map"?ei(m):l==="filter"?c:l==="find"?c.item:xt}:null}return{value:n,arrayCall:r,bind:gk}}function N0(e){let t=e.node.property;return!e.node.computed&&mn.isIdentifier(t)?t.name:mn.isStringLiteral(t)?t.value:mn.isNumericLiteral(t)?String(t.value):null}function va(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:va(n.map(r=>r?.kind==="array"?r.item:null))??kr}:{kind:"array",item:kr,empty:!0}}return e.every(n=>n?.kind==="primitive")?xt:e.every(n=>n?.kind==="jsx")?t:e.every(tn)?kr:null}function Ek(e){if(!Qo(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 m=Ft(e.files.get(d)),g=m===null?null:Te(d,m);if(g?.ok)return super.set(d,g.module),t.set(g.module.ast.program,g.module),g.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,m=o(u);if(!m||!d?.constant||!d.path.isImportSpecifier()||d.path.node.importKind==="type"||!f?.isImportDeclaration()||f.node.importKind==="type")return null;let g=At(m.file,f.node.source.value,e.files);if(!g)return null;let p=d.path.node.imported;return{module:m,file:g,name:bk.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?Bo(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 m=s(d),g=m&&o(m);return!!(m?.isFunctionDeclaration()&&m.node.id?.name===f.name&&g&&ku(e.files,e.trusted_host_file_hashes,g.file))},l=xk({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(h=>tn(l.value(h,d,f)))?{kind:"json"}:null;let m=u.get("callee");for(;m.isMemberExpression()&&!m.node.computed;)m=m.get("object");if(!m.isIdentifier())return null;let g=i(m);if(!g||g.name!=="cms"||!/^(?:src\/)?lib\/cms\/index\.ts$/u.test(g.file)||yr(g.module.ast,g.local))return null;let p=Dr(u.node,{file:g.module.file,imports:new Map([[g.local,{source:g.file,importedName:g.name}]])})?.operation;return p?yk(p):null}}),c=l.bind(e.owner,[{kind:"object",properties:new Map([["params",{kind:"promise",value:hk(e.route_id)}],["searchParams",{kind:"promise",value:{kind:"json"}}]])}]);return u=>{if(!u.node||!tn(l.value(u,c)))return!1;let d=!0,f=m=>{if(!d){m.skip();return}if(m.isCallExpression()){let g=m.get("callee"),p=g.isIdentifier()&&!g.scope.getBinding(g.node.name)&&["String","Number","Boolean","encodeURIComponent","decodeURIComponent"].includes(g.node.name);(!(a(m)||p)||!tn(l.value(m,c)))&&(d=!1)}else m.isMemberExpression()||m.isOptionalMemberExpression()?tn(l.value(m,c))||(d=!1):!Fr(m.node)&&!m.isObjectExpression()&&!m.isObjectProperty()&&!m.isArrayExpression()&&!m.isLogicalExpression()&&!m.isConditionalExpression()&&!m.isBinaryExpression()&&!m.isTSAsExpression()&&!m.isTSSatisfiesExpression()&&!m.isParenthesizedExpression()&&(d=!1)};return f(u),u.traverse({enter:f}),d}}var A0=typeof ng=="function"?ng:ng.default,T0=typeof tg=="function"?tg:tg.default;function Ik(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=Ft(n.get(o.sourceFile));if(i===null||`sha256:${Sk("sha256").update(i).digest("hex")}`!==t.ownerSourceHash)return{complete:!1};let s=Te(o.sourceFile,i);if(!s.ok)return{complete:!1};let a=null;A0(s.module.ast,{JSXElement(W){let Ee=o.callLocator.sourceRange;W.node.loc?.start.line===Ee.startLine&&W.node.loc.start.column===Ee.startColumn&&W.node.loc.end.line===Ee.endLine&&W.node.loc.end.column===Ee.endColumn&&(a=W)}});let l=a,c=l?.getFunctionParent();if(!l||!c?.isFunctionDeclaration()||!c.parentPath.isExportDefaultDeclaration()||!c.get("body").isBlockStatement())return{complete:!1};let u=l.findParent(W=>W.isReturnStatement());if(!u?.isReturnStatement()||u.parentPath!==c.get("body"))return{complete:!1};let d=new Set,f=new Map,m=new Set,g=new Set,p=new Set,h=!1,x=W=>{if(!W||d.has(W))return;if(d.add(W),!W.constant||W.constantViolations.length){h=!0;return}let Ee=W.path;if(Ee.isImportSpecifier()||Ee.isImportDefaultSpecifier()||Ee.isImportNamespaceSpecifier()){let Ce=Ee.parentPath;if(!Ce.isImportDeclaration()){h=!0;return}let Me=f.get(Ce.node)??new Set;Me.add(Ee.node),f.set(Ce.node,Me);return}if(W.kind==="param"){let Ce=c.node.params[0];if(!Ze.isObjectPattern(Ce)){h=!0;return}let Me=Ce.properties.filter(ot=>Ze.isObjectProperty(ot)&&!ot.computed&&Ze.isIdentifier(ot.value,{name:W.identifier.name})),bt=Me[0];if(Me.length!==1||!Ze.isObjectProperty(bt)){h=!0;return}let Ie=Ze.isIdentifier(bt.key)?bt.key.name:Ze.isStringLiteral(bt.key)?bt.key.value:"";if(!["params","searchParams"].includes(Ie)){h=!0;return}p.add(Ie);return}let xe=Ee.getStatementParent();if(!xe||xe.node===c.node){h=!0;return}if(Ee.isVariableDeclarator()){if(!xe.isVariableDeclaration({kind:"const"})||xe.node.declarations.length!==1){h=!0;return}}else if(!Ee.isFunctionDeclaration()&&!Ee.isTSTypeAliasDeclaration()&&!Ee.isTSInterfaceDeclaration()){h=!0;return}if(xe.parentPath===c.get("body"))g.add(xe.node);else if(xe.parentPath.isProgram())m.add(xe.node);else if(xe.parentPath.isExportNamedDeclaration()&&xe.parentPath.parentPath.isProgram())m.add(xe.node);else{h=!0;return}b(xe)},b=W=>{let Ee=xe=>x(xe.scope.getBinding(xe.node.name));W.isReferencedIdentifier()&&Ee(W),W.traverse({ReferencedIdentifier(xe){Ee(xe)},JSXOpeningElement(xe){Ze.isJSXIdentifier(xe.node.name)&&!/^[a-z]/u.test(xe.node.name.name)&&x(xe.scope.getBinding(xe.node.name.name))}})};b(l);let E=c.get("body").get("body").filter(W=>(W.node.start??1/0)<(u.node.start??-1)),S=Ek({module:s.module,owner:c,files:n,trusted_host_file_hashes:e.trusted_host_file_hashes,route_id:e.target.composition.routeId}),v=new Set,A=(W,Ee)=>{let xe=Ee.path.parentPath;if(!Ee.path.isImportSpecifier()||!Ze.isIdentifier(Ee.path.node.imported,{name:"cms"})||!xe?.isImportDeclaration())return!1;let Ce=At(o.sourceFile,xe.node.source.value,n);if(!Ce||!/^(?:src\/)?lib\/cms\/index\.ts$/u.test(Ce))return!1;let Me=W;for(;Me.parentPath?.isMemberExpression()&&Me.parentPath.node.object===Me.node&&!Me.parentPath.node.computed;)Me=Me.parentPath;let bt=Me.parentPath;return!!(bt?.isCallExpression()&&bt.node.callee===Me.node&&Dr(bt.node,{file:o.sourceFile,imports:new Map([[Ee.identifier.name,{source:Ce,importedName:"cms"}]])}))},I=!0;for(;I&&!h;){I=!1;for(let W of E){if(g.has(W.node))continue;let Ee=!1;if(W.traverse({ReferencedIdentifier(Ce){let Me=Ce.scope.getBinding(Ce.node.name);Me&&(d.has(Me)||v.has(Me))&&!A(Ce,Me)&&(Ee=!0)}}),!Ee)continue;if(W.isVariableDeclaration({kind:"const"})&&W.node.declarations.length===1){let Ce=W.get("declarations")[0];if(Ce.get("id").isIdentifier()&&S(Ce.get("init"))){let Me=Ce.node.id.name,bt=W.scope.getBinding(Me);bt&&!v.has(bt)&&(v.add(bt),I=!0);continue}}let xe=!1;if(W.traverse({Function(Ce){Ce.skip()},ReturnStatement(Ce){Ce.node.argument&&(xe=!0)}}),xe){h=!0;break}g.add(W.node),b(W);for(let Ce of Object.keys(Ze.getBindingIdentifiers(W.node)))x(W.scope.getBinding(Ce));I=!0}}if(h||!d.size)return{complete:!1};let _=Sk("sha256").update(JSON.stringify([t.sourceHash,t.ownerSourceHash,o.callLocator.sourceRange])).digest("hex"),k=`components/site/portable/${_.slice(0,24)}/page.tsx`;if(n.has(k))return{complete:!1};let T=[];for(let[W,Ee]of f){let xe=Ze.cloneNode(W,!0);if(xe.specifiers=W.specifiers.filter(Ce=>Ee.has(Ce)||Ze.isImportSpecifier(Ce)&&Ce.importKind==="type").map(Ce=>Ze.cloneNode(Ce,!0)),xe.source.value.startsWith(".")){let Ce=At(o.sourceFile,xe.source.value,n);if(!Ce)return{complete:!1};xe.source=Ze.stringLiteral(`@/${Ce.replace(/\.[cm]?[jt]sx?$/u,"")}`)}T.push(xe)}let L=Ze.functionDeclaration(Ze.identifier(`PortableCmsDataEntry_${_.slice(0,8)}`),c.node.params.map(W=>Ze.cloneNode(W,!0)),Ze.blockStatement([...[...g].sort(rg).map(W=>Ze.cloneNode(W,!0)),Ze.returnStatement(Ze.cloneNode(l.node,!0))]));L.async=c.node.async;let $=Ze.program([...T.sort(rg),...[...m].sort(rg).map(W=>Ze.cloneNode(W,!0)),Ze.exportDefaultDeclaration(L)]),J=T0(Ze.file($)).code,z=l.node.loc;if(!z||l.node.start==null||l.node.end==null)return{complete:!1};let Z=[...p].sort().map(W=>({propName:W,value:{kind:W==="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:l.node.start,end_offset:l.node.end,start_line:z.start.line,start_column:z.start.column,end_line:z.end.line,end_column:z.end.column},owner:t.descriptor.owner,call_chain:[],strategy:"extract-jsx",entry_file:k,entry_export:{kind:"default"},invocation:null},extracted:{complete:!0,entry_file:k,source_files:[{path:k,content:J}],source_mapping:[],invocation_bindings:Z,selected_root_ref:t.root.rootRef}}}function rg(e,t){return(e.start??0)-(t.start??0)}import og from"@babel/traverse";import*as nt from"@babel/types";import{createHash as vk}from"node:crypto";var kk=typeof og=="function"?og:og.default,w0=/^[a-z0-9][a-z0-9_-]{0,123}$/u;function _k(e){let t=vr({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=Ft(e.files.get(i.path)),a=s===null?null:Te(i.path,s);a?.ok&&kk(a.module.ast,{ImportDeclaration(l){if(l.node.importKind==="type")return;let c=At(i.path,l.node.source.value,e.files);if(c)for(let u of l.node.specifiers){if(nt.isImportSpecifier(u)&&u.importKind==="type"||!l.scope.getBinding(u.local.name)?.referencePaths.length)continue;let d=o.get(c)??new Set;d.add(nt.isImportDefaultSpecifier(u)?"default":nt.isImportSpecifier(u)?nt.isIdentifier(u.imported)?u.imported.name:u.imported.value:"*"),o.set(c,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=Ft(e.files.get(i.path));if(s===null)continue;let a=Te(i.path,s);if(!a.ok){r.push({code:"CMS_BINDING_SOURCE_INVALID",source_path:i.path,message:a.diagnostic.message});continue}let l=new Map;for(let c of a.module.ast.program.body)if((nt.isExportNamedDeclaration(c)||nt.isExportAllDeclaration(c))&&c.source&&c.exportKind!=="type"){let u=At(i.path,c.source.value,e.files);u&&ig(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 c of a.module.ast.program.body){if(!nt.isImportDeclaration(c)||c.importKind==="type")continue;let u=At(i.path,c.source.value,e.files);if(u)for(let d of c.specifiers)u&&ig(u)&&!nt.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."}),!(!nt.isImportSpecifier(d)||d.importKind==="type")&&l.set(d.local.name,{source:u,importedName:nt.isIdentifier(d.imported)?d.imported.name:d.imported.value})}kk(a.module.ast,{FunctionDeclaration(c){let u=c.parentPath.isExportDefaultDeclaration()?"default":c.parentPath.isExportNamedDeclaration()?c.node.id?.name:void 0;u&&!o.get(i.path)?.has(u)&&!o.get(i.path)?.has("*")&&(!c.node.id||!c.scope.getBinding(c.node.id.name)?.referencePaths.some(d=>!d.isExportDeclaration()))&&c.skip()},ReferencedIdentifier(c){let u=l.get(c.node.name);if(!u||!ig(u.source)||!c.scope.getBinding(c.node.name)?.path.isImportSpecifier()||!["cms","collections","cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(u.importedName))return;let f=c;for(;f.parentPath?.isMemberExpression()&&f.parentPath.node.object===f.node;)f=f.parentPath;if(!nt.isExpression(f.node))return;let m=Dr(nt.callExpression(f.node,[]),{file:i.path,imports:l}),g=u.importedName==="cms"&&f.isMemberExpression()&&!f.node.computed&&f.get("object").isMemberExpression()&&nt.isMemberExpression(f.node.object)&&!f.node.object.computed&&nt.isIdentifier(f.node.object.object,{name:c.node.name})&&nt.isIdentifier(f.node.object.property,{name:"field"});(!m||!sg(f,new Set))&&!g&&r.push({code:"CMS_BINDING_UNSUPPORTED",source_path:i.path,message:"The CMS request facade is used outside a recognized application request.",...c.node.loc?{call_site:{line:c.node.loc.start.line,column:c.node.loc.start.column}}:{}})},CallExpression(c){let u=c.get("callee"),d=new Set;for(;u.isIdentifier()&&!l.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(!nt.isExpression(u.node))return;let f=u;for(;f.isMemberExpression()&&!f.node.computed;)f=f.get("object");if(f.isIdentifier()&&["cms","collections"].includes(l.get(f.node.name)?.importedName??"")){let S=f.scope.getBinding(f.node.name);if(!S?.path.isImportSpecifier())return;if(yr(a.module.ast,f.node.name)||!Ck(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 m=Dr(nt.callExpression(u.node,[]),{file:i.path,imports:l});if(!m)return;if(m.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 g=m.operation;if(g==="getByUrlStrict"&&e.allow_build_sample&&e.on_build_only_value){let S=c.get("arguments")[1];if(S?.isObjectExpression()){let v=S.get("properties").find(I=>I.isObjectProperty()&&!I.node.computed&&(nt.isIdentifier(I.node.key,{name:"buildSample"})||nt.isStringLiteral(I.node.key,{value:"buildSample"}))),A=v?.isObjectProperty()?v.get("value"):void 0;if(A?.isIdentifier()){let I=A.scope.getBinding(A.node.name);A=I?.constant&&I.referencePaths.length===1&&I.path.isVariableDeclarator()?I.path.get("init"):void 0}for(;A?.isTSAsExpression()||A?.isTSSatisfiesExpression();)A=A.get("expression");A?.isObjectExpression()&&A.node.start!=null&&A.node.end!=null&&e.on_build_only_value({file_path:i.path,start:A.node.start,end:A.node.end,source_hash:`sha256:${vk("sha256").update(s).digest("hex")}`})}}let p=c.get("arguments")[0];if(p?.isObjectExpression()&&g.startsWith("cmsFetch")){let S=p.get("properties").find(v=>v.isObjectProperty()&&!v.node.computed&&(nt.isIdentifier(v.node.key,{name:"path"})||nt.isStringLiteral(v.node.key,{value:"path"})));p=S?.isObjectProperty()?S.get("value"):void 0}let h=g.startsWith("getByUrl")||g.startsWith("cmsFetch"),x=p?Hi(p,h,new Set):null,b=x&&h?Dl(x):x;if(!b||!w0.test(b)){r.push({code:"CMS_BINDING_UNRESOLVED",source_path:i.path,message:"The CMS application identity cannot be determined from its request binding.",...c.node.loc?{call_site:{line:c.node.loc.start.line,column:c.node.loc.start.column}}:{}});return}h&&!e.confirmed_slugs?.has(b)&&r.push({code:"CMS_URL_COLLECTION_UNPROVEN",source_path:i.path,message:"The CMS request namespace requires a matching site-authorized application schema."});let E=n.get(b)??[];E.push({source_path:i.path,operation:g,binding:"trusted-cms",call_site:{line:c.node.loc?.start.line??1,column:c.node.loc?.start.column??0}}),n.set(b,E)},JSXOpeningElement(c){if(!e.on_host_call||!nt.isJSXIdentifier(c.node.name)||c.node.start==null||c.node.end==null)return;let u=l.get(c.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:c.node.start,end:c.node.end,source_hash:`sha256:${vk("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 ig(e){return/^(?:src\/)?lib\/cms(?:\/index)?\.[cm]?[jt]s$/u.test(e)||/^(?:src\/)?lib\/cms\/(?:collections|client)\.[cm]?[jt]s$/u.test(e)}function sg(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 sg(r,n);if(r?.isVariableDeclarator()&&r.node.init===e.node&&nt.isIdentifier(r.node.id)){let o=r.scope.getBinding(r.node.id.name);return!!o?.constant&&o.referencePaths.length>0&&o.referencePaths.every(i=>sg(i,n))}return!1}function Ck(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&&nt.isIdentifier(o.node.id)){let i=o.scope.getBinding(o.node.id.name);return!!i?.constant&&Ck(i,n)}return!1})}function Hi(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 Hi(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 Hi(i,t,r)}return null}if(e.isBinaryExpression({operator:"+"})){let o=Hi(e.get("left"),t,r),i=Hi(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 l=Hi(a,t,r);if(l===null&&!t)return null;o+=(l??":record")+(e.node.quasis[s+1]?.value.cooked??"")}return o}return null}import{createHash as i_}from"node:crypto";import Sg from"node:path";import Ig from"@babel/traverse";import*as ut from"@babel/types";import{GeneratedSiteCapabilitiesSchema as L$,SiteEditSourcePathSchema as F$}from"@vcp-dev/contracts";import{parse as xg}from"@babel/parser";import*as oe from"@babel/types";import{PortableCollectionRecipeFactsSchema as h$}from"@vcp-dev/contracts";import{parse as bo}from"@babel/parser";import ag from"@babel/traverse";import*as D from"@babel/types";import{createHash as O0}from"node:crypto";import{GeneratedSiteCapabilitiesSchema as L0,generateDetailBreadcrumb as F0,ResolvedFieldSchema as D0}from"@vcp-dev/contracts";import*as Rt from"@babel/types";function Rk(e){if(!Rt.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(!Rt.isObjectPattern(o)||o.properties.length!==1||!Rt.isObjectProperty(o.properties[0])||o.properties[0].computed||!Rt.isIdentifier(o.properties[0].key,{name:"children"})||!Rt.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=Rt.isBlockStatement(s)?s.body.length===1&&Rt.isReturnStatement(s.body[0])?s.body[0].argument:null:s,l=new Set(["article","aside","div","footer","header","li","main","nav","ol","p","section","span","ul"]),c=(u,d)=>{if(!u||d>32)return!1;if(Rt.isJSXExpressionContainer(u))return u.expression===i.referencePaths[0].node;if(!Rt.isJSXElement(u)&&!Rt.isJSXFragment(u)||Rt.isJSXElement(u)&&(!Rt.isJSXIdentifier(u.openingElement.name)||!l.has(u.openingElement.name.name)||u.openingElement.attributes.length>0))return!1;let f=u.children.filter(m=>!Rt.isJSXText(m)||m.value.trim()!=="");return f.length===1&&c(f[0],d+1)};return c(a,0)}var _a=typeof ag=="function"?ag:ag.default;function dg(e){return Tk(e,!1)}function M0(e){if(e.list_container_file.length===0||e.list_container_file.length>1024||/[\\%?#:\s\u0000-\u001f\u007f]/u.test(e.list_container_file)||e.list_container_file.split("/").some(o=>!o||o.startsWith(".")||o==="node_modules"))return{complete:!1,relation:null,errors:[{code:"RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",path:"<list-container>",message:"The existing list container path is unsafe."}]};let t=Tk({files:e.files,list_entry_file:e.list_container_file,selected_component_source:`@/${e.list_container_file}`,detail_prefix:e.detail_prefix},!0);if(!t.relation)return{...t,relation:null};let{list_entry_file:n,...r}=t.relation;return{...t,relation:r}}function Tk(e,t){let n=mg(e.files),r=(m,g,p)=>({complete:!1,relation:null,errors:[{code:m,path:g,message:p}]}),o=Ok(e,n,t);if(!o.complete)return{complete:!1,relation:null,errors:o.errors};if(!o.consumer)return{complete:!0,relation:null,errors:[]};let{slug:i,consumer:s}=o,a=[...n.keys()].filter(Vk),l=a.find(m=>typeof n.get(m)!="string");if(l)return r("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",l,"A candidate detail route is not valid UTF-8 source, so uniqueness cannot be proven.");let c=a.flatMap(m=>{let g=n.get(m);if(typeof g!="string")return[];let p=ti(m,g,i,"getByUrlStrict",n,e.detail_prefix??`/${i}`);return p&&Pu(p.ast,e.detail_prefix??`/${i}`)!==null?[p]:[]});if(c.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=c[0];if(!n$(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=dr(u.source,{filePath:u.path,exportName:"default"}).components.flatMap(m=>{let g=gn(u.path,m.source,n),p=g?n.get(g):void 0;return!g||typeof p!="string"||!Mk(p,m.export_name)||!Ru(p,u.adapter_source,u.interface_name)?[]:[{path:g,export_name:m.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 wk(e){let t=Ok(e,mg(e.files));return t.complete&&t.consumer!==null}function Ok(e,t,n=!1){let r=(l,c)=>({complete:!1,errors:[{code:"RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",path:l,message:c}]}),o=gn(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(!W0(i,o,"listStrict"))return{complete:!0,slug:null,consumer:null};if(!n&&!Lk(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=H0(i,o),a=s?ti(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 Lk(e,t,n,r=!1,o="default"){let i=Ft(n.get(e));if(i===null)return!1;let s=Te(e,i);if(!s.ok)return!1;let a=En({module:s.module,exportName:o,allowNonRenderingGuards:r});if(!a.ok||a.metadataOnly)return!1;let l=dr(i,{filePath:e,exportName:o}),c=new Set(l.rendered_component_openings.filter(d=>!d.static_render_blockers?.length).map(d=>d.start_offset)),u=d=>{let f=0,m=g=>{if(g.isJSXElement()){let p=g.get("openingElement"),h=p.node.name;if(!D.isJSXIdentifier(h))return;if(!/^[a-z]/u.test(h.name)){let x=p.scope.getBinding(h.name),b=x?.path.parentPath;if(x?.constant&&b?.isImportDeclaration()&&b.node.importKind!=="type"&&(x.path.isImportDefaultSpecifier()||x.path.isImportSpecifier()&&x.path.node.importKind!=="type"&&D.isIdentifier(x.path.node.imported,{name:"default"}))&&typeof p.node.start=="number"&&c.has(p.node.start)&&gn(e,b.node.source.value,n)===t){f++;return}if(!Rk(p))return}if(B0(p.node))return}for(let p of g.get("children"))if(p.isJSXElement()||p.isJSXFragment())m(p);else if(p.isJSXExpressionContainer()){let h=p.get("expression");(h.isJSXElement()||h.isJSXFragment())&&m(h)}};for(let g of d)m(g);return f};return a.returnAlternatives?a.returnAlternatives.every(d=>u([d])===1):u(a.roots)===1}function B0(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 fg(e){let t=mg(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 E of e.source_closure.nodes)E.kind==="source"&&typeof t.get(E.path)!="string"&&n.push({code:"RELATED_SOURCE_CLOSURE_INCOMPLETE",path:E.path,message:"A selected source is missing or is not valid UTF-8 text."});cg(t,e.collection.list_entry_file,"RELATED_LIST_ENTRY_MISSING",n),cg(t,e.collection.detail_entry_file,"RELATED_DETAIL_ENTRY_MISSING",n),cg(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 l=e.list_route_required??!i,c=l&&Uk(e.collection.list_entry_file);l&&!c&&n.push({code:"RELATED_LIST_ROUTE_UNPROVEN",path:e.collection.list_entry_file,message:"The collection caller is not a Next App Router page."}),c&&lg(o,{path:e.collection.list_entry_file,kind:"route",requirementKey:e.collection.requirement_key}),Vk(e.collection.detail_entry_file)?lg(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=vr({entry_files:[e.collection.detail_entry_file],files:t}),d=new Set;if(i)if(!L0.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 E of u.nodes){if(E.kind==="external"||Vi({node:E,host_capabilities:e.host_capabilities}).ownership!=="host-public"&&!r$(E.path))continue;d.add(E.path);let v=s.get(E.path),A=v===void 0?null:`sha256:${O0("sha256").update(v).digest("hex")}`;(!A||e.trusted_host_file_hashes?.get(E.path)!==A)&&n.push({code:"RELATED_HOST_IMPLEMENTATION_UNPROVEN",path:E.path,message:"A related host source requires trusted matching Snapshot provenance."})}for(let E of u.nodes)E.kind==="source"&&typeof t.get(E.path)!="string"&&n.push({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:E.path,message:"A detail source is missing or is not valid UTF-8 text."});u.complete||n.push(...u.errors.map(E=>({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:E.path,message:E.message})));let f=u.nodes.find(E=>E.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 m=i?$0(e.collection,t,s):null,g=e.trusted_schema===void 0?null:U0(e,t,n,e.trusted_schema),p=i&&g&&e.trusted_schema?j0(e.collection,g,e.trusted_schema,t,s):null;for(let E of u.nodes)if(E.kind!=="external"&&E.path!==e.collection.detail_entry_file&&E.path!==e.collection.detail_view_file&&!d.has(E.path)&&!(!c&&E.path===e.collection.list_entry_file)){if(t$(E.path,e.collection)){if(i&&E.path!==m&&E.path!==p){n.push({code:"RELATED_MANAGED_SOURCE_UNPROVEN",path:E.path,message:"A related generated source cannot be omitted based on its pathname alone."});continue}lg(o,{path:E.path,kind:E.path.includes("/page.")?"route":"adapter",requirementKey:e.collection.requirement_key});continue}o$(E.path,e.collection.detail_view_file,e.collection.slug)&&r.push({path:E.path,export:{kind:"default"},purpose:"i18n-companion"})}let h=t.get(e.collection.detail_view_file);typeof h=="string"&&Q0(h,e.collection.detail_view_file,u.nodes,t,r,d),e.page_template&&(a=e$(e.page_template,t,n));let x=a$(r).map((E,S)=>({key:l$(E,S),pathTemplate:E.path,export:E.export,purpose:E.purpose,requirementKey:e.collection.requirement_key})),b=u$(n).sort(d$);return{complete:b.length===0,entries:x.sort((E,S)=>E.pathTemplate.localeCompare(S.pathTemplate)||E.purpose.localeCompare(S.purpose)||E.key.localeCompare(S.key)),managed_requirements:o.sort(c$),thin_entry_plan:a,collection_wiring:g,errors:b}}function j0(e,t,n,r,o){let i=D0.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,l=new Set(["id","url","seo"]);for(let b of s){if(!/^[A-Za-z_$][A-Za-z0-9_$]{0,99}$/u.test(b.name)||["__proto__","prototype","constructor"].includes(b.name)||a.has(b.name))return null;if(a.add(b.name),b.front_display==="forbidden")continue;let E=["id","url","seo"].includes(b.name)?`${b.name}_field`:b.name;if(l.has(E))return null;l.add(E)}let c=new Set(t.force_multi_media??[]);for(let b of c){let E=s.find(S=>S.name===b);if(!E||E.front_display==="forbidden"||E.value_shape!=="media_list"&&!["Image","Avatar","Video","File","Audio"].includes(E.cms_type))return null}let u=Ft(r.get(t.list_container_file)),d=Ft(r.get(e.detail_entry_file)),f=pg(e.detail_entry_file);if(u===null||d===null||!f)return null;let m=ti(t.list_container_file,u,e.slug,"listStrict",r),g=ti(e.detail_entry_file,d,e.slug,"getByUrlStrict",r,f),p=`lib/cms/generated/${e.slug}.ts`;if(!m||!g||m.adapter_source!==g.adapter_source||gn(m.path,m.adapter_source,r)!==p||gn(g.path,g.adapter_source,r)!==p)return null;let h=o.get(p);if(h===void 0)return null;let x=Bm(e.slug,s,{forceMultiMedia:c});return typeof h=="string"?h===x?p:null:Buffer.from(h).equals(Buffer.from(x))?p:null}function $0(e,t,n){let r=t.get(e.detail_entry_file),o=pg(e.detail_entry_file);if(typeof r!="string"||!o)return null;let i=ti(e.detail_entry_file,r,e.slug,"getByUrlStrict",t,o);if(!i)return null;let s=Pu(i.ast,o),a=Bk(i,t,s);if(!s||!a||a==="unproven")return null;let l=`components/site/generated/${e.slug}-breadcrumb.tsx`;if(!Lk(i.path,l,t,!0))return null;let c=n.get(l);return c===void 0?null:[void 0,{variant:"floating",shape:"bar"},{variant:"floating",shape:"island"}].some(d=>{let f=F0({slug:e.slug,detailPrefix:s,...a,headerShell:d});return typeof c=="string"?c===f:Buffer.from(c).equals(Buffer.from(f))})?l:null}function U0(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 A=t.get(v.path);if(typeof A!="string")return[];let I=ti(v.path,A,e.collection.slug,"listStrict",t);return I?[I]:[]});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,l=a?Pk(a,t,v=>v!==e.collection.detail_view_file):null;l?a&&!Ru(t.get(l.source_path),a.adapter_source,a.interface_name)&&n.push({code:"RELATED_COLLECTION_LIST_VIEW_UNPROVEN",path:l.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 c=t.get(e.collection.detail_entry_file),u=pg(e.collection.detail_entry_file),d=typeof c=="string"&&u?ti(e.collection.detail_entry_file,c,e.collection.slug,"getByUrlStrict",t,u):null,f=d?Pk(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."}):Ru(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 m=new Set(i.map(v=>v.name)),g=a?gn(a.path,a.adapter_source,t):null,p=g?t.get(g):null,h=[...e.required_fields??i.filter(v=>v.required).map(v=>v.name)].sort(ug),x=[...e.force_multi_media??(typeof p=="string"?jk(p):[])].sort(ug);for(let v of[...h,...x])m.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&&x.length)for(let v of x)(typeof p!="string"||!q0(p,v))&&n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:g??a.adapter_source,message:`The generated adapter does not prove multi-media handling for ${v}.`});let b=d&&u?Pu(d.ast,u):null;b||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:e.collection.detail_entry_file,message:"The detail route does not prove a literal getByUrlStrict prefix."});let E=d?Z0(d.ast):null;E||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:e.collection.detail_entry_file,message:"The generated detail route must expose a literal PAGE_SEO title."});let S=d?Bk(d,t,b):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||!l||!d||!f||!b?null:{source_slug:e.collection.slug,detail_prefix:b,schema:i,schema_evidence_path:r.evidence_path,list_container_file:a.path,list_view:{...l,interface_name:a.interface_name},detail_view:{...f,interface_name:d.interface_name},...E?{title:E}:{},...S&&S!=="unproven"?{breadcrumb:S}:{},...h.length>0?{required_fields:h}:{},...x.length>0?{force_multi_media:x}:{}}}function ti(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)&&ni(u.callee,r));if(!z0(s,e,o,r)||r==="listStrict"&&(a.length!==1||!D.isStringLiteral(a[0]?.arguments[0],{value:n}))||r==="getByUrlStrict"&&(a.length===0||Pu(s,i)===null))return null;let c=s.program.body.flatMap(u=>D.isImportDeclaration(u)?u.specifiers.flatMap(d=>{if(!D.isImportSpecifier(d))return[];let f=D.isIdentifier(d.imported)?d.imported.name:d.imported.value,m=/^to([A-Za-z_$][A-Za-z0-9_$]*View)$/u.exec(f);return m?[{source:u.source.value,local_name:d.local.name,interface_name:m[1]}]:[]}):[]).filter(u=>xo(s,d=>D.isIdentifier(d,{name:u.local_name})).length>1);return c.length!==1||!V0(s,e,o,c[0],r,n)?null:{path:e,source:t,ast:s,adapter_source:c[0].source,interface_name:c[0].interface_name}}function V0(e,t,n,r,o,i){let s=!1;return _a(e,{JSXOpeningElement(a){let l=a.getFunctionParent();if(!l?.isFunctionDeclaration()||!l.parentPath.isExportDefaultDeclaration()||!D.isJSXIdentifier(a.node.name)||a.node.attributes.some(x=>D.isJSXSpreadAttribute(x)))return;let c=a.parentPath;for(;c&&!c.isReturnStatement()&&!c.isFunction();){if(c.isVariableDeclarator()||c.isJSXAttribute()||c.isConditionalExpression()||c.isLogicalExpression()||c.isCallExpression()||c.isJSXElement()&&c.node!==a.parentPath.node&&(!D.isJSXIdentifier(c.node.openingElement.name)||!/^[a-z]/u.test(c.node.openingElement.name.name)))return;c=c.parentPath}if(!c?.isReturnStatement()||c.getFunctionParent()!==l||c.parentPath!==l.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 m=gn(t,f.node.source.value,n);if(!m||!Ru(n.get(m),r.source,r.interface_name))return;let g=a.get("attributes").filter(x=>x.isJSXAttribute()&&D.isJSXIdentifier(x.node.name,{name:o==="listStrict"?"records":"record"}));if(g.length!==1||!g[0].isJSXAttribute())return;let p=g[0].get("value");if(!p.isJSXExpressionContainer())return;let h={opening:a,attribute:o==="listStrict"?"records":"record",file:t,files:n};(o==="listStrict"?Fk(p.get("expression"),l,r,i,h,new Set):Dk(p.get("expression"),l,r,h,new Set))&&(s=!0)}}),s}function Fk(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 g=e.scope.getBinding(e.node.name);return!g?.constant||!g.path.isVariableDeclarator()||g.path.getFunctionParent()!==t||!g.path.parentPath.isVariableDeclaration({kind:"const"})||ka(g.referencePaths,n,o)?!1:Fk(g.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||!Cu(a,n))return!1;let l=s.get("object");if(l.isConditionalExpression()){let g=l.get("consequent"),p=l.get("alternate"),h=x=>x.isArrayExpression()&&x.node.elements.length===0;if(h(g))l=p;else if(h(p))l=g;else return!1}if(!l.isMemberExpression()||l.node.computed||!D.isIdentifier(l.node.property,{name:"items"}))return!1;let c=l.get("object");if(!c.isMemberExpression()||c.node.computed||!D.isIdentifier(c.node.property,{name:"data"}))return!1;let u=c.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"})||ka(d.referencePaths,n,null))return!1;let f=d.path.get("init");if(!f.isAwaitExpression())return!1;let m=f.get("argument");return m.isCallExpression()&&ni(m.node.callee,"listStrict")&&D.isStringLiteral(m.node.arguments[0],{value:r})}function Dk(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"})||ka(d.referencePaths,n,r)?!1:Dk(d.path.get("init"),t,n,r,o)}if(!e.isCallExpression()||e.node.arguments.length!==1)return!1;let i=e.get("callee");if(!Cu(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 l=a.scope.getBinding(a.node.name);if(!l?.constant||!l.path.isVariableDeclarator()||l.path.getFunctionParent()!==t||!l.path.parentPath.isVariableDeclaration({kind:"const"})||ka(l.referencePaths,n,null))return!1;let c=l.path.get("init");if(!c.isAwaitExpression())return!1;let u=c.get("argument");return u.isCallExpression()&&ni(u.node.callee,"getByUrlStrict")}function Cu(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 ka(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),ka(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 l=s.get("callee"),c=s.get("arguments")[0];return!(l.isMemberExpression()&&!l.node.computed&&D.isIdentifier(l.node.property,{name:"map"})&&c&&Cu(c,t))}let a=s.get("callee");return!(i.isMemberExpression()&&!i.node.computed&&D.isIdentifier(i.node.property,{name:"data"})&&Cu(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()&&K0(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 K0(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=gn(r.file,s.node.source.value,r.files),l=gn(r.file,n.source,r.files),c=a?r.files.get(a):void 0,u=l?r.files.get(l):void 0;return typeof c!="string"||typeof u!="string"?!1:J0(c,a)&&X0(u,l,`to${n.interface_name}`,t)}function J0(e,t){let n=Te(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 _a(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 X0(e,t,n,r){let o=Te(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(_a(o.module.ast,{Program(d){let f=d.scope.getBinding(n);a=!!(f?.constant&&f.path.node===s),d.stop()}}),!a)return!1;let l=xo(s.body,d=>D.isReturnStatement(d)),c=s.body.body.at(-1);if(l.length!==1||!D.isReturnStatement(c)||c!==l[0]||!D.isObjectExpression(c.argument))return!1;let u=new Set;for(let d of c.argument.properties){if(!D.isObjectProperty(d)||d.computed||!(D.isIdentifier(d.key)||D.isStringLiteral(d.key)))return!1;let f=D.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 z0(e,t,n,r){let o=0,i=yr(e,"cms");for(let s of e.program.body){if(!D.isImportDeclaration(s)||s.importKind==="type")continue;let a=gn(t,s.source.value,n);!a||!/^(?:src\/)?lib\/cms(?:\/index|\/collections)?\.[cm]?[jt]s$/u.test(a)||s.specifiers.some(l=>{if(D.isImportSpecifier(l)&&l.importKind==="type")return!1;if(!D.isImportSpecifier(l))return!0;let c=D.isIdentifier(l.imported)?l.imported.name:l.imported.value;return c==="collections"||c==="cms"&&l.local.name!=="cms"})&&(i=!0)}return _a(e,{CallExpression(s){if(!ni(s.node.callee,r))return;o+=1;let a=s.scope.getBinding("cms"),l=a?.path,c=l?.parentPath;if(!a?.constant||!l?.isImportSpecifier()||l.node.importKind==="type"||!D.isIdentifier(l.node.imported,{name:"cms"})||!c?.isImportDeclaration()||c.node.importKind==="type"){i=!0;return}let u=gn(t,c.node.source.value,n);(!u||!/^(?:src\/)?lib\/cms(?:\/index)?\.[cm]?[jt]s$/u.test(u)||a.referencePaths.some(d=>{let f=d.parentPath,m=f?.parentPath,g=m?.parentPath;return!(f?.isMemberExpression()&&f.node.object===d.node&&!f.node.computed&&D.isIdentifier(f.node.property,{name:"collections"})&&m?.isMemberExpression()&&m.node.object===f.node&&!m.node.computed&&D.isIdentifier(m.node.property)&&g?.isCallExpression()&&g.node.callee===m.node)}))&&(i=!0)}}),o>0&&!i}function H0(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)&&ni(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 W0(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)&&ni(o.callee,n)).length>0}function Pk(e,t,n){let r=dr(e.source,{filePath:e.path,exportName:"default"});if(r.diagnostics.length>0)return null;let o=r.components.flatMap(i=>{let s=gn(e.path,i.source,t),a=s?t.get(s):null;return!s||!n(s)||typeof a!="string"||!Mk(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 Mk(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 Ru(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 ni(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 Pu(e,t){let n=[];return _a(e,{CallExpression(r){ni(r.node.callee,"getByUrlStrict")&&n.push(G0(r.node.arguments[0],o=>Y0(r,o)))}}),n.length===0?null:n.every(r=>r===t)?t:null}function G0(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 Y0(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&&Nu(a.key)==="slug"&&D.isIdentifier(a.value,{name:t}))&&Nk(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)&&Nk(n.path,s.object.argument.name)}function Nk(e,t){let n=e.scope.getBinding(t);if(!n?.constant||n.kind!=="param")return!1;let r=n.path.getFunctionParent();if(!r||!r.isFunctionDeclaration())return!1;let o=r.parentPath;return!o.isExportDefaultDeclaration()&&!(o.isExportNamedDeclaration()&&r.node.id?.name==="generateMetadata")?!1:r.node.params.some(i=>D.isObjectPattern(i)&&i.properties.some(s=>D.isObjectProperty(s)&&!s.computed&&Nu(s.key)==="params"&&D.isIdentifier(s.value,{name:t})))}function Z0(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=$k(n.init);if(!D.isObjectExpression(r))return null;let o=r.properties.find(i=>D.isObjectProperty(i)&&!i.computed&&Nu(i.key)==="title");return o&&D.isStringLiteral(o.value)?o.value.value:null}return null}function Bk(e,t,n){let o=dr(e.source,{filePath:e.path,exportName:"default"}).components.filter(l=>/(?:^|\/)components\/site\/generated\/[A-Za-z0-9_-]+-breadcrumb$/u.test(l.source));if(o.length===0)return null;if(o.length!==1||!n)return"unproven";let i=gn(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 l of xo(a,c=>D.isArrayExpression(c))){let c=l.elements.flatMap(f=>{if(!D.isObjectExpression(f))return[];let m=new Map;for(let g of f.properties){if(!D.isObjectProperty(g)||g.computed)continue;let p=Nu(g.key);p&&D.isStringLiteral(g.value)&&m.set(p,g.value.value)}return m.has("name")&&m.has("href")?[m]:[]}),u=c.find(f=>f.get("href")==="/"),d=c.find(f=>f.get("href")===n);if(u&&d)return{homeLabel:u.get("name"),collectionLabel:d.get("name")}}return"unproven"}function jk(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(ug)}function q0(e,t){return jk(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)Ak(s)&&r(s);else Ak(i)&&r(i)};return r(e),n}function Ak(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function $k(e){return e?D.isTSAsExpression(e)||D.isTSTypeAssertion(e)||D.isTSNonNullExpression(e)?$k(e.expression):e:null}function Nu(e){return D.isIdentifier(e)?e.name:D.isStringLiteral(e)?e.value:null}function ug(e,t){return e.localeCompare(t)}function Q0(e,t,n,r,o,i){let s=dr(e,{filePath:t,exportName:"default"});for(let a of s.components){let l=gn(t,a.source,r);if(!l||i.has(l))continue;let c=n.find(d=>d.path===l),u=r.get(l);!c||c.kind==="external"||typeof u!="string"||i$(u)&&o.push({path:l,export:a.export_name==="default"?{kind:"default"}:{kind:"named",name:a.export_name},purpose:"client-importer"})}}function e$(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=dr(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 cg(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 t$(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 Uk(e){return/^(?:src\/)?app\/(?:[^/.][^/]*\/)*page\.[cm]?[jt]sx?$/u.test(e)}function Vk(e){return Uk(e)&&/\/\[slug\]\/page\.[cm]?[jt]sx?$/u.test(e)}function n$(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 pg(e){let t=/^(?:src\/)?app\/([A-Za-z0-9_-]+)\/\[slug\]\/page\.[cm]?[jt]sx?$/u.exec(e);return t?`/${t[1]}`:null}function r$(e){return/^(?:src\/)?lib\/cms(?:\.[cm]?[jt]sx?$|\/(?!generated\/))/u.test(e)}function o$(e,t,n){let r=e.replace(/\\/g,"/"),o=t.replace(/\.(?:tsx?|jsx?)$/u,""),i=Kk(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 i$(e){try{return bo(e,{sourceType:"module",plugins:["jsx","typescript"]}).program.directives.some(n=>n.value.value==="use client")}catch{return!1}}function gn(e,t,n){if(!kt(t))return null;let r=t.startsWith("@/")?t.slice(2):s$(`${Kk(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 Kk(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function s$(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."?t.length>0&&t.at(-1)!==".."?t.pop():t.push(".."):t.push(n));return t.join("/")}function mg(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=Ft(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 lg(e,t){e.some(r=>r.path===t.path&&r.kind===t.kind)||e.push(t)}function c$(e,t){return e.path.localeCompare(t.path)||e.kind.localeCompare(t.kind)||e.requirementKey.localeCompare(t.requirementKey)}function l$(e,t){return`${`related.${e.purpose}.${e.path.replace(/[^A-Za-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}`.slice(0,112)}.${t}`}function u$(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function d$(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}import{parse as Wk}from"@babel/parser";import gg from"@babel/traverse";import*as Le from"@babel/types";var f$=typeof gg=="function"?gg:gg.default,p$=Wk(`
|
|
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],hk=H0.body.body;function Sk(e,t,n){let r;try{r=Ek(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let o=[];z0(r,{ExportDefaultDeclaration(p){let h=p.get("declaration");(h.isFunctionDeclaration()||h.isFunctionExpression()||h.isArrowFunctionExpression())&&o.push(h)}});let i=o.length===1?o[0]:void 0;if(!i||!Re.isBlockStatement(i.node.body))return null;let s=i.node.body.body,a=bk(i.node,p=>Re.isCallExpression(p)&&yk(p,"listStrict",n));if(a.length!==1||a[0].arguments.length!==2)return null;let l=a[0],c=s.findIndex(p=>xk(p,l));if(c<0)return null;let u=l.arguments[1];if(!Re.isObjectExpression(u))return null;let d=new Map;for(let p of u.properties){if(!Re.isObjectProperty(p)||p.computed)return null;let h=Re.isIdentifier(p.key)?p.key.name:Re.isStringLiteral(p.key)?p.key.value:null;if(!h||!["page","pageSize","category"].includes(h)||d.has(h)||!Re.isExpression(p.value))return null;d.set(h,p.value)}let f=d.get("page"),g=d.get("pageSize");if(!f||!Re.isNumericLiteral(g)||!Number.isSafeInteger(g.value)||g.value<1||g.value>100)return null;let m=bk(i.node,p=>Re.isCallExpression(p)&&yk(p,"categories",n));return d.has("category")?!Re.isIdentifier(f,{name:"page"})||!Re.isIdentifier(d.get("category"),{name:"category"})||m.length!==1||m[0].arguments.length!==1||!xk(s[c+1],m[0])||!G0(i,s.slice(0,c))?null:{paginate:!0,limit:g.value}:m.length||!W0(f,s.slice(0,c),i)?null:{paginate:!1,limit:g.value}}function yk(e,t,n){let r=e.callee;return Re.isMemberExpression(r)&&!r.computed&&Re.isIdentifier(r.property,{name:t})&&Re.isMemberExpression(r.object)&&!r.object.computed&&Re.isIdentifier(r.object.property,{name:"collections"})&&Re.isIdentifier(r.object.object,{name:"cms"})&&Re.isStringLiteral(e.arguments[0],{value:n})}function xk(e,t){return!!(Re.isVariableDeclaration(e,{kind:"const"})&&e.declarations.length===1&&Re.isIdentifier(e.declarations[0].id)&&Re.isAwaitExpression(e.declarations[0].init)&&e.declarations[0].init.argument===t)}function W0(e,t,n){if(n.scope.getBinding("searchParams")?.referencePaths.length)return!1;if(Re.isNumericLiteral(e,{value:1}))return t.length===0;if(!Re.isIdentifier(e)||t.length!==1)return!1;let o=t[0];if(!Re.isVariableDeclaration(o,{kind:"const"})||o.declarations.length!==1)return!1;let i=o.declarations[0],s=n.scope.getBinding(e.name);return!!(Re.isIdentifier(i.id,{name:e.name})&&Re.isNumericLiteral(i.init,{value:1})&&s?.identifier===i.id&&s.constant)}function G0(e,t){if(t.length!==hk.length||!t.every((u,d)=>Re.isNodesEquivalent(u,hk[d]))||e.scope.getBinding("Number")||e.scope.getBinding("undefined"))return!1;let n=e.node.params[0];if(!Re.isObjectPattern(n)||n.properties.length!==1||!Re.isObjectProperty(n.properties[0])||n.properties[0].computed||!Re.isIdentifier(n.properties[0].key,{name:"searchParams"})||!Re.isIdentifier(n.properties[0].value,{name:"searchParams"}))return!1;let r=t.map(u=>Re.isVariableDeclaration(u)?u.declarations[0]:void 0),[o,i,s,a]=r;if(!o?.init||!i?.init||!s?.init||!a?.init)return!1;let l=["sp","pageValue","page","category"].map(u=>e.scope.getBinding(u));if(l.some((u,d)=>!u?.constant||u.identifier!==r[d]?.id))return!1;let c=e.scope.getBinding("searchParams");return!(!c?.constant||c.identifier!==n.properties[0].value||!Xm(c.referencePaths,[o.init])||!Xm(l[0].referencePaths,[i.init,a.init])||!Xm(l[1].referencePaths,[s.init]))}function Xm(e,t){return e.every(n=>!!n.findParent(r=>t.includes(r.node)))}function bk(e,t){let n=[],r=o=>{if(!(o!==e&&Re.isFunction(o))){t(o)&&n.push(o);for(let i of Re.VISITOR_KEYS[o.type]??[]){let s=o[i];if(Array.isArray(s))for(let a of s)Re.isNode(a)&&r(a);else Re.isNode(s)&&r(s)}}};return r(e),n}var Z0=new Set(["blockId","block_id","targetBlockId","target_block_id","sourceBlockId","source_block_id"]),q0=new Set(["data-vcp-block-id","data-vcp-edit-key"]),Q0=new Set(["data-vcp-order","sourceOrder","source_order"]);function Pi(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(Qs)}),n;try{n=Hm(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=a$(n),o=Cn(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=[],l=0;if(Zl(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 h=Nk(m.name);if(!h)return;let x=u$(m.name,r);x&&(e.target.local_name&&e.target.local_name!==h||x.source!==e.target.source||x.export_name!==e.target.export_name||s.has(p)&&a.push({node:m,element:f,local:x,context:g,ordinal:l++}))}),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 c=a.map(f=>Rk(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=Pk(c,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:Gm(d).sort(Qs)}}function _k(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(Qs)}),n;try{n=Hm(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(Zl(n,new Set,(a,l)=>{if(!Y.isJSXElement(a))return;let c=a.openingElement;if(typeof c.start!="number"||Nk(c.name)!==e.target.local_name)return;let u=o++;e.call_source_range&&(c.loc?.start.line!==e.call_source_range.start_line||c.loc.start.column!==e.call_source_range.start_column)||r.push({node:c,element:a,context:l,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=>Rk(e,a.node,a.element,{kind:"local",local_name:e.target.local_name},a.context,a.ordinal)),s=Pk(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:Gm(s.errors).sort(Qs)}: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 e$(e){let t;try{t=Hm(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=On({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=Cn(e.source,{filePath:e.file_path,exportName:"default"});if(i.components.length===0)return{invocation:null,errors:[]};let s=i.components.map(a=>Pi({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 t$(e){let t=Pi(e),n=r$(e.files),r=o$(e.file_path,e.target.source,n),o=r?yt(n.get(r)):null,i=r&&typeof o=="string"?Sk(o,r,e.collection.slug):null,s=Um({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],l=[];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:n$(f.code),path:f.path,message:f.message});t.call&&l.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 c=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{l.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})}c&&r!==c.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(c&&i&&a.length===0){let f={source_slug:c.source_slug,list_mode:i.paginate?"page":"embedded",paginate:i.paginate,...i.paginate?{page_size:i.limit}:{top_n:i.limit},detail_prefix:c.detail_prefix,schema:c.schema.map(m=>({...m})),list_view:{...c.list_view},detail_view:{...c.detail_view},...c.title?{title:c.title}:{},...c.breadcrumb?{breadcrumb:{...c.breadcrumb}}:{},...c.required_fields?{required_fields:[...c.required_fields]}:{},...c.force_multi_media?{force_multi_media:[...c.force_multi_media]}:{},list_route_required:i.paginate},g=Y0.safeParse(f);g.success?(u=g.data,l.push({fact:"detail-route",path:e.collection.detail_entry_file,reason:`The rendered detail consumer proves literal prefix ${c.detail_prefix}.`},{fact:"list-view",path:c.list_view.source_path,reason:`The list container renders ${c.list_view.export_name} with ${c.list_view.interface_name}.`},{fact:"detail-view",path:c.detail_view.source_path,reason:`The detail route renders ${c.detail_view.export_name} with ${c.detail_view.interface_name}.`},{fact:"schema",path:c.schema_evidence_path,reason:"The complete CMS schema is supplied by the trusted application projection."})):a.push({code:"COLLECTION_RECIPE_INVALID",path:`collection-recipe:${c.source_slug}`,message:g.error.issues[0]?.message??"Observed collection facts do not satisfy the portable recipe contract."})}let d=Gm(a).sort(Qs);return{...t,complete:d.length===0&&u!==null,errors:d,collection_recipe:u,collection_evidence:l.sort(s$),related_entries:s}}function n$(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 r$(e){return e instanceof Map?e:new Map(Object.entries(e))}function o$(e,t,n){if(!mt(t))return null;let r=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",o=t.startsWith("@/")?t.slice(2):i$(`${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 i$(e){let t=[];for(let n of e.split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return t.join("/")}function s$(e,t){return e.fact.localeCompare(t.fact)||e.path.localeCompare(t.path)}function a$(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 Rk(e,t,n,r,o,i){let s=p$(t),a=[],l=[],c={},u=new Set,d=null,f=null,g=(p,h)=>{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),l.push({propName:p,value:h}),(p==="type"||p==="variant")&&h.kind==="json-literal"&&(c[p]=h.value)};for(let p of t.attributes){if(Y.isJSXSpreadAttribute(p)){let S=eo(p.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[v,P]of Object.entries(S.value)){if(!Ik(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,zm(P))}continue}let h=d$(p.name);if(!h)continue;let x=p.value,E=x&&Y.isJSXExpressionContainer(x)?x.expression:null;if(q0.has(h)){let S=x?Yl(x):{ok:!0,value:!0};!S.ok||typeof S.value!="string"?a.push({code:"INVOCATION_BLOCK_ID_UNRESOLVED",path:`${e.file_path}:${h}`,message:"Portable invocation requires a literal original block identity.",source_range:s}):d=S.value;continue}if(Q0.has(h)){let S=x?Yl(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}:${h}`,message:"Portable invocation requires a literal original order.",source_range:s}):f=S.value;continue}if(!Ik(h)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${h}`,message:`Portable invocation cannot encode prop ${h}.`,source_range:s});continue}if(Z0.has(h)){let S=x?Yl(x):{ok:!0,value:!0};S.ok&&typeof S.value=="string"?d=S.value:E&&vk(E,o)&&a.push({code:"INVOCATION_BLOCK_ID_UNRESOLVED",path:`${e.file_path}:${h}`,message:"A target block identity cannot be supplied by route search params.",source_range:s}),g(h,{kind:"target-block-id"});continue}if(E&&vk(E,o)){g(h,{kind:"route-search-params"});continue}let b=x?Yl(x):{ok:!0,value:!0};if(!b.ok){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${h}`,message:`Portable invocation cannot prove a JSON-literal value for ${h}.`,source_range:s});continue}g(h,zm(b.value))}let m=c$(n);return m.ok?m.value!==void 0&&g("children",zm(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:l,original_block_id:d??e.target.original_block_id??null,original_order:f,semantic_props:c,errors:a}}function Pk(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 Yl(e){return e===null?{ok:!0,value:!0}:Y.isStringLiteral(e)?{ok:!0,value:e.value}:Y.isJSXExpressionContainer(e)?eo(e.expression):{ok:!1}}function eo(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 eo(e.expression);if(Y.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(Y.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(Y.isObjectExpression(e)){let t={};for(let n of e.properties){if(Y.isSpreadElement(n)){let i=eo(n.argument);if(!i.ok||!Ck(i.value))return{ok:!1};Object.assign(t,i.value);continue}if(!Y.isObjectProperty(n)||n.computed)return{ok:!1};let r=f$(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 c$(e){if(e.children.length===0)return{ok:!0,value:void 0};let t=[];for(let n of Y.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 Zl(e,t,n){let r=Ak(e)?new Set([...t,...l$(e)]):t;n(e,{names:r});for(let o of Object.values(e))if(Array.isArray(o))for(let i of o)kk(i)&&Zl(i,r,n);else kk(o)&&Zl(o,r,n)}function l$(e){if(!Ak(e))return[];let t=[];for(let n of e.params)qs(n,t);return t}function qs(e,t){if(Y.isIdentifier(e)){t.push(e.name);return}if(Y.isAssignmentPattern(e)){qs(e.left,t);return}if(Y.isObjectPattern(e)){for(let n of e.properties)Y.isRestElement(n)?qs(n.argument,t):Y.isObjectProperty(n)&&qs(n.value,t);return}if(Y.isArrayPattern(e))for(let n of e.elements)n&&qs(n,t)}function vk(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 zm(e){return{kind:"json-literal",value:e}}function Ck(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ik(e){return/^[A-Za-z][A-Za-z0-9_]{0,127}$/u.test(e)}function Nk(e){if(Y.isJSXIdentifier(e))return e.name;if(!Y.isJSXMemberExpression(e))return null;let t=Wm(e.object);return t?`${t}.${e.property.name}`:null}function Wm(e){if(Y.isJSXIdentifier(e))return e.name;if(!Y.isJSXMemberExpression(e))return null;let t=Wm(e.object);return t?`${t}.${e.property.name}`:null}function u$(e,t){if(Y.isJSXIdentifier(e))return t.get(e.name)??null;if(!Y.isJSXMemberExpression(e))return null;let n=Wm(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 d$(e){return Y.isJSXIdentifier(e)?e.name:Y.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function f$(e){return Y.isIdentifier(e)?e.name:Y.isStringLiteral(e)||Y.isNumericLiteral(e)?String(e.value):null}function Ak(e){return Y.isFunctionDeclaration(e)||Y.isFunctionExpression(e)||Y.isArrowFunctionExpression(e)}function kk(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function p$(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 Gm(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function Qs(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var h$=typeof Zm=="function"?Zm:Zm.default,qm=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=ql(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=Ee(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 y$(e){return Ok(e,!1)}function wk(e){return Ok(e,!0)}function Ok(e,t){let{binding:n,files:r}=e;if(e.hostCapabilities!==null&&!m$.safeParse(e.hostCapabilities).success)return vt("INVOCATION_VALUE_UNRESOLVED","generated-site-capabilities","Trusted host capabilities failed their strict schema.");if(!ea(n.descriptor.source.file)||!ea(n.ownerFile))return vt("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The resolved block source path is not a safe Snapshot source path.");let o=ql(r,n.descriptor.source.file),i=ql(r,n.ownerFile);if(o===null||i===null)return vt("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(Te(o)!==n.descriptor.source.contentHash||Te(o)!==n.sourceHash||Te(i)!==n.ownerSourceHash)return vt("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The pinned block or owner source hash no longer matches the resolved binding.");let s=Ee(n.descriptor.source.file,o);if(!s.ok)return vt("INVOCATION_PARSE_FAILED",n.descriptor.source.file,s.diagnostic.message);let a=Ql(s.module.ast,n.rootLocator.sourceRange);if(a.length!==1)return vt("INVOCATION_TARGET_AMBIGUOUS",n.descriptor.source.file,"The selected block source range does not identify exactly one JSX element.");let l=a[0],c=Lk(l.node);if(!c)return vt("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 qm(r),g=x$(e,c,f,t);if(g)return g;if(d.some(x=>(x.alternativeLocators?.length??0)>1))return vt("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=ql(r,E.sourceFile);if(b===null||!ea(E.sourceFile))return vt("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"A statically proven call-chain source is missing from the fixed Snapshot map.");let S=Ee(E.sourceFile,b);if(!S.ok)return vt("INVOCATION_PARSE_FAILED",E.sourceFile,S.diagnostic.message);let v=Ql(S.module.ast,E.callLocator.sourceRange);if(v.length!==1)return vt("INVOCATION_TARGET_AMBIGUOUS",E.sourceFile,"A call-chain locator does not identify exactly one current JSX element.");let P=d[x+1]?.sourceFile??n.descriptor.source.file,I=d[x+1]?.callLocator.sourceRange??n.rootLocator.sourceRange,C=_n({module:S.module,componentName:E.component,callSourceRange:E.callLocator.sourceRange});if(C.ok){if(C.sourceFile!==P)return vt("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The selected local component does not resolve to the source definition proven by the block graph.");if(C.roots.filter(oe=>Ci(oe.node,I)).length!==1)return vt("INVOCATION_TARGET_NOT_RENDERED",C.sourceFile,"The local component definition does not select exactly one proven JSX root.");let ge=_k({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(!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:C,entryExport:null});continue}let N=Qm(S.module.ast,v[0].node.openingElement.name,E.component,E.exportName);if(!N)return vt("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The statically proven component call no longer resolves through one exact import.");let w=eg(E.sourceFile,N.source,r);if(!w)return vt("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The selected component import is not a resolvable local Snapshot source.");let L=f.read(w);if(!L.ok)return vt(L.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",w,L.message);let D=Ut({module:L.module,exportName:N.exportName,parsedModules:f});if(!D.ok)return vt("INVOCATION_TARGET_NOT_RENDERED",D.diagnostic.file,D.diagnostic.message);if(D.sourceFile!==P)return vt("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=>Ci(K.node,I));if(U.length!==1)return vt("INVOCATION_TARGET_NOT_RENDERED",D.sourceFile,"The unique component export does not select exactly one proven JSX root.");let M=null;if(x===d.length-1&&d.length===1&&!Mk(n.ownerFile)&&Ci(U[0].node,n.rootLocator.sourceRange)){let K=f.read(D.sourceFile);if(!K.ok)return vt(K.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",D.sourceFile,K.message);if(M=Fk(K.module,D.componentName,N.exportName),!M)return vt("INVOCATION_TARGET_AMBIGUOUS",D.sourceFile,"The proven component definition has no unique final export for a Portable entry.")}let G=Pi({file_path:E.sourceFile,source:b,target:{source:N.source,export_name:N.exportName,local_name:N.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:M})}let m={kind:"page-block",composition:Dk(n.composition),blockKey:n.blockKey},p=b$(n,l,u,r,e.hostCapabilities);if(!p.ok)return{complete:!1,errors:[p.error]};let h=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:c,owner:n.descriptor.owner,call_chain:u.map(({call:x})=>x),strategy:p.strategy,entry_file:p.entryFile,entry_export:p.entryExport,invocation:h}}}function x$(e,t,n,r){let{binding:o,files:i}=e,s=o.root.callChain;if(s.length!==2)return null;let[a,l]=s;if(!a||!l||(a.alternativeLocators?.length??0)>1)return null;let c=n.get(a.sourceFile);if(!c)return null;let u=Ql(c.ast,a.callLocator.sourceRange);if(u.length!==1)return null;let d=Qm(c.ast,u[0].node.openingElement.name,a.component,a.exportName);if(!d)return null;let f=eg(a.sourceFile,d.source,i),g=f?n.get(f):void 0;if(!g)return null;let m=Ut({module:g,exportName:d.exportName,parsedModules:n});if(!m.ok||m.sourceFile!==l.sourceFile)return null;let p=n.get(m.sourceFile);if(!p||Fk(p,m.componentName,"default")?.kind!=="default")return null;let h={files:i,list_entry_file:a.sourceFile,selected_component_source:`@/${m.sourceFile.replace(/\.[cm]?[jt]sx?$/u,"")}`};if(r){if(!ik(h))return null}else{let P=$m(h);if(!P.complete||!P.relation)return null}let x=l.alternativeLocators?.length?l.alternativeLocators:[l.callLocator],E=m.returnAlternatives?.length?m.returnAlternatives:m.roots;if(E.length!==x.length||!E.every(P=>x.filter(I=>Ci(P.node,I.sourceRange)).length===1))return null;for(let P of x){let I=Ql(p.ast,P.sourceRange);if(I.length!==1)return null;let C=Qm(p.ast,I[0].node.openingElement.name,l.component,l.exportName);if(!C)return null;let N=eg(m.sourceFile,C.source,i),w=N?n.get(N):void 0;if(!w)return null;let L=Ut({module:w,exportName:C.exportName,parsedModules:n});if(!L.ok||L.sourceFile!==o.descriptor.source.file||L.roots.length!==1||!Ci(L.roots[0].node,o.rootLocator.sourceRange))return null}let b=Pi({file_path:a.sourceFile,source:c.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 v=`components/site/portable/${Tk("sha256").update(JSON.stringify(["collection-container",o.composition,o.blockKey,o.sourceHash,Te(p.source)])).digest("hex").slice(0,24)}/page.tsx`;return i.has(v)?vt("INVOCATION_TARGET_AMBIGUOUS",v,"The isolated collection entry collides with a pinned Snapshot source."):{complete:!0,selection:{target:{kind:"page-block",composition:Dk(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:v,entry_export:{kind:"default"},invocation:b}}}function b$(e,t,n,r,o){let i=n.at(-1);if(i?.kind==="import"){let c=i.definition.roots.length===1&&Ci(i.definition.roots[0].node,e.rootLocator.sourceRange),u=Mk(e.ownerFile);if(n.length===1&&c&&u)return{ok:!0,strategy:"managed-thin-entry",entryFile:e.ownerFile,entryExport:{kind:"default"}};if(n.length===1&&c&&i.entryExport)return{ok:!0,strategy:"reuse-entry",entryFile:i.definition.sourceFile,entryExport:i.entryExport}}if(!Lk(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 l=`components/site/portable/${Tk("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(l)||r.has(l)?{ok:!1,error:{code:"INVOCATION_TARGET_AMBIGUOUS",path:l,message:"The deterministic in-memory Portable entry path collides with an existing Snapshot file."}}:{ok:!0,strategy:"extract-jsx",entryFile:l,entryExport:{kind:"default"}}}function Fk(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=E$(i.declaration,t);s&&r.add(s)}if(!i.source)for(let s of i.specifiers)et.isExportSpecifier(s)&&s.exportKind!=="type"&&ng(s.local)===t&&r.add(ng(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 E$(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 Qm(e,t,n,r){let o=tg(t);if(!o||o!==n)return null;let i=et.isJSXMemberExpression(t)?tg(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 l of a.specifiers){if(et.isImportDefaultSpecifier(l)&&l.local.name===i)return r==="default"&&!s?{source:a.source.value,exportName:"default",localName:o}:null;if(et.isImportSpecifier(l)&&l.local.name===i){let c=ng(l.imported);return c===r&&!s?{source:a.source.value,exportName:c,localName:o}:null}if(et.isImportNamespaceSpecifier(l)&&l.local.name===i&&s)return s===r?{source:a.source.value,exportName:s,localName:o}:null}return null}function Ql(e,t){let n=[];return h$(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 Lk(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 Ci(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 ql(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 eg(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?Ym.posix.normalize(Ym.posix.join(Ym.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 tg(e){if(et.isJSXIdentifier(e))return e.name;if(et.isJSXMemberExpression(e)){let t=tg(e.object);return t?`${t}.${e.property.name}`:null}return null}function ng(e){return et.isIdentifier(e)?e.name:e.value}function Dk(e){return{routeId:e.routeId,...e.effectiveTemplateId!==void 0?{templateId:e.effectiveTemplateId}:{}}}function ea(e){return g$.safeParse(e).success}function Mk(e){return/(?:^|\/)\.vcp\/page-templates\//u.test(e)}function vt(e,t,n){return{complete:!1,errors:[{code:e,path:t,message:n}]}}import rg from"@babel/generator";import og from"@babel/traverse";import*as Q from"@babel/types";var eu=typeof og=="function"?og:og.default,Bk=typeof rg=="function"?rg:rg.default;function $k(e){let t=new Map(e.files),n=new Set(e.private_paths),r=[];for(let i of e.private_paths){let s=tu(t.get(i));if(s===null||!/\.[cm]?[jt]sx?$/iu.test(i))continue;let a=Ee(i,s);if(!a.ok){r.push({code:"SOURCE_PARSE_FAILED",path:i,message:a.diagnostic.message});continue}let l=!1;eu(a.module.ast,{Function:{exit(c){let u=c.get("body");u.isBlockStatement()&&(u.scope.crawl(),jk(u)&&(l=!0))}}}),eu(a.module.ast,{Program(c){let u;do{c.scope.crawl(),u=jk(c),u&&(l=!0),u&&c.scope.crawl();for(let d of c.get("body"))(d.isFunctionDeclaration()&&d.node.id&&!c.scope.getBinding(d.node.id.name)?.referenced||d.isVariableDeclaration({kind:"const"})&&d.node.declarations.every(f=>Q.isIdentifier(f.id)&&!c.scope.getBinding(f.id.name)?.referenced&&(!f.init||Ni(f.init))))&&(d.remove(),u=l=!0)}while(u);c.scope.crawl();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 f=ht(i,d.node.source.value,t);if(!(!f||!n.has(f))&&!d.node.specifiers.some(g=>c.scope.getBinding(g.local.name)?.referenced)){if(!Uk(f,t,new Set)){r.push({code:"SOURCE_UNUSED_IMPORT_UNPROVEN",path:i,message:`The unused import ${d.node.source.value} may have initialization effects.`});continue}d.remove(),l=!0}}c.stop()}}),l&&t.set(i,Bk(a.module.ast).code)}let o=S$(e.entry_file,t,n);for(let i of e.private_paths){let s=tu(t.get(i));if(s===null||!/\.[cm]?[jt]sx?$/iu.test(i))continue;let a=Ee(i,s);if(!a.ok)continue;let l=!1;eu(a.module.ast,{Program(c){let u=o.get(i)??new Set,d=g=>i===e.entry_file||!c.scope.getBinding(g)?.referencePaths.some(m=>!m.isExportDeclaration()&&!m.parentPath?.isExportSpecifier());if(i!==e.entry_file&&u.size>0&&!u.has("*")){for(let g of c.get("body")){if(!g.isExportNamedDeclaration()||g.node.exportKind==="type")continue;let m=g.node.declaration;if(!Q.isVariableDeclaration(m,{kind:"const"})||m.declarations.length!==1)continue;let p=m.declarations[0];Q.isIdentifier(p.id)&&Q.isStringLiteral(p.init)&&!u.has(p.id.name)&&d(p.id.name)&&!c.scope.getBinding(p.id.name)?.referencePaths.some(h=>h.parentPath?.isExportSpecifier())&&(g.remove(),l=!0)}l&&c.scope.crawl()}let f=[];for(let g of c.node.body)if(Q.isExportDefaultDeclaration(g))f.push("default");else if(Q.isExportAllDeclaration(g)&&g.exportKind!=="type")f.push(null,null);else if(Q.isExportNamedDeclaration(g)&&g.exportKind!=="type"){g.declaration&&!Q.isTSInterfaceDeclaration(g.declaration)&&!Q.isTSTypeAliasDeclaration(g.declaration)&&f.push(...Object.keys(Q.getOuterBindingIdentifiers(g.declaration)).filter(d));for(let m of g.specifiers)Q.isExportSpecifier(m)?m.exportKind!=="type"&&d(m.local.name)&&f.push(Q.isIdentifier(m.exported)?m.exported.name:m.exported.value):f.push(null)}f.length>1&&(i===e.entry_file||f.some(g=>g===null||!u.has(g)))&&r.push({code:"SOURCE_EXPORT_ISOLATION_UNPROVEN",path:i,message:"Multiple value exports cannot yet be isolated from unselected source."}),c.stop()}}),l&&t.set(i,Bk(a.module.ast).code)}return{files:t,errors:r}}function S$(e,t,n){let r=new Map,o=new Set,i=[e];for(;i.length&&o.size<512;){let s=i.pop();if(o.has(s))continue;o.add(s);let a=tu(t.get(s));if(a===null)continue;let l=Ee(s,a);if(!l.ok)continue;let c=u=>{let d=ht(s,u,t);if(!d||!n.has(d))return;let f=r.get(d)??new Set;f.add("*"),r.set(d,f),i.push(d)};eu(l.module.ast,{Program(u){for(let d of u.get("body")){if((d.isExportNamedDeclaration()||d.isExportAllDeclaration())&&d.node.source&&d.node.exportKind!=="type"){c(d.node.source.value);continue}if(!d.isImportDeclaration()||d.node.importKind==="type")continue;let f=ht(s,d.node.source.value,t);if(!f||!n.has(f))continue;i.push(f);let g=r.get(f)??new Set;for(let m of d.node.specifiers)if(!(Q.isImportSpecifier(m)&&m.importKind==="type")){if(!u.scope.getBinding(m.local.name)?.referenced){g.add("*");continue}Q.isImportDefaultSpecifier(m)?g.add("default"):Q.isImportSpecifier(m)?g.add(Q.isIdentifier(m.imported)?m.imported.name:m.imported.value):g.add("*")}r.set(f,g)}u.traverse({CallExpression(d){if(Q.isImport(d.node.callee)&&Q.isStringLiteral(d.node.arguments[0])&&c(d.node.arguments[0].value),Q.isIdentifier(d.node.callee)&&["eval","Function"].includes(d.node.callee.name)){let f=r.get(s)??new Set;f.add("*"),r.set(s,f)}},NewExpression(d){if(Q.isIdentifier(d.node.callee,{name:"Function"})){let f=r.get(s)??new Set;f.add("*"),r.set(s,f)}}}),u.stop()}})}return r}function jk(e){let t=new Map;for(let l of e.get("body")){let c=null,u=null;if(l.isFunctionDeclaration()&&l.node.id)c=l.node.id.name,u=l.node;else if(l.isVariableDeclaration({kind:"const"})&&l.node.declarations.length===1){let f=l.node.declarations[0];Q.isIdentifier(f.id)&&(Q.isFunctionExpression(f.init)||Q.isArrowFunctionExpression(f.init))&&(c=f.id.name,u=f.init)}let d=c?e.scope.getBinding(c):void 0;c&&u&&d&&d.constantViolations.length===0&&t.set(c,{definition:u,declaration:l,binding:d})}let n=new Map([...t].map(([l,c])=>[c.definition,l])),r=new Set,o=new Map;for(let[l,c]of t)for(let u of c.binding.referencePaths){let d=u.findParent(g=>n.has(g.node)),f=d?n.get(d.node):void 0;if(!f)r.add(l);else{let g=o.get(f)??new Set;g.add(l),o.set(f,g)}}let i=new Set,s=[...r];for(;s.length;){let l=s.pop();i.has(l)||(i.add(l),s.push(...o.get(l)??[]))}let a=!1;for(let[l,c]of t)i.has(l)||(c.declaration.remove(),a=!0);return a}function Uk(e,t,n){if(n.has(e)||n.size>=64)return!1;let r=tu(t.get(e));if(r===null)return!1;let o=Ee(e,r);if(!o.ok)return!1;let i=new Set(n).add(e),s=a=>{if(!mt(a))return!1;let l=ht(e,a,t);return l!==null&&Uk(l,t,i)};return o.module.ast.program.body.every(a=>Q.isImportDeclaration(a)?a.importKind==="type"||a.specifiers.length>0&&a.specifiers.every(l=>Q.isImportSpecifier(l)&&l.importKind==="type")?!0:s(a.source.value):Q.isExportAllDeclaration(a)?a.exportKind==="type"||s(a.source.value):Q.isExportNamedDeclaration(a)?a.exportKind==="type"?!0:a.source?s(a.source.value):a.declaration?ig(a.declaration):!0:Q.isExportDefaultDeclaration(a)?ig(a.declaration):ig(a))}function ig(e){return Q.isFunctionDeclaration(e)||Q.isTSInterfaceDeclaration(e)||Q.isTSTypeAliasDeclaration(e)||Q.isTSDeclareFunction(e)||Q.isEmptyStatement(e)?!0:Q.isVariableDeclaration(e)&&e.kind==="const"?e.declarations.every(t=>Q.isIdentifier(t.id)&&(!t.init||Ni(t.init))):Ni(e)}function Ni(e){return Q.isStringLiteral(e)||Q.isNumericLiteral(e)||Q.isBooleanLiteral(e)||Q.isNullLiteral(e)||Q.isFunctionExpression(e)||Q.isArrowFunctionExpression(e)?!0:Q.isArrayExpression(e)?e.elements.every(t=>t===null||!Q.isSpreadElement(t)&&Ni(t)):Q.isObjectExpression(e)?e.properties.every(t=>Q.isObjectProperty(t)&&!t.computed&&!t.shorthand&&Ni(t.value)):Q.isTSAsExpression(e)||Q.isTSSatisfiesExpression(e)||Q.isTSNonNullExpression(e)||Q.isParenthesizedExpression(e)?Ni(e.expression):!1}function tu(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 ta}from"node:crypto";import sg from"@babel/traverse";import*as Pe from"@babel/types";import{PORTABLE_AUDITED_PLACEHOLDER_SVG as ag,PORTABLE_AUDITED_SAFE_IMAGE as v$}from"@vcp-dev/contracts";var lg=typeof sg=="function"?sg:sg.default,nu=v$.digest_sha256;function Kk(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:${nu}`)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(ag.path);if(i===void 0||ta("sha256").update(i).digest("hex")!==nu||!(s instanceof Uint8Array)||s.byteLength!==ag.byte_size||ta("sha256").update(s).digest("hex")!==ag.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 l=[],c=I$(e,n);for(let u of a){let d=u.from,f=(e.selected_host_calls??[]).filter(N=>N.file_path===d&&N.host_file===e.host_file);if(!f.length&&!c(d))return t();let g=yt(e.files.get(d));if(g===null)return t();let m=Ee(d,g);if(!m.ok)return t();let p=Ut({module:m.module,exportName:n.get(d)??"default"});if(!f.length&&(!p.ok||p.metadataOnly||p.returnAlternatives))return t();let h=null,x=!1;if(lg(m.module.ast,{ImportDeclaration(N){if(ht(d,N.node.source.value,e.files)!==e.host_file||N.node.importKind==="type")return;let w=N.get("specifiers"),L=w[0];if(h||w.length!==1||!L?.isImportSpecifier()||L.node.importKind==="type"||!Pe.isIdentifier(L.node.imported,{name:"SafeImage"})){x=!0;return}h=L}}),x||!h)return t();let E=h,b=E.scope.getBinding(E.node.local.name);if(!b?.constant||b.path.node!==E.node)return t();if(f.length){let N=`sha256:${ta("sha256").update(g).digest("hex")}`;if(f.length>256||f.some(U=>U.source_hash!==N))return t();let w=new Set(f.map(U=>`${U.start}:${U.end}`)),L=new Map,D=!1;if(lg(m.module.ast,{JSXOpeningElement(U){if(!(!Pe.isJSXIdentifier(U.node.name)||U.scope.getBinding(U.node.name.name)!==b)){if(!w.has(`${U.node.start}:${U.node.end}`)||!Vk(U.node)){D=!0;return}L.set(U.node,U)}}}),D||L.size!==w.size||!cg(b.referencePaths,new Set(L.keys())))return t();for(let U of L.values()){let M=U.node;if(M.start==null||M.end==null||!M.loc)return t();let G=g.slice(M.start,M.end);l.push({file_path:d,kind:"host-fallback",source:"host-fallback",value:"/media/placeholder.svg",expression:G,asset_key:null,source_range:{start_offset:M.start,end_offset:M.end,start_line:M.loc.start.line,start_column:M.loc.start.column,end_line:M.loc.end.line,end_column:M.loc.end.column},content_digest:`sha256:${ta("sha256").update(G).digest("hex")}`,complete:!0,host_fallback:{file_path:e.host_file,digest_sha256:nu}})}continue}if(!p.ok||p.metadataOnly||p.returnAlternatives)return t();let S=new Map,v=new Map,P=!1,I=0,C=(N,w=0,L=!1)=>{if(++I>2048||w>128){P=!0;return}if(N.isJSXElement()){let D=N.get("openingElement");if(!Pe.isJSXIdentifier(D.node.name)){P=!0;return}if(D.scope.getBinding(D.node.name.name)===b){Vk(D.node)||(P=!0),S.set(D.node,D);return}if(!/^[a-z]/u.test(D.node.name.name)){if(L)return;let U=D.scope.getBinding(D.node.name.name);if(!U?.constant)return;let M=U.path;if(!(M.isFunctionDeclaration()&&!M.parentPath.isExportNamedDeclaration()&&!M.parentPath.isExportDefaultDeclaration()||M.isVariableDeclarator()&&M.parentPath.isVariableDeclaration({kind:"const"})&&!M.parentPath.parentPath.isExportNamedDeclaration()&&(Pe.isFunctionExpression(M.node.init)||Pe.isArrowFunctionExpression(M.node.init)))||!N.node.loc)return;let K=v.get(U.identifier);if(K){K.openings.add(D.node),K.active&&(P=!0);return}if(v.size>=32){P=!0;return}let ge={references:U.referencePaths,openings:new Set([D.node]),active:!0};v.set(U.identifier,ge);let oe=_n({module:m.module,componentName:D.node.name.name,callSourceRange:{startLine:N.node.loc.start.line,startColumn:N.node.loc.start.column,endLine:N.node.loc.end.line,endColumn:N.node.loc.end.column}});if(!oe.ok||oe.metadataOnly||oe.returnAlternatives||oe.sourceFile!==d){P=!0;return}for(let Me of oe.roots)C(Me,w+1,L);ge.active=!1;return}if(["template","script","style","noscript"].includes(D.node.name.name)||D.node.attributes.some(U=>!Pe.isJSXAttribute(U)||!Pe.isJSXIdentifier(U.name)||/^(?:on|ref$|style$|dangerouslySetInnerHTML$)/iu.test(U.name.name))){P=!0;return}}for(let D of N.get("children"))if(D.isJSXElement()||D.isJSXFragment())C(D,w+1,L);else if(D.isJSXExpressionContainer()){let U=D.get("expression");if(U.isJSXElement()||U.isJSXFragment())C(U,w+1,L);else if(U.isLogicalExpression({operator:"&&"})&&ru(U.node.left)&&_$(U.get("left"))){let M=U.get("right");(M.isJSXElement()||M.isJSXFragment())&&C(M,w+1,!0)}}};for(let N of p.roots)C(N);if(P||S.size===0||!cg(b.referencePaths,new Set(S.keys())))return t();for(let N of v.values())if(!cg(N.references,N.openings))return t();for(let N of S.values()){let w=N.node;if(w.start==null||w.end==null||!w.loc)return t();let L=g.slice(w.start,w.end);l.push({file_path:d,kind:"host-fallback",source:"host-fallback",value:"/media/placeholder.svg",expression:L,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:${ta("sha256").update(L).digest("hex")}`,complete:!0,host_fallback:{file_path:e.host_file,digest_sha256:nu}})}}return{complete:!0,references:l}}function cg(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 I$(e,t){let n=new Map;for(let a of e.closure.edges){if(!a.target||a.kind==="type")continue;let l=n.get(a.target)??[];l.push(a),n.set(a.target,l)}let r=new Map,o=new Set,i=new Map,s=a=>{if(t.has(a))return!0;let l=r.get(a);if(l!==void 0)return l;if(o.has(a)||o.size>=32||r.size>=512)return!1;o.add(a);let c=n.get(a)??[],u=c.length>0&&c.length<=256;for(let d of c){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=k$(d.from,a,e.files,t.get(d.from)??"default")&&Hl(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 k$(e,t,n,r){let o=yt(n.get(e));if(o===null)return!1;let i=Ee(e,o);if(!i.ok)return!1;let s=null,a=!1;if(lg(i.module.ast,{ImportDeclaration(p){if(p.node.importKind==="type"||ht(e,p.node.source.value,n)!==t)return;let h=p.get("specifiers"),x=h[0];if(s||h.length!==1||!x||!(x.isImportDefaultSpecifier()||x.isImportSpecifier()&&x.node.importKind!=="type"&&Pe.isIdentifier(x.node.imported,{name:"default"}))){a=!0;return}s=x}}),a||!s)return!1;let l=s,c=l.scope.getBinding(l.node.local.name);if(!c?.constant||c.path.node!==l.node)return!1;let u=[],d=[];for(let p of c.referencePaths){let h=p.parentPath;if(h?.isJSXOpeningElement()&&h.node.name===p.node)u.push(h);else if(h?.isJSXClosingElement()&&h.node.name===p.node)d.push(h);else return!1}let f=Cn(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=Ut({module:i.module,exportName:r});if(!p.ok||p.metadataOnly||!p.returnAlternatives||p.returnAlternatives.length!==u.length||!p.returnAlternatives.every(h=>h.isJSXElement()&&m.has(h.node.openingElement))||new Set(p.returnAlternatives.map(h=>h.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 Vk(e){let t=new Set;for(let n of e.attributes){if(!Pe.isJSXAttribute(n)||!Pe.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"&&Pe.isJSXExpressionContainer(o)&&Do(o.expression))&&o!==null&&!Pe.isStringLiteral(o)&&!(Pe.isJSXExpressionContainer(o)&&(Pe.isStringLiteral(o.expression)||Pe.isNumericLiteral(o.expression)||Pe.isBooleanLiteral(o.expression))))return!1}return t.has("src")}function _$(e){try{let t=e.evaluate();return!t.confident||!!t.value}catch{return!1}}function ru(e,t=0){return t>32?!1:Pe.isIdentifier(e)?!["undefined","NaN","Infinity"].includes(e.name):Pe.isMemberExpression(e)||Pe.isOptionalMemberExpression(e)?Do(e):Pe.isUnaryExpression(e,{operator:"!"})?ru(e.argument,t+1):Pe.isBinaryExpression(e)?ru(e.left,t+1)&&Do(e.right)||Do(e.left)&&ru(e.right,t+1):!1}function Do(e,t=0){if(t>32)return!1;if(Pe.isStringLiteral(e)||Pe.isNumericLiteral(e)||Pe.isBooleanLiteral(e)||Pe.isNullLiteral(e)||Pe.isIdentifier(e))return!0;if(Pe.isMemberExpression(e)||Pe.isOptionalMemberExpression(e)){let n=e.property;return!e.computed&&!Pe.isIdentifier(n)||e.computed&&!(Pe.isStringLiteral(n)||Pe.isNumericLiteral(n))||(Pe.isIdentifier(n)||Pe.isStringLiteral(n))&&["__proto__","prototype","constructor"].includes(Pe.isIdentifier(n)?n.name:n.value)?!1:Do(e.object,t+1)}return Pe.isLogicalExpression(e)?Do(e.left,t+1)&&Do(e.right,t+1):!1}async function Xk(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=yt(n.get(t.ownerFile)),s=yt(n.get(t.descriptor.source.file));if(i===null||s===null)return[];let a=async l=>{let c=yt(n.get(l));if(c===null)throw new Error("Snapshot source unavailable");return c};try{let l=await zo(t.ownerFile,i,a,async p=>n.has(p));if(!l.entryModule||l.diagnostics.length)return[];let c=[...l.graph.elements.values()].filter(p=>p.importedFrom===t.descriptor.source.file);if(c.length!==1||c[0].sourceFile!==o.sourceFile||c[0].exportName!==o.exportName||!R$(c[0].sourceRange,o.callLocator.sourceRange))return[];let u=[...l.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 h=l.parsedModules.get(p.sourceFile);if(!h)continue;let x=_n({module:h,componentName:p.tag,callSourceRange:p.sourceRange,...p.importedFrom?{imported:{file:p.importedFrom,module:l.parsedModules.get(p.importedFrom),exportName:p.exportName??p.tag,parsedModules:l.parsedModules}}:{}});if(!x.ok||x.metadataOnly)continue;let E=[...x.roots,...x.returnAlternatives??[]];for(let b of l.graph.fileIndex.get(x.sourceFile)??[]){let S=l.graph.elements.get(b);if(!(!S||d.has(b)||!E.some(v=>{let P=v.node.loc;return P&&Jk({startLine:P.start.line,startColumn:P.start.column,endLine:P.end.line,endColumn:P.end.column},S.sourceRange)}))&&(d.add(b),u.push(S),u.length>256))return[]}}d.add(c[0].identity.key);let f={...l.graph,elements:new Map([...l.graph.elements].filter(([p])=>d.has(p))),regions:l.graph.regions.filter(p=>d.has(p.ownerKey))},g=new Set,m=new Map;for(let p of u){let h=await fl({element:p,graph:f,file:p.sourceFile,source:await a(p.sourceFile),readFile:a,exists:async x=>n.has(x),fileCache:m});for(let x of h.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 R$(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 ug from"@babel/traverse";import*as tt from"@babel/types";import*as rn from"@babel/types";function zk(e){let t=new Set,n=new Map,r=l=>{let c=l.get("arguments");return c.length===1&&c[0].isArrowFunctionExpression()&&!c[0].node.async&&c[0].node.params.length<=2&&!c[0].node.params.some(u=>rn.isRestElement(u))},o=l=>{let c=l;for(;c.parentPath&&(c.parentPath.isTSAsExpression()||c.parentPath.isTSTypeAssertion()||c.parentPath.isTSSatisfiesExpression()||c.parentPath.isTSNonNullExpression()||c.parentPath.isParenthesizedExpression());)c=c.parentPath;let u=c.parentPath;return u?u.isAssignmentExpression()&&u.node.left===c.node||u.isUpdateExpression()||u.isUnaryExpression({operator:"delete"})||(u.isCallExpression()||u.isOptionalCallExpression())&&u.node.callee===c.node||(u.isMemberExpression()||u.isOptionalMemberExpression())&&u.node.object===c.node&&["call","apply","bind"].includes(ou(u.node)??"")||u.isNewExpression()&&u.node.callee===c.node||u.isTaggedTemplateExpression()&&u.node.tag===c.node||u.isForInStatement()&&u.node.left===c.node||u.isForOfStatement()&&u.node.left===c.node:!0},i=l=>{if(!l.node.computed||!rn.isIdentifier(l.node.object))return!1;let c=l.get("property");if(!c.isBinaryExpression({operator:"-"})||!rn.isNumericLiteral(c.node.right)||!Number.isSafeInteger(c.node.right.value)||c.node.right.value<=0)return!1;let u=c.get("left");return!u.isMemberExpression()||ou(u.node)!=="length"||!rn.isIdentifier(u.node.object)?!1:l.scope.getBinding(l.node.object.name)===u.scope.getBinding(u.node.object.name)},s=l=>{let c=n.get(l.identifier);if(c!==void 0)return c;if(t.has(l.identifier))return!0;t.add(l.identifier);let u=l.referencePaths.every(d=>{let f=d.parentPath;if(!f?.isMemberExpression()||f.node.object!==d.node)return!1;let g=ou(f.node);if(g==="map"||g==="forEach"){let m=f.parentPath;return m.isCallExpression()&&m.node.callee===f.node&&r(m)}return(g==="length"||f.node.computed&&rn.isNumericLiteral(f.node.property)||i(f))&&!o(f)});return t.delete(l.identifier),n.set(l.identifier,u),u},a=(l,c)=>{if(!l.node||c.has(l.node)||c.size>=32)return!1;let u=new Set(c).add(l.node);if(l.isTSAsExpression()||l.isTSTypeAssertion()||l.isTSSatisfiesExpression()||l.isTSNonNullExpression()||l.isParenthesizedExpression())return a(l.get("expression"),u);if(l.isIdentifier()){let d=l.scope.getBinding(l.node.name);return!!(d?.constant&&d.kind==="const"&&!d.constantViolations.length&&d.path.isVariableDeclarator()&&rn.isIdentifier(d.path.node.id)&&d.path.node.start!=null&&l.node.start!=null&&d.path.node.start<l.node.start&&s(d)&&a(d.path.get("init"),u))}if(l.isArrayExpression())return l.node.elements.every(d=>d!==null&&!rn.isSpreadElement(d));if(l.isCallExpression()){let d=l.get("callee");return d.isMemberExpression()&&ou(d.node)==="map"&&r(l)&&a(d.get("object"),u)}return!1};return i(e)&&!o(e)&&a(e.get("object"),new Set)}function ou(e){return!e.computed&&rn.isIdentifier(e.property)?e.property.name:rn.isStringLiteral(e.property)?e.property.value:null}var Hk=typeof ug=="function"?ug:ug.default;function Wk(e){let t=new Map;for(let[n,r]of e.sources){if(!/\.[cm]?[jt]sx?$/iu.test(n))continue;let o=Ee(n,r);o.ok&&Hk(o.module.ast,{ImportDeclaration(i){if(i.node.importKind==="type")return;let s=ht(n,i.node.source.value,e.files);if(!(!s||!e.sources.has(s)))for(let a of i.node.specifiers){if(tt.isImportSpecifier(a)&&a.importKind==="type")continue;let l=i.scope.getBinding(a.local.name);if(!l?.referencePaths.length)continue;let c=!tt.isImportNamespaceSpecifier(a)&&l.constant&&l.referencePaths.every(u=>(u.parentPath?.isJSXOpeningElement()||u.parentPath?.isJSXClosingElement())&&u.parentPath.node.name===u.node);t.set(s,(t.get(s)??!0)&&c)}}})}return new Set([...t].filter(([,n])=>n).map(([n])=>n))}function Gk(e){let t=Ee(e.file_path,e.source),n=[],r=new Set,o=(s,a)=>{n.some(l=>l.code===s&&l.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&&C$(s,e.current_route)){r.add(e.current_route);return}if(tt.isTemplateLiteral(s)&&Yk(s,e.current_route,"#"))return;if(!tt.isStringLiteral(s)){o("ROUTE_VALUE_UNRESOLVED","A navigation destination is not a proven literal.");return}let a=Zk(s.value);a==="host-route"?r.add(s.value):a==="unknown"&&o("ROUTE_VALUE_UNRESOLVED","A navigation destination is unsafe or unsupported.")};return Hk(t.module.ast,{JSXOpeningElement(s){let a=tt.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 l=s.node.attributes.filter(d=>tt.isJSXAttribute(d)&&tt.isJSXIdentifier(d.name)&&d.name.name.toLowerCase()==="type"),c=l.length===1&&tt.isJSXAttribute(l[0])?l[0].value:null,u=tt.isStringLiteral(c)?c.value.toLowerCase():null;(a==="button"&&u!=="button"||a==="input"&&(l.length>1||l.length===1&&!u||u==="submit"||u==="image"))&&o("ROUTE_VALUE_UNRESOLVED","A form control may submit an unproven host form.")}},JSXAttribute(s){if(!tt.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 l=s.node.value;i(tt.isJSXExpressionContainer(l)?l.expression:l)},JSXSpreadAttribute(s){e.allow_props_forwarding&&P$(s)||o("ROUTE_VALUE_UNRESOLVED","A JSX spread may contain an unproven navigation destination.")},ObjectProperty(s){let a=na(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=na(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=na(s.node.property,s.node.computed);s.node.computed&&a===null&&!zk(s)&&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)&&tt.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"&&tt.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){(tt.isIdentifier(s.node.left,{name:"location"})||tt.isMemberExpression(s.node.left)&&(na(s.node.left.property,s.node.left.computed)==="href"||s.node.left.computed&&na(s.node.left.property,!0)===null))&&o("ROUTE_VALUE_UNRESOLVED","Imperative navigation is not proven.")},CallExpression(s){tt.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 P$(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 C$(e,t){return Yk(e,t,"?")}function Yk(e,t,n){if(!t||t.includes("?")||t.includes("#")||Zk(t)!=="host-route")return!1;let r=tt.isStringLiteral(e)?[e.value]:tt.isTemplateLiteral(e)?e.quasis.map(o=>o.value.cooked):[];return r.length>0&&typeof r[0]=="string"&&r[0].startsWith(n)&&r.every(o=>typeof o=="string"&&o.length<=2048&&!/[\s\u0000-\u0020\u007f-\u009f\\]/u.test(o))}function na(e,t){return tt.isStringLiteral(e)?e.value:!t&&tt.isIdentifier(e)?e.name:t&&tt.isNumericLiteral(e)?String(e.value):null}function Zk(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 T$}from"node:crypto";import w$ from"@babel/traverse";import*as Ve from"@babel/types";import dg from"@babel/traverse";import*as It from"@babel/types";var N$=typeof dg=="function"?dg:dg.default,A$=new Set(["__proto__","prototype","constructor"]);function qk(e){let t=new Map,n=new WeakMap,r=new Set,o=new Map,i=e.files??new Map,s=(h,x)=>{N$(x,{Program(E){t.set(h,E),n.set(E.node,h),E.stop()}})};s(e.file_path,e.ast);let a=h=>{if(t.has(h))return t.get(h)??null;if(t.size>=512)return null;t.set(h,null);let x=i.get(h);if(x===void 0)return null;let E=typeof x=="string"?x:new TextDecoder("utf-8",{fatal:!0}).decode(x),b=Ee(h,E);return b.ok&&s(h,b.module.ast),t.get(h)??null},l=h=>n.get(h.scope.getProgramParent().path.node),c=(h,x)=>{let E=!x&&It.isIdentifier(h)?h.name:It.isStringLiteral(h)?h.value:It.isNumericLiteral(h)&&Number.isSafeInteger(h.value)&&h.value>=0?String(h.value):null;return E!==null&&!A$.has(E)?E:null},u=(h,x)=>{let E=[];for(let b of h.get("body"))if(!(!b.isExportNamedDeclaration()||b.node.source)){It.isVariableDeclaration(b.node.declaration)&&b.node.declaration.declarations.some(S=>It.isIdentifier(S.id,{name:x}))&&E.push(x);for(let S of b.node.specifiers)It.isExportSpecifier(S)&&It.isIdentifier(S.local,{name:x})&&E.push(It.isIdentifier(S.exported)?S.exported.name:S.exported.value)}return E},d=(h,x)=>{let E=Object.values(h.scope.bindings).filter(b=>u(h,b.identifier.name).includes(x));return E.length===1?E[0]:null},f=h=>{if(!h.path.isImportSpecifier()||h.path.node.importKind==="type")return null;let x=h.path.parentPath,E=l(h.path);if(!E||!x.isImportDeclaration()||x.node.importKind==="type")return null;let b=ht(E,x.node.source.value,i),S=b?a(b):null,v=h.path.node.imported,P=S?d(S,It.isIdentifier(v)?v.name:v.value):null;return P?.path.isVariableDeclarator()?P:null},g=(h,x=new Set)=>{if(!h.constant||h.constantViolations.length||x.has(h.identifier)||x.size>=32)return null;if(h.path.isImportSpecifier()){let E=f(h);return E?g(E,new Set(x).add(h.identifier)):null}return h.kind==="const"&&h.path.isVariableDeclarator()&&It.isIdentifier(h.path.node.id)&&h.path.parentPath.isVariableDeclaration({kind:"const"})?h.path.get("init"):null},m=h=>{let x=o.get(h.identifier);if(x!==void 0)return x;if(r.has(h.identifier))return!0;r.add(h.identifier);let E=h.constant&&h.constantViolations.length===0;for(let P of h.referencePaths){if(!E)break;if(P.isExportNamedDeclaration()||P.parentPath?.isExportSpecifier()&&P.parentPath.node.local===P.node)continue;let I=P;for(;I.parentPath?.isMemberExpression()&&I.parentPath.node.object===I.node;)I=I.parentPath;let C=I.parentPath;if(I===P||C?.isAssignmentExpression()&&C.node.left===I.node||C?.isUpdateExpression()||C?.isUnaryExpression({operator:"delete"})||C?.isForInStatement()||C?.isForOfStatement()){E=!1;break}let N=p(I,new Set);(!N||!(N.isStringLiteral()||N.isTemplateLiteral()&&N.node.expressions.length===0))&&(E=!1)}let b=l(h.path),S=h.path.scope.getProgramParent().path,v=b&&S.isProgram()&&!h.path.isImportSpecifier()?u(S,h.identifier.name):[];if(E&&v.length)for(let[P]of i){if(!E||!/\.[cm]?[jt]sx?$/iu.test(P))continue;let I=a(P);if(!I){E=!1;break}for(let C of I.get("body"))if(!(!(C.isImportDeclaration()||C.isExportNamedDeclaration()||C.isExportAllDeclaration())||!C.node.source||ht(P,C.node.source.value,i)!==b)){if(!C.isImportDeclaration()){E=!1;break}if(C.node.importKind!=="type")for(let N of C.node.specifiers){if(It.isImportNamespaceSpecifier(N)){E=!1;break}if(!It.isImportSpecifier(N)||N.importKind==="type")continue;let w=It.isIdentifier(N.imported)?N.imported.name:N.imported.value;if(!v.includes(w))continue;let L=I.scope.getBinding(N.local.name);if(!L||!m(L)){E=!1;break}}}}return r.delete(h.identifier),o.set(h.identifier,E),E},p=(h,x)=>{if(!h.node||x.has(h.node)||x.size>=32)return null;let E=new Set(x).add(h.node);if(h.isJSXExpressionContainer()||h.isTSAsExpression()||h.isTSTypeAssertion()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()||h.isParenthesizedExpression())return p(h.get("expression"),E);if(h.isIdentifier()){let b=h.scope.getBinding(h.node.name);if(!b||b.path.isVariableDeclarator()&&(b.path.node.start==null||h.node.start==null||b.path.node.start>=h.node.start))return null;let S=g(b),v=S?p(S,E):null;if(v&&(v.isObjectExpression()||v.isArrayExpression())){let P=b.path.isImportSpecifier()?f(b):b;if(!P||!m(P)||!m(b))return null}return v}if(h.isMemberExpression()){let b=c(h.node.property,h.node.computed),S=p(h.get("object"),E);if(b===null||!S)return null;if(S.isArrayExpression()){if(!/^(?:0|[1-9][0-9]*)$/u.test(b)||S.node.elements.some(P=>!P||It.isSpreadElement(P)))return null;let v=S.get("elements")[Number(b)];return v?.node?p(v,E):null}if(S.isObjectExpression()){let v=S.get("properties"),P=v.map(C=>C.isObjectProperty()?c(C.node.key,C.node.computed):null);if(P.some(C=>C===null)||new Set(P).size!==P.length)return null;let I=v[P.indexOf(b)];return I?.isObjectProperty()?p(I.get("value"),E):null}return null}return h.isStringLiteral()||h.isTemplateLiteral()&&h.node.expressions.length===0||h.isObjectExpression()||h.isArrayExpression()?h:null};return h=>{let x=p(h,new Set);return x?.isStringLiteral()?{value:x.node.value,complete:!0}:x?.isTemplateLiteral()&&!x.node.expressions.length?{value:x.node.quasis.map(E=>E.value.cooked??E.value.raw).join(""),complete:!0}:{value:null,complete:!1}}}var fg=w$,O$=typeof fg=="function"?fg:fg.default,F$=new Set(["avif","bmp","gif","jpeg","jpg","mp3","mp4","ogg","png","svg","wav","webm","webp"]),to=new Set(["backgroundimage","fallbacksrc","image","imageurl","media","mediaurl","poster","src","srcset","thumbnail","thumbnailurl"]),n_=/(?:asset|avatar|gallery|image|media|photo|poster|thumbnail|video)/iu,L$=/^(?:audio|img|image|picture|safeimage|source|video|media|.*(?:audio|image|video))$/iu;function au(e){let t=Ee(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=qk({file_path:e.file_path,ast:t.module.ast,files:e.files}),o=[],i=new Set,s=c=>{if(e.static_only&&!c.complete)return;let u=t_(c.node),d=V$(e.source,u),f=`${u.start_offset}:${u.end_offset}:${c.kind}:${c.value??"<unknown>"}`;i.has(f)||(i.add(f),n.push({file_path:e.file_path,occurrence:n.length,kind:c.kind,source:c.source,value:c.value,expression:d,asset_key:c.assetKey??null,source_range:u,content_digest:K$(d),complete:c.complete}),c.complete||o.push({code:"MEDIA_VALUE_UNKNOWN",file_path:e.file_path,message:"The media expression cannot be resolved without executing user code.",source_range:u}))},a=(c,u)=>{if(!u){s({node:c,kind:"manifest",source:"media-manifest",value:null,complete:!1});return}let d=e.media_manifest?.[u];if(d===void 0){let f=t_(c);o.push({code:"MEDIA_MANIFEST_KEY_UNKNOWN",file_path:e.file_path,message:`The media manifest key ${u} is not available in the supplied snapshot.`,source_range:f})}s({node:c,kind:"manifest",source:"media-manifest",value:d??null,assetKey:u,complete:d!==void 0})};O$(t.module.ast,{ImportDeclaration(c){let u=c.node.source.value;M$(u)&&s({node:c.node.source,kind:"import",source:"import",value:u,complete:!0})},JSXOpeningElement(c){let u=r_(c.node.name),d=L$.test(u);for(let f of c.get("attributes")){if(f.isJSXSpreadAttribute()){d&&s({node:f.node.argument,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}if(!f.isJSXAttribute())continue;let g=f.node,m=j$(g);if(m==="style"&&!D$(g.value)){s({node:g.value??g,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}if(!m||!B$(m,d))continue;let p=r(f.get("value"));s({node:g.value??g,kind:Qk(m),source:"jsx-attribute",value:p.value,complete:p.complete})}},ObjectProperty(c){let u=ra(c);if(!u.known){s({node:c.node,kind:"object",source:"object-property",value:null,complete:!1});return}let d=u.name;if(!d||!to.has(d)&&!(e_(c)&&pg(d)))return;let f=c.get("value");if(to.has(d)&&(f.isObjectExpression()||f.isArrayExpression())&&su(f))return;let g=r(c.get("value"));s({node:c.node.value,kind:Qk(d),source:"object-property",value:g.value,complete:g.complete})},ObjectMethod(c){let u=ra(c);(!u.known||c.node.kind!=="method"&&u.name&&(to.has(u.name)||e_(c)&&pg(u.name)))&&s({node:c.node,kind:"object",source:"object-property",value:null,complete:!1})},ArrayExpression(c){if(U$(c))for(let u of c.get("elements")){if(!u.node||(u.isObjectExpression()||u.isArrayExpression())&&su(u))continue;let d=r(u);(d.value!==null||!d.complete)&&s({node:u.node,kind:"array-item",source:"array-item",value:d.value,complete:d.complete})}},CallExpression(c){let u=c.node.callee;if(!Ve.isIdentifier(u,{name:"mediaAsset"})||c.node.arguments.length!==1)return;let d=c.node.arguments[0];if(!Ve.isExpression(d)){a(c.node,null);return}let f=Ai(d);a(c.node,f.complete?f.value:null)},MemberExpression(c){if(!$$(c.node.object))return;let u=c.node.computed?Ai(c.node.property):Ve.isIdentifier(c.node.property)?{value:c.node.property.name,complete:!0}:{value:null,complete:!1};a(c.node,u.complete?u.value:null)}});let l=J$(o).sort(X$);return{complete:l.length===0,references:n.map((c,u)=>({...c,occurrence:u})),errors:l}}function D$(e){return!Ve.isJSXExpressionContainer(e)||!Ve.isObjectExpression(e.expression)?!1:e.expression.properties.every(t=>{if(!Ve.isObjectProperty(t)||t.computed||!(Ve.isIdentifier(t.key)||Ve.isStringLiteral(t.key)))return!1;let n=Ve.isIdentifier(t.key)?t.key.name:t.key.value;return!n||n==="__proto__"||n.startsWith("--")?!1:Ve.isNumericLiteral(t.value)?Number.isFinite(t.value.value):Ve.isStringLiteral(t.value)&&/^[\w\s#.,%+!-]*$/u.test(t.value.value)})}function M$(e){let n=(e.split(/[?#]/u,1)[0]??"").split(".").pop()?.toLowerCase();return n!==void 0&&F$.has(n)}function B$(e,t){return e!=="src"||t?to.has(e):!1}function Qk(e){return e==="srcset"?"srcset":e==="poster"?"poster":e.startsWith("thumbnail")?"thumbnail":e==="src"?"src":"object"}function j$(e){return Ve.isJSXIdentifier(e.name)?e.name.name.toLowerCase():Ve.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`.toLowerCase():null}function r_(e){return Ve.isJSXIdentifier(e)?e.name:Ve.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:`${r_(e.object)}.${e.property.name}`}function ra(e){if(!e.node.computed){let n=e.node.key;return Ve.isIdentifier(n)?{known:!0,name:n.name.toLowerCase()}:Ve.isStringLiteral(n)?{known:!0,name:n.value.toLowerCase()}:{known:!0,name:null}}let t=iu(e.get("key"));if(t.complete&&t.value!==null)return{known:!0,name:t.value.toLowerCase()};if(Ve.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=[...to,"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 $$(e){return Ve.isIdentifier(e,{name:"mediaAssets"})}function U$(e){let t=e.parentPath;if(t?.isObjectProperty()){let n=ra(t).name;return n!==null&&to.has(n)}return t?.isVariableDeclarator()&&Ve.isIdentifier(t.node.id)?n_.test(t.node.id.name):!1}function e_(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=ra(r).name;if(o&&to.has(o))return!0;t=r.parentPath;continue}return!!(r?.isVariableDeclarator()&&r.node.init===t.node&&Ve.isIdentifier(r.node.id)&&n_.test(r.node.id.name))}return t!==null}function pg(e){return e==="src"||e==="srcset"||e==="url"||e==="thumbnail_url"}function su(e,t=0){if(t>=32)return!1;if(e.isArrayExpression())return e.get("elements").some(r=>r.node!==null&&(r.isObjectExpression()||r.isArrayExpression()?su(r,t+1):!0));let n=!1;for(let r of e.get("properties")){if(!r.isObjectProperty()&&!r.isObjectMethod())return!1;let o=ra(r);if(!o.known)return!0;let i=o.name;if(r.isObjectMethod()&&r.node.kind==="method")continue;if(i!==null&&(to.has(i)||pg(i))){n=!0;continue}if(r.isObjectMethod())continue;let s=r.get("value");(s.isObjectExpression()||s.isArrayExpression())&&su(s,t+1)&&(n=!0)}return n}function Ai(e){return e?Ve.isStringLiteral(e)?{value:e.value,complete:!0}:Ve.isJSXExpressionContainer(e)?Ai(e.expression):Ve.isTemplateLiteral(e)&&e.expressions.length===0?{value:e.quasis.map(t=>t.value.cooked??t.value.raw).join(""),complete:!0}:Ve.isTSAsExpression(e)||Ve.isTSTypeAssertion(e)||Ve.isParenthesizedExpression(e)?Ai(e.expression):{value:null,complete:!1}:{value:null,complete:!1}}function iu(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 iu(e.get("expression"),n);if(e.isIdentifier()){let r=e.scope.getBinding(e.node.name);return!r?.constant||r.kind!=="const"||!r.path.isVariableDeclarator()||!Ve.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}:iu(r.path.get("init"),n)}return Ai(e.node)}function t_(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 V$(e,t){return e.slice(t.start_offset,t.end_offset)}function K$(e){return`sha256:${T$("sha256").update(e).digest("hex")}`}function J$(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 X$(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 i_=512,Z$=1024*1024,q$=8*1024*1024,s_=256;function Q$(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||a_(e.snapshot_files)!==e.snapshot_digest||!Number.isSafeInteger(e.occurrence)||e.occurrence<0||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset%o_!==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>W$||e.offset>=a.byteLength)return t();let l=eU(s,a);if(!l)return t();let c=Buffer.from(a);return{complete:!0,snapshot_digest:e.snapshot_digest,file_path:e.file_path,occurrence:e.occurrence,path:s,mime_type:l,byte_size:c.byteLength,digest_sha256:du("sha256").update(c).digest("hex"),offset:e.offset,data_base64:c.subarray(e.offset,e.offset+o_).toString("base64")}}function eU(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===mg.path&&t.byteLength===mg.byte_size&&du("sha256").update(t).digest("hex")===mg.digest_sha256?"image/svg+xml":null}async function tU(e){if(e.snapshot.site_id!==e.site_id||e.snapshot.snapshot_id!==e.base_snapshot_id)return on("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=G$.safeParse(e.target),l=z$.safeParse(e.selection_ref);if(!a.success||!l.success)return on("BLOCK_SELECTION_INVALID","<selection>","The block target or render occurrence is invalid.");let c=a.data,u=l.data,d=cu(o,t,n,r);if(d)return d;let f=H$.safeParse(e.host_capabilities);if(!f.success)return on("HOST_CAPABILITIES_INVALID","<host-capabilities>","The host capability contract is invalid.");let g=new Map;for(let[$,ae]of e.snapshot.files){if(typeof ae!="string"&&!(ae instanceof Uint8Array))return on("SNAPSHOT_CONTENT_MISMATCH",$,"A Snapshot file has an unsupported content type.");g.set($,typeof ae=="string"?ae:new Uint8Array(ae))}if(!rU(e.snapshot.manifest,t,n,g))return on("SNAPSHOT_CONTENT_MISMATCH","<snapshot>","The file mapping does not match the authenticated Snapshot manifest.");let m=a_(g),p=await mm({site_id:t,base_snapshot_id:n,composition:c.composition,document_version:r,target:c,selection_ref:u,files:g});if(!p.ok)return on(`BLOCK_${p.code}`,c.blockKey,p.message);if(!p.binding.descriptor.capabilities.save)return on("BLOCK_EXPORT_NOT_ALLOWED",c.blockKey,"The selected block is not exportable.");let h=wk({binding:p.binding,files:g,hostCapabilities:f.data}),x;if(!h.complete){let $=lu(h.errors.map(({code:kt,path:Un,message:ia})=>({code:kt,path:Un,message:ia})));if(!h.errors.some(kt=>kt.code==="INVOCATION_VALUE_UNRESOLVED"))return $;let ae=_i(g,i)?GI({binding:p.binding,target:c,files:g,trusted_host_file_hashes:i}):null,he=ae?.complete?[]:await Xk({binding:p.binding,files:g}),Le=cu(o,t,n,r);if(Le)return Le;if(!ae?.complete)return he.length?{...$,cms_candidates:{kind:"partial-unproven",slugs:he}}:$;h={complete:!0,selection:ae.selection},x=ae.extracted}let E=x??_m({selection:h.selection,files:g});if(!E.complete)return lu(E.errors.map(({code:$,path:ae,message:he})=>({code:$,path:ae,message:he})));let b=new Map(g);for(let $ of E.source_files){let ae=b.get($.path);if(ae!==void 0&&!nU(ae,$.content))return on("SOURCE_COLLISION",$.path,"An extracted entry conflicts with the pinned Snapshot.");b.set($.path,$.content)}let S=ar({entry_files:[E.entry_file],files:b,max_nodes:i_}),v=S.nodes.filter($=>gg($.path)&&i.get($.path)===uu(b.get($.path))).map($=>$.path),P=Ml({closure:S,host_capabilities:f.data,platform_managed_paths:v,platform_managed_packages:["server-only"]}),I=$k({files:b,entry_file:E.entry_file,private_paths:P.nodes.filter($=>$.ownership==="private").map($=>$.path)});b=new Map(I.files);let C=ar({entry_files:[E.entry_file],files:b,max_nodes:i_}),N=Ml({closure:C,host_capabilities:f.data,platform_managed_paths:v,platform_managed_packages:["server-only"]}),w=[],L=[],D=qI({entry_file:E.entry_file,entry_export:h.selection.entry_export,files:b,confirmed_slugs:new Set(s.map($=>$.source_slug)),allow_build_sample:UI(b,i),on_host_call:$=>L.push($),on_build_only_value:$=>w.push($)}),U=D.dependencies.length>0,M=[...I.errors.filter($=>C.nodes.some(ae=>ae.path===$.path)),...N.errors.map(({code:$,path:ae,message:he})=>({code:$,path:ae,message:he})),...D.unresolved.map(({code:$,source_path:ae,message:he,call_site:Le})=>({code:$,path:ae,message:he,...Le?{call_site:Le}:{}}))];if(D.complete){let $=new Set(D.dependencies.map(he=>he.slug)),ae=new Set;U&&s.length>0&&s.length!==D.dependencies.length&&M.push({code:"CMS_SCHEMA_DEPENDENCY_UNPROVEN",path:"<cms-schema>",message:"Every selected application requires exactly one matching schema."});for(let he of s){if(ae.has(he.source_slug)||!$.has(he.source_slug)){M.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}ae.add(he.source_slug)}}let G=new Set(v);for(let $ of C.nodes)U&&/^(?:src\/)?lib\/cms\/jsonld\.tsx$/u.test($.path)&&!Kl(b,i,$.path)&&M.push({code:"HOST_CMS_IMPLEMENTATION_UNPROVEN",path:$.path,message:"A modified CMS helper cannot be omitted from the exported code dependencies."}),gg($.path)&&!G.has($.path)&&M.push({code:"HOST_CMS_IMPLEMENTATION_UNPROVEN",path:$.path,message:"A CMS host implementation requires trusted matching provenance regardless of its declared ownership."});for(let $ of N.nodes)$.kind==="external"||$.ownership!=="host-public"||gg($.path)||i.get($.path)!==uu(g.get($.path))&&M.push({code:"HOST_IMPLEMENTATION_UNPROVEN",path:$.path,message:"A host-public source requires trusted matching provenance before it may be omitted from the export."});let K=[];for(let $ of N.nodes){if($.kind!=="source"||!["host-public","platform-managed"].includes($.ownership))continue;let ae=yt(b.get($.path)),he=ae===null?null:au({file_path:$.path,source:ae});if(!he||he.references.length>0||he.errors.length>0){let Le=$.ownership==="host-public"&&h.selection.entry_export.kind==="default"?Kk({entry_file:E.entry_file,host_file:$.path,files:b,closure:C,trusted_host_file_hashes:i,...D.complete?{selected_host_calls:L}:{}}):{complete:!1};if(Le.complete){K.push(...Le.references);continue}M.push({code:"HOST_MEDIA_DEPENDENCY_UNPROVEN",path:$.path,message:"The omitted host source has media that cannot yet be bound to this archive."})}}let ge=new Map(N.nodes.map($=>[$.path,$.ownership])),oe=[];for(let $ of C.nodes){if(ge.get($.path)!=="private")continue;let ae=b.get($.path),he=null;try{typeof ae=="string"?he=ae:ae instanceof Uint8Array&&(he=new TextDecoder("utf-8",{fatal:!0}).decode(ae))}catch{}he===null?M.push({code:"SOURCE_TEXT_UNSUPPORTED",path:$.path,message:"A private source dependency is not valid UTF-8 text."}):oe.push({path:$.path,content:he})}for(let $ of oe)(/^(?:src\/)?components\/site\/generated\/(?:forms|product-search)\//u.test($.path)||$.path==="lib/generated/product-search-config.json")&&M.push({code:"MANAGED_REQUIREMENT_UNPROVEN",path:$.path,message:"A managed capability requires a proven requirement before exporting the block."});oe.some($=>$.path===E.entry_file)||M.push({code:"ENTRY_NOT_PRIVATE",path:E.entry_file,message:"The selected entry is not site-owned source."});let Me=0,He=new Map(oe.map($=>[$.path,$.content])),pt=[];for(let $ of oe){let ae=Buffer.byteLength($.content,"utf8");if(Me+=ae,(ae>Z$||Me>q$)&&M.push({code:"SOURCE_BUDGET_EXCEEDED",path:$.path,message:"The selected source exceeds its export byte budget."}),/\.[cm]?[jt]sx?$/iu.test($.path)){let he=au({file_path:$.path,source:$.content,static_only:U,files:He});pt.push(...he.references.filter(Le=>!D.complete||!w.some(kt=>kt.file_path===$.path&&kt.source_hash===uu($.content)&&kt.start<=Le.source_range.start_offset&&kt.end>=Le.source_range.end_offset))),M.push(...he.errors.map(({code:Le,file_path:kt,message:Un})=>({code:Le,path:kt,message:Un})))}}for(let $ of K){let he=pt.filter(Le=>Le.file_path===$.file_path).reduce((Le,kt)=>Math.max(Le,kt.occurrence+1),0);pt.push({...$,occurrence:he})}let xe=new Map;if(D.complete){let $=new Map(oe.map(he=>[he.path,he.content]));for(let he of N.nodes){if(he.kind!=="source"||!["host-public","platform-managed"].includes(he.ownership))continue;let Le=b.get(he.path);try{if(typeof Le=="string")$.set(he.path,Le);else if(Le instanceof Uint8Array)$.set(he.path,new TextDecoder("utf-8",{fatal:!0}).decode(Le));else throw new Error("missing source")}catch{D.dependencies.length===0&&M.push({code:"ROUTE_SOURCE_UNAVAILABLE",path:he.path,message:"A host source cannot be inspected for navigation."})}}let ae=Wk({sources:$,files:b});for(let[he,Le]of $){if(!/\.[cm]?[jt]sx?$/iu.test(he))continue;let kt=Gk({file_path:he,source:Le,current_route:c.composition.routeId,allow_props_forwarding:he!==E.entry_file&&ae.has(he)});D.dependencies.length===0&&M.push(...kt.errors);for(let Un of kt.dependencies)xe.set(Un.href,Un)}xe.size>256&&D.dependencies.length===0&&M.push({code:"ROUTE_BUDGET_EXCEEDED",path:"<routes>",message:"The selected source exceeds its route dependency limit."})}let st=D.complete&&D.dependencies.length>0&&s.length===D.dependencies.length&&new Set(s.map($=>$.source_slug)).size===s.length&&D.dependencies.every($=>s.some(ae=>ae.source_slug===$.slug)&&$.evidence.every(ae=>["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"].includes(ae.operation)))&&_i(b,i);if(M.length>0||!C.complete||!N.complete||!D.complete){let $=[...new Set([...D.dependencies.map(Le=>Le.slug)])].sort();if(!($.length>0&&$.length<=16&&new Set($).size===$.length&&$.every(Le=>/^[a-z0-9][a-z0-9_-]{0,123}$/u.test(Le))))return lu(M);let he=cu(o,t,n,r);return he||{...lu(M),cms_candidates:{kind:"partial-unproven",slugs:$}}}let Je=cu(o,t,n,r);if(Je)return Je;let pe={complete:!0,site_id:t,base_snapshot_id:n,snapshot_digest:m,document_version:r,target:h.selection.target,selection_ref:E.selected_root_ref,entry:{file:E.entry_file,export:h.selection.entry_export},files:oe.map(({path:$,content:ae})=>({path:$,content:ae})),source_closure:C,dependency_audit:N,cms:D,media:pt,invocation_bindings:E.invocation_bindings,host_contract_digest:f.data.host_contract_digest,...D.dependencies.length===0?{route_dependencies:[...xe.values()].sort(($,ae)=>$.href.localeCompare(ae.href))}:{},...st?{cms_sample_proof:{kind:"whole-application"}}:{}};return Y$.safeParse(pe).success?pe:on("PORTABLE_EXPORT_RESULT_INVALID","<export>","The selected source result failed its bounded export contract.")}function cu(e,t,n,r){if(!Number.isSafeInteger(r)||r<0)return on("DOCUMENT_VERSION_STALE","<document>","The selected document version is invalid.");try{let o=e();return o.site_id!==t||o.snapshot_id!==n?on("SNAPSHOT_MISMATCH","<snapshot>","The live runtime no longer matches the requested Snapshot."):o.document_version!==r?on("DOCUMENT_VERSION_STALE","<document>","The live document version changed during export."):null}catch{return on("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live runtime identity could not be verified.")}}function a_(e){let t=du("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 nU(e,t){return typeof e=="string"?e===t:Buffer.from(e).equals(Buffer.from(t,"utf8"))}function gg(e){return/^(?:src\/)?lib\/cms(?:\.[cm]?[jt]sx?$|\/(?!generated\/))/u.test(e)}function uu(e){return e===void 0?null:`sha256:${du("sha256").update(e).digest("hex")}`}function rU(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||uu(s)!==i.hash||(typeof s=="string"?Buffer.byteLength(s,"utf8"):s.byteLength)!==i.size_bytes)return!1}return!0}function on(e,t,n){return{complete:!1,unresolved:[{code:e,path:t,message:n}]}}function lu(e){return e.length?e.length<=s_?{complete:!1,unresolved:e}:{complete:!1,unresolved:[...e.slice(0,s_-1),{code:"PORTABLE_DIAGNOSTICS_TRUNCATED",path:"<selection>",message:"Additional unresolved export diagnostics were omitted."}]}:on("PORTABLE_EXPORT_INCOMPLETE","<selection>","The selected block's export proof is incomplete.")}import hg from"@babel/generator";import{parse as oU}from"@babel/parser";import iU from"@babel/traverse";import*as At from"@babel/types";var yg=iU,sU=typeof yg=="function"?yg:yg.default,aU=typeof hg=="function"?hg:hg.default,p_="components/site/generated/{{$INSTANCE}}/",m_=new Set([".tsx",".ts",".jsx",".js"]),c_=new Set(["data-site-block-id","data-vcp-block-id","data-vcp-edit-key"]),cU=new Set(["data-site-block-order","data-vcp-order"]);function lU(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=vr(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=vr(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=vr(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:yU(b)})),l=new Map(a.map(b=>[b.source_path,b.path_template])),c=uU(e.source_mapping??[],l,t),u=dU(e.required_source_paths??[],l,t),d=[],f=new Map,g=[];for(let b of s){let S=n.get(b);if(!S)continue;let v=pU(b,S.content,r,l,d,f,t);v!==null&&g.push({path_template:l.get(b),content:v,...S.role?{role:S.role}:{}})}let m=d_(t).sort(f_);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(b=>{let S=a.find(P=>P.path_template===b.path_template)?.source_path,v=n.get(S)?.content??"";return{source_path:S,path_template:b.path_template,original_byte_size:l_(v),output_byte_size:l_(b.content),original_line_count:u_(v),output_line_count:u_(b.content)}}),h=[...f.values()].map(b=>({...b,normalized:!0})).sort((b,S)=>b.source_path.localeCompare(S.source_path)),x=l.get(o)??null;if(e.thin_entry_plan){let b=fU(e.thin_entry_plan,l,t);b&&(g.push(b),x=b.path_template)}let E=d_(t).sort(f_);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:p.sort((b,S)=>b.path_template.localeCompare(S.path_template)),required_path_mappings:u,source_mapping:c,managed_rebindings:d.sort(vU),block_metadata:h,errors:[]}}function uU(e,t,n){let r=new Set,o=[];for(let[i,s]of e.entries()){let a=vr(s.generated_path),l=vr(s.source_file),c=a,u=t.get(a);if(!a||a!==s.generated_path||!l||l!==s.source_file||!s.structural_path||r.has(c)){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(c),!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 dU(e,t,n){let r=new Set,o=new Set,i=[];for(let[s,a]of e.entries()){let l=vr(a.source_path);if(!/^[a-z][a-z0-9-]{0,127}$/u.test(a.key)||!l||r.has(a.key)||o.has(l)){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(l);let c=t.get(l);if(!c){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:l,path_template:c})}return i.sort((s,a)=>s.key.localeCompare(a.key)||s.source_path.localeCompare(a.source_path))}function fU(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(vr(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=`${p_}__managed-root-entry.tsx`,i=g_(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],Jk=p$.body.body;function Gk(e,t,n){let r;try{r=Wk(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let o=[];f$(r,{ExportDefaultDeclaration(p){let h=p.get("declaration");(h.isFunctionDeclaration()||h.isFunctionExpression()||h.isArrowFunctionExpression())&&o.push(h)}});let i=o.length===1?o[0]:void 0;if(!i||!Le.isBlockStatement(i.node.body))return null;let s=i.node.body.body,a=Hk(i.node,p=>Le.isCallExpression(p)&&Xk(p,"listStrict",n));if(a.length!==1||a[0].arguments.length!==2)return null;let l=a[0],c=s.findIndex(p=>zk(p,l));if(c<0)return null;let u=l.arguments[1];if(!Le.isObjectExpression(u))return null;let d=new Map;for(let p of u.properties){if(!Le.isObjectProperty(p)||p.computed)return null;let h=Le.isIdentifier(p.key)?p.key.name:Le.isStringLiteral(p.key)?p.key.value:null;if(!h||!["page","pageSize","category"].includes(h)||d.has(h)||!Le.isExpression(p.value))return null;d.set(h,p.value)}let f=d.get("page"),m=d.get("pageSize");if(!f||!Le.isNumericLiteral(m)||!Number.isSafeInteger(m.value)||m.value<1||m.value>100)return null;let g=Hk(i.node,p=>Le.isCallExpression(p)&&Xk(p,"categories",n));return d.has("category")?!Le.isIdentifier(f,{name:"page"})||!Le.isIdentifier(d.get("category"),{name:"category"})||g.length!==1||g[0].arguments.length!==1||!zk(s[c+1],g[0])||!g$(i,s.slice(0,c))?null:{paginate:!0,limit:m.value}:g.length||!m$(f,s.slice(0,c),i)?null:{paginate:!1,limit:m.value}}function Xk(e,t,n){let r=e.callee;return Le.isMemberExpression(r)&&!r.computed&&Le.isIdentifier(r.property,{name:t})&&Le.isMemberExpression(r.object)&&!r.object.computed&&Le.isIdentifier(r.object.property,{name:"collections"})&&Le.isIdentifier(r.object.object,{name:"cms"})&&Le.isStringLiteral(e.arguments[0],{value:n})}function zk(e,t){return!!(Le.isVariableDeclaration(e,{kind:"const"})&&e.declarations.length===1&&Le.isIdentifier(e.declarations[0].id)&&Le.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(Le.isNumericLiteral(e,{value:1}))return t.length===0;if(!Le.isIdentifier(e)||t.length!==1)return!1;let o=t[0];if(!Le.isVariableDeclaration(o,{kind:"const"})||o.declarations.length!==1)return!1;let i=o.declarations[0],s=n.scope.getBinding(e.name);return!!(Le.isIdentifier(i.id,{name:e.name})&&Le.isNumericLiteral(i.init,{value:1})&&s?.identifier===i.id&&s.constant)}function g$(e,t){if(t.length!==Jk.length||!t.every((u,d)=>Le.isNodesEquivalent(u,Jk[d]))||e.scope.getBinding("Number")||e.scope.getBinding("undefined"))return!1;let n=e.node.params[0];if(!Le.isObjectPattern(n)||n.properties.length!==1||!Le.isObjectProperty(n.properties[0])||n.properties[0].computed||!Le.isIdentifier(n.properties[0].key,{name:"searchParams"})||!Le.isIdentifier(n.properties[0].value,{name:"searchParams"}))return!1;let r=t.map(u=>Le.isVariableDeclaration(u)?u.declarations[0]:void 0),[o,i,s,a]=r;if(!o?.init||!i?.init||!s?.init||!a?.init)return!1;let l=["sp","pageValue","page","category"].map(u=>e.scope.getBinding(u));if(l.some((u,d)=>!u?.constant||u.identifier!==r[d]?.id))return!1;let c=e.scope.getBinding("searchParams");return!(!c?.constant||c.identifier!==n.properties[0].value||!hg(c.referencePaths,[o.init])||!hg(l[0].referencePaths,[i.init,a.init])||!hg(l[1].referencePaths,[s.init]))}function hg(e,t){return e.every(n=>!!n.findParent(r=>t.includes(r.node)))}function Hk(e,t){let n=[],r=o=>{if(!(o!==e&&Le.isFunction(o))){t(o)&&n.push(o);for(let i of Le.VISITOR_KEYS[o.type]??[]){let s=o[i];if(Array.isArray(s))for(let a of s)Le.isNode(a)&&r(a);else Le.isNode(s)&&r(s)}}};return r(e),n}var y$=new Set(["blockId","block_id","targetBlockId","target_block_id","sourceBlockId","source_block_id"]),x$=new Set(["data-vcp-block-id","data-vcp-edit-key"]),b$=new Set(["data-vcp-order","sourceOrder","source_order"]);function Wi(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(Ra)}),n;try{n=xg(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=R$(n),o=dr(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=[],l=0;if(Tu(n,new Set,(f,m)=>{if(!oe.isJSXElement(f))return;let g=f.openingElement,p=g.start;if(typeof p!="number"||e.call_source_range&&(g.loc?.start.line!==e.call_source_range.start_line||g.loc.start.column!==e.call_source_range.start_column))return;let h=r_(g.name);if(!h)return;let x=A$(g.name,r);x&&(e.target.local_name&&e.target.local_name!==h||x.source!==e.target.source||x.export_name!==e.target.export_name||s.has(p)&&a.push({node:g,element:f,local:x,context:m,ordinal:l++}))}),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 c=a.map(f=>e_(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=t_(c,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:Eg(d).sort(Ra)}}function Qk(e){let t=a=>({complete:!1,entry_file:e.file_path,target:e.target,call:null,bindings:[],original_block_id:null,original_order:null,semantic_props:{},errors:[...a].sort(Ra)}),n;try{n=xg(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(Tu(n,new Set,(a,l)=>{if(!oe.isJSXElement(a))return;let c=a.openingElement;if(typeof c.start!="number"||r_(c.name)!==e.target.local_name)return;let u=o++;e.call_source_range&&(c.loc?.start.line!==e.call_source_range.start_line||c.loc.start.column!==e.call_source_range.start_column)||r.push({node:c,element:a,context:l,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=>e_(e,a.node,a.element,{kind:"local",local_name:e.target.local_name},a.context,a.ordinal)),s=t_(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:Eg(s.errors).sort(Ra)}: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 E$(e){let t;try{t=xg(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=Hn({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=dr(e.source,{filePath:e.file_path,exportName:"default"});if(i.components.length===0)return{invocation:null,errors:[]};let s=i.components.map(a=>Wi({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 S$(e){let t=Wi(e),n=v$(e.files),r=k$(e.file_path,e.target.source,n),o=r?Ft(n.get(r)):null,i=r&&typeof o=="string"?Gk(o,r,e.collection.slug):null,s=fg({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],l=[];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:I$(f.code),path:f.path,message:f.message});t.call&&l.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 c=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{l.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(m=>m.propName==="searchParams"&&m.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})}c&&r!==c.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(c&&i&&a.length===0){let f={source_slug:c.source_slug,list_mode:i.paginate?"page":"embedded",paginate:i.paginate,...i.paginate?{page_size:i.limit}:{top_n:i.limit},detail_prefix:c.detail_prefix,schema:c.schema.map(g=>({...g})),list_view:{...c.list_view},detail_view:{...c.detail_view},...c.title?{title:c.title}:{},...c.breadcrumb?{breadcrumb:{...c.breadcrumb}}:{},...c.required_fields?{required_fields:[...c.required_fields]}:{},...c.force_multi_media?{force_multi_media:[...c.force_multi_media]}:{},list_route_required:i.paginate},m=h$.safeParse(f);m.success?(u=m.data,l.push({fact:"detail-route",path:e.collection.detail_entry_file,reason:`The rendered detail consumer proves literal prefix ${c.detail_prefix}.`},{fact:"list-view",path:c.list_view.source_path,reason:`The list container renders ${c.list_view.export_name} with ${c.list_view.interface_name}.`},{fact:"detail-view",path:c.detail_view.source_path,reason:`The detail route renders ${c.detail_view.export_name} with ${c.detail_view.interface_name}.`},{fact:"schema",path:c.schema_evidence_path,reason:"The complete CMS schema is supplied by the trusted application projection."})):a.push({code:"COLLECTION_RECIPE_INVALID",path:`collection-recipe:${c.source_slug}`,message:m.error.issues[0]?.message??"Observed collection facts do not satisfy the portable recipe contract."})}let d=Eg(a).sort(Ra);return{...t,complete:d.length===0&&u!==null,errors:d,collection_recipe:u,collection_evidence:l.sort(C$),related_entries:s}}function I$(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 v$(e){return e instanceof Map?e:new Map(Object.entries(e))}function k$(e,t,n){if(!kt(t))return null;let r=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",o=t.startsWith("@/")?t.slice(2):_$(`${r}/${t}`);return[o,`${o}.tsx`,`${o}.ts`,`${o}.jsx`,`${o}.js`,`${o}/index.tsx`,`${o}/index.ts`,`${o}/index.jsx`,`${o}/index.js`].find(i=>n.has(i))??null}function _$(e){let t=[];for(let n of e.split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return t.join("/")}function C$(e,t){return e.fact.localeCompare(t.fact)||e.path.localeCompare(t.path)}function R$(e){let t=new Map;for(let n of e.program.body){if(!oe.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(oe.isIdentifier(o.local)){if(oe.isImportDefaultSpecifier(o))t.set(o.local.name,{source:r,export_name:"default",local_name:o.local.name});else if(oe.isImportNamespaceSpecifier(o))t.set(o.local.name,{source:r,export_name:"*",local_name:o.local.name});else if(oe.isImportSpecifier(o)){let i=oe.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 e_(e,t,n,r,o,i){let s=O$(t),a=[],l=[],c={},u=new Set,d=null,f=null,m=(p,h)=>{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),l.push({propName:p,value:h}),(p==="type"||p==="variant")&&h.kind==="json-literal"&&(c[p]=h.value)};for(let p of t.attributes){if(oe.isJSXSpreadAttribute(p)){let S=Eo(p.argument);if(!S.ok||!n_(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,A]of Object.entries(S.value)){if(!Zk(v)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${v}`,message:`Portable invocation cannot encode prop ${v}.`,source_range:s});continue}m(v,yg(A))}continue}let h=T$(p.name);if(!h)continue;let x=p.value,b=x&&oe.isJSXExpressionContainer(x)?x.expression:null;if(x$.has(h)){let S=x?Au(x):{ok:!0,value:!0};!S.ok||typeof S.value!="string"?a.push({code:"INVOCATION_BLOCK_ID_UNRESOLVED",path:`${e.file_path}:${h}`,message:"Portable invocation requires a literal original block identity.",source_range:s}):d=S.value;continue}if(b$.has(h)){let S=x?Au(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}:${h}`,message:"Portable invocation requires a literal original order.",source_range:s}):f=S.value;continue}if(!Zk(h)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${h}`,message:`Portable invocation cannot encode prop ${h}.`,source_range:s});continue}if(y$.has(h)){let S=x?Au(x):{ok:!0,value:!0};S.ok&&typeof S.value=="string"?d=S.value:b&&Yk(b,o)&&a.push({code:"INVOCATION_BLOCK_ID_UNRESOLVED",path:`${e.file_path}:${h}`,message:"A target block identity cannot be supplied by route search params.",source_range:s}),m(h,{kind:"target-block-id"});continue}if(b&&Yk(b,o)){m(h,{kind:"route-search-params"});continue}let E=x?Au(x):{ok:!0,value:!0};if(!E.ok){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${h}`,message:`Portable invocation cannot prove a JSON-literal value for ${h}.`,source_range:s});continue}m(h,yg(E.value))}let g=P$(n);return g.ok?g.value!==void 0&&m("children",yg(g.value)):a.push({code:"INVOCATION_CHILDREN_UNRESOLVED",path:`${e.file_path}:children`,message:g.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:l,original_block_id:d??e.target.original_block_id??null,original_order:f,semantic_props:c,errors:a}}function t_(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 Au(e){return e===null?{ok:!0,value:!0}:oe.isStringLiteral(e)?{ok:!0,value:e.value}:oe.isJSXExpressionContainer(e)?Eo(e.expression):{ok:!1}}function Eo(e){if(!e)return{ok:!1};if(oe.isStringLiteral(e))return{ok:!0,value:e.value};if(oe.isNumericLiteral(e)&&Number.isFinite(e.value))return{ok:!0,value:e.value};if(oe.isBooleanLiteral(e))return{ok:!0,value:e.value};if(oe.isNullLiteral(e))return{ok:!0,value:null};if(oe.isTemplateLiteral(e)&&e.expressions.length===0)return{ok:!0,value:e.quasis[0]?.value.cooked??""};if(oe.isTSAsExpression(e)||oe.isTSTypeAssertion(e)||oe.isTSNonNullExpression(e))return Eo(e.expression);if(oe.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(oe.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(oe.isObjectExpression(e)){let t={};for(let n of e.properties){if(oe.isSpreadElement(n)){let i=Eo(n.argument);if(!i.ok||!n_(i.value))return{ok:!1};Object.assign(t,i.value);continue}if(!oe.isObjectProperty(n)||n.computed)return{ok:!1};let r=w$(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 P$(e){if(e.children.length===0)return{ok:!0,value:void 0};let t=[];for(let n of oe.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 Tu(e,t,n){let r=o_(e)?new Set([...t,...N$(e)]):t;n(e,{names:r});for(let o of Object.values(e))if(Array.isArray(o))for(let i of o)qk(i)&&Tu(i,r,n);else qk(o)&&Tu(o,r,n)}function N$(e){if(!o_(e))return[];let t=[];for(let n of e.params)Ca(n,t);return t}function Ca(e,t){if(oe.isIdentifier(e)){t.push(e.name);return}if(oe.isAssignmentPattern(e)){Ca(e.left,t);return}if(oe.isObjectPattern(e)){for(let n of e.properties)oe.isRestElement(n)?Ca(n.argument,t):oe.isObjectProperty(n)&&Ca(n.value,t);return}if(oe.isArrayPattern(e))for(let n of e.elements)n&&Ca(n,t)}function Yk(e,t){return oe.isIdentifier(e)?e.name==="searchParams"&&t.names.has(e.name):oe.isMemberExpression(e)&&!e.computed&&oe.isIdentifier(e.property)&&e.property.name==="searchParams"&&oe.isIdentifier(e.object)&&t.names.has(e.object.name)}function yg(e){return{kind:"json-literal",value:e}}function n_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zk(e){return/^[A-Za-z][A-Za-z0-9_]{0,127}$/u.test(e)}function r_(e){if(oe.isJSXIdentifier(e))return e.name;if(!oe.isJSXMemberExpression(e))return null;let t=bg(e.object);return t?`${t}.${e.property.name}`:null}function bg(e){if(oe.isJSXIdentifier(e))return e.name;if(!oe.isJSXMemberExpression(e))return null;let t=bg(e.object);return t?`${t}.${e.property.name}`:null}function A$(e,t){if(oe.isJSXIdentifier(e))return t.get(e.name)??null;if(!oe.isJSXMemberExpression(e))return null;let n=bg(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 T$(e){return oe.isJSXIdentifier(e)?e.name:oe.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function w$(e){return oe.isIdentifier(e)?e.name:oe.isStringLiteral(e)||oe.isNumericLiteral(e)?String(e.value):null}function o_(e){return oe.isFunctionDeclaration(e)||oe.isFunctionExpression(e)||oe.isArrowFunctionExpression(e)}function qk(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function O$(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 Eg(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function Ra(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var D$=typeof Ig=="function"?Ig:Ig.default,vg=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=wu(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=Te(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 M$(e){return a_(e,!1)}function s_(e){return a_(e,!0)}function a_(e,t){let{binding:n,files:r}=e;if(e.hostCapabilities!==null&&!L$.safeParse(e.hostCapabilities).success)return wt("INVOCATION_VALUE_UNRESOLVED","generated-site-capabilities","Trusted host capabilities failed their strict schema.");if(!Pa(n.descriptor.source.file)||!Pa(n.ownerFile))return wt("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The resolved block source path is not a safe Snapshot source path.");let o=wu(r,n.descriptor.source.file),i=wu(r,n.ownerFile);if(o===null||i===null)return wt("INVOCATION_TARGET_NOT_RENDERED",o===null?n.descriptor.source.file:n.ownerFile,"The resolved block or owner source is missing or is not valid UTF-8 text.");if(je(o)!==n.descriptor.source.contentHash||je(o)!==n.sourceHash||je(i)!==n.ownerSourceHash)return wt("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The pinned block or owner source hash no longer matches the resolved binding.");let s=Te(n.descriptor.source.file,o);if(!s.ok)return wt("INVOCATION_PARSE_FAILED",n.descriptor.source.file,s.diagnostic.message);let a=Ou(s.module.ast,n.rootLocator.sourceRange);if(a.length!==1)return wt("INVOCATION_TARGET_AMBIGUOUS",n.descriptor.source.file,"The selected block source range does not identify exactly one JSX element.");let l=a[0],c=l_(l.node);if(!c)return wt("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 vg(r),m=B$(e,c,f,t);if(m)return m;if(d.some(x=>(x.alternativeLocators?.length??0)>1))return wt("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The conditional invocation has no single statically proven props binding.");for(let[x,b]of d.entries()){let E=wu(r,b.sourceFile);if(E===null||!Pa(b.sourceFile))return wt("INVOCATION_TARGET_NOT_RENDERED",b.sourceFile,"A statically proven call-chain source is missing from the fixed Snapshot map.");let S=Te(b.sourceFile,E);if(!S.ok)return wt("INVOCATION_PARSE_FAILED",b.sourceFile,S.diagnostic.message);let v=Ou(S.module.ast,b.callLocator.sourceRange);if(v.length!==1)return wt("INVOCATION_TARGET_AMBIGUOUS",b.sourceFile,"A call-chain locator does not identify exactly one current JSX element.");let A=d[x+1]?.sourceFile??n.descriptor.source.file,I=d[x+1]?.callLocator.sourceRange??n.rootLocator.sourceRange,_=lr({module:S.module,componentName:b.component,callSourceRange:b.callLocator.sourceRange});if(_.ok){if(_.sourceFile!==A)return wt("INVOCATION_TARGET_NOT_RENDERED",b.sourceFile,"The selected local component does not resolve to the source definition proven by the block graph.");if(_.roots.filter(xe=>Gi(xe.node,I)).length!==1)return wt("INVOCATION_TARGET_NOT_RENDERED",_.sourceFile,"The local component definition does not select exactly one proven JSX root.");let Ee=Qk({file_path:b.sourceFile,source:E,target:{kind:"local",local_name:b.component},call_source_range:{start_line:b.callLocator.sourceRange.startLine,start_column:b.callLocator.sourceRange.startColumn}});if(!Ee.call||!Ee.complete)return{complete:!1,errors:Ee.errors.length>0?Ee.errors:[{code:"INVOCATION_TARGET_NOT_RENDERED",path:b.sourceFile,message:"The selected local call did not produce a complete invocation binding."}]};u.push({kind:"local",call:Ee.call,invocation:Ee,definition:_,entryExport:null});continue}let k=kg(S.module.ast,v[0].node.openingElement.name,b.component,b.exportName);if(!k)return wt("INVOCATION_TARGET_NOT_RENDERED",b.sourceFile,"The statically proven component call no longer resolves through one exact import.");let T=_g(b.sourceFile,k.source,r);if(!T)return wt("INVOCATION_TARGET_NOT_RENDERED",b.sourceFile,"The selected component import is not a resolvable local Snapshot source.");let L=f.read(T);if(!L.ok)return wt(L.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",T,L.message);let $=En({module:L.module,exportName:k.exportName,parsedModules:f});if(!$.ok)return wt("INVOCATION_TARGET_NOT_RENDERED",$.diagnostic.file,$.diagnostic.message);if($.sourceFile!==A)return wt("INVOCATION_TARGET_NOT_RENDERED",b.sourceFile,"The selected component import does not resolve to the source definition proven by the block graph.");let J=$.roots.filter(W=>Gi(W.node,I));if(J.length!==1)return wt("INVOCATION_TARGET_NOT_RENDERED",$.sourceFile,"The unique component export does not select exactly one proven JSX root.");let z=null;if(x===d.length-1&&d.length===1&&!d_(n.ownerFile)&&Gi(J[0].node,n.rootLocator.sourceRange)){let W=f.read($.sourceFile);if(!W.ok)return wt(W.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",$.sourceFile,W.message);if(z=c_(W.module,$.componentName,k.exportName),!z)return wt("INVOCATION_TARGET_AMBIGUOUS",$.sourceFile,"The proven component definition has no unique final export for a Portable entry.")}let Z=Wi({file_path:b.sourceFile,source:E,target:{source:k.source,export_name:k.exportName,local_name:k.localName},call_source_range:{start_line:b.callLocator.sourceRange.startLine,start_column:b.callLocator.sourceRange.startColumn}});if(!Z.call||!Z.complete)return{complete:!1,errors:Z.errors.length>0?Z.errors:[{code:"INVOCATION_TARGET_NOT_RENDERED",path:b.sourceFile,message:"The selected call did not produce a complete invocation binding."}]};u.push({kind:"import",call:Z.call,invocation:Z,definition:$,entryExport:z})}let g={kind:"page-block",composition:u_(n.composition),blockKey:n.blockKey},p=j$(n,l,u,r,e.hostCapabilities);if(!p.ok)return{complete:!1,errors:[p.error]};let h=u[0]?.invocation??null;return{complete:!0,selection:{target:g,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:c,owner:n.descriptor.owner,call_chain:u.map(({call:x})=>x),strategy:p.strategy,entry_file:p.entryFile,entry_export:p.entryExport,invocation:h}}}function B$(e,t,n,r){let{binding:o,files:i}=e,s=o.root.callChain;if(s.length!==2)return null;let[a,l]=s;if(!a||!l||(a.alternativeLocators?.length??0)>1)return null;let c=n.get(a.sourceFile);if(!c)return null;let u=Ou(c.ast,a.callLocator.sourceRange);if(u.length!==1)return null;let d=kg(c.ast,u[0].node.openingElement.name,a.component,a.exportName);if(!d)return null;let f=_g(a.sourceFile,d.source,i),m=f?n.get(f):void 0;if(!m)return null;let g=En({module:m,exportName:d.exportName,parsedModules:n});if(!g.ok||g.sourceFile!==l.sourceFile)return null;let p=n.get(g.sourceFile);if(!p||c_(p,g.componentName,"default")?.kind!=="default")return null;let h={files:i,list_entry_file:a.sourceFile,selected_component_source:`@/${g.sourceFile.replace(/\.[cm]?[jt]sx?$/u,"")}`};if(r){if(!wk(h))return null}else{let A=dg(h);if(!A.complete||!A.relation)return null}let x=l.alternativeLocators?.length?l.alternativeLocators:[l.callLocator],b=g.returnAlternatives?.length?g.returnAlternatives:g.roots;if(b.length!==x.length||!b.every(A=>x.filter(I=>Gi(A.node,I.sourceRange)).length===1))return null;for(let A of x){let I=Ou(p.ast,A.sourceRange);if(I.length!==1)return null;let _=kg(p.ast,I[0].node.openingElement.name,l.component,l.exportName);if(!_)return null;let k=_g(g.sourceFile,_.source,i),T=k?n.get(k):void 0;if(!T)return null;let L=En({module:T,exportName:_.exportName,parsedModules:n});if(!L.ok||L.sourceFile!==o.descriptor.source.file||L.roots.length!==1||!Gi(L.roots[0].node,o.rootLocator.sourceRange))return null}let E=Wi({file_path:a.sourceFile,source:c.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(!E.complete||!E.call)return{complete:!1,errors:E.errors};let v=`components/site/portable/${i_("sha256").update(JSON.stringify(["collection-container",o.composition,o.blockKey,o.sourceHash,je(p.source)])).digest("hex").slice(0,24)}/page.tsx`;return i.has(v)?wt("INVOCATION_TARGET_AMBIGUOUS",v,"The isolated collection entry collides with a pinned Snapshot source."):{complete:!0,selection:{target:{kind:"page-block",composition:u_(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:[E.call],strategy:"collection-container",collection_container_file:g.sourceFile,entry_file:v,entry_export:{kind:"default"},invocation:E}}}function j$(e,t,n,r,o){let i=n.at(-1);if(i?.kind==="import"){let c=i.definition.roots.length===1&&Gi(i.definition.roots[0].node,e.rootLocator.sourceRange),u=d_(e.ownerFile);if(n.length===1&&c&&u)return{ok:!0,strategy:"managed-thin-entry",entryFile:e.ownerFile,entryExport:{kind:"default"}};if(n.length===1&&c&&i.entryExport)return{ok:!0,strategy:"reuse-entry",entryFile:i.definition.sourceFile,entryExport:i.entryExport}}if(!l_(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 l=`components/site/portable/${i_("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!Pa(l)||r.has(l)?{ok:!1,error:{code:"INVOCATION_TARGET_AMBIGUOUS",path:l,message:"The deterministic in-memory Portable entry path collides with an existing Snapshot file."}}:{ok:!0,strategy:"extract-jsx",entryFile:l,entryExport:{kind:"default"}}}function c_(e,t,n){let r=new Set;for(let i of e.ast.program.body){if(ut.isExportDefaultDeclaration(i)){let s=i.declaration;(ut.isFunctionDeclaration(s)&&(s.id?.name===t||t==="default")||ut.isIdentifier(s)&&s.name===t)&&r.add("default");continue}if(!(!ut.isExportNamedDeclaration(i)||i.exportKind==="type")){if(i.declaration){let s=$$(i.declaration,t);s&&r.add(s)}if(!i.source)for(let s of i.specifiers)ut.isExportSpecifier(s)&&s.exportKind!=="type"&&Rg(s.local)===t&&r.add(Rg(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 $$(e,t){return ut.isFunctionDeclaration(e)?e.id?.name===t?t:null:ut.isVariableDeclaration(e)&&e.declarations.some(n=>ut.isIdentifier(n.id)&&n.id.name===t)?t:null}function kg(e,t,n,r){let o=Cg(t);if(!o||o!==n)return null;let i=ut.isJSXMemberExpression(t)?Cg(t.object):ut.isJSXNamespacedName(t)?t.namespace.name:o,s=ut.isJSXMemberExpression(t)?t.property.name:null;for(let a of e.program.body)if(ut.isImportDeclaration(a))for(let l of a.specifiers){if(ut.isImportDefaultSpecifier(l)&&l.local.name===i)return r==="default"&&!s?{source:a.source.value,exportName:"default",localName:o}:null;if(ut.isImportSpecifier(l)&&l.local.name===i){let c=Rg(l.imported);return c===r&&!s?{source:a.source.value,exportName:c,localName:o}:null}if(ut.isImportNamespaceSpecifier(l)&&l.local.name===i&&s)return s===r?{source:a.source.value,exportName:s,localName:o}:null}return null}function Ou(e,t){let n=[];return D$(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 l_(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 Gi(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 wu(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 _g(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?Sg.posix.normalize(Sg.posix.join(Sg.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=>Pa(i)&&n.has(i))??null}function Cg(e){if(ut.isJSXIdentifier(e))return e.name;if(ut.isJSXMemberExpression(e)){let t=Cg(e.object);return t?`${t}.${e.property.name}`:null}return null}function Rg(e){return ut.isIdentifier(e)?e.name:e.value}function u_(e){return{routeId:e.routeId,...e.effectiveTemplateId!==void 0?{templateId:e.effectiveTemplateId}:{}}}function Pa(e){return F$.safeParse(e).success}function d_(e){return/(?:^|\/)\.vcp\/page-templates\//u.test(e)}function wt(e,t,n){return{complete:!1,errors:[{code:e,path:t,message:n}]}}import{createHash as g_}from"node:crypto";import Ng from"@babel/traverse";import*as Na from"@babel/types";import{rollup as K$,VERSION as J$}from"rollup";import Zi from"typescript";import{PortableInvocationBindingSchema as X$}from"@vcp-dev/contracts";import Pg from"@babel/traverse";import*as Yi from"@babel/types";import{decode as U$}from"@jridgewell/sourcemap-codec";var V$=typeof Pg=="function"?Pg:Pg.default;function f_(e){if(e.file_path.endsWith(".json"))return!0;let t=Te(e.file_path,e.source);if(!t.ok)return!1;let n=!0;return V$(t.module.ast,{Program(r){let o=new Map,i=new Map;for(let[u,d]of Object.entries(r.scope.bindings))i.set(u,d.path);for(let u of r.get("body"))if(u.isExportDefaultDeclaration()){let d=u.get("declaration"),f=d.isIdentifier()?d.node.name:(d.isFunctionDeclaration()||d.isClassDeclaration())&&d.node.id?d.node.id.name:"#default";o.set("default",f),i.has(f)||i.set(f,d)}else if(u.isExportNamedDeclaration()&&!u.node.source&&u.node.exportKind!=="type"){if(u.node.declaration)for(let d of Object.keys(Yi.getOuterBindingIdentifiers(u.node.declaration)))o.set(d,d);for(let d of u.node.specifiers)Yi.isExportSpecifier(d)&&d.exportKind!=="type"&&o.set(Yi.isIdentifier(d.exported)?d.exported.name:d.exported.value,d.local.name)}let s=new Set,a=e.rendered_exports.flatMap(u=>o.has(u)?[o.get(u)]:[]);for(;a.length;){let u=a.pop();if(s.has(u))continue;s.add(u);let d=i.get(u);if(d?.traverse({ReferencedIdentifier(f){let m=f.scope.getBinding(f.node.name);m?.scope===r.scope&&!s.has(m.identifier.name)&&a.push(m.identifier.name)}}),d?.isIdentifier()){let f=d.scope.getBinding(d.node.name);f?.scope===r.scope&&!s.has(f.identifier.name)&&a.push(f.identifier.name)}}let l=[...new Set(o.values())].filter(u=>!s.has(u));if(!l.length){r.stop();return}let c=U$(e.mappings).flatMap(u=>u.flatMap(d=>{let f=d[2],m=d[3];return typeof f=="number"&&typeof m=="number"?[{line:f+1,column:m}]:[]}));for(let u of l){let d=i.get(u)?.node.loc;if(d&&c.some(f=>(f.line>d.start.line||f.line===d.start.line&&f.column>=d.start.column)&&(f.line<d.end.line||f.line===d.end.line&&f.column<d.end.column))){n=!1;break}}r.stop()}}),n}var qi="/__vcp_snapshot__/",p_=/\.[cm]?[jt]sx?$/iu,z$=typeof Ng=="function"?Ng:Ng.default,_t=class extends Error{constructor(t,n,r){super(r),this.diagnostic=Object.freeze({code:t,path:n,message:r})}},m_=e=>`sha256:${g_("sha256").update(e).digest("hex")}`,Lu=e=>e.length>0&&e.length<=1024&&!/[\\\0%?#:]/u.test(e)&&!e.startsWith("/")&&e.split("/").every(t=>t&&!t.startsWith(".")&&t!=="node_modules");function Fu(e,t=0){if(t>64||typeof e=="number"&&!Number.isFinite(e))throw new Error("Invalid JSON value");return Array.isArray(e)?`[${e.map(n=>Fu(n,t+1)).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).map(([n,r])=>`[${JSON.stringify(n)}]:${Fu(r,t+1)}`).join(",")}}`:JSON.stringify(e)}async function h_(e){let t;try{let n=()=>{if(e.signal?.aborted)throw new _t("SOURCE_BUNDLE_CANCELLED","<bundle>","Source bundling was cancelled.")};if(n(),!Lu(e.entry_file)||!p_.test(e.entry_file)||e.entry_export.kind==="named"&&!/^[A-Za-z_$][\w$]*$/u.test(e.entry_export.name))throw new _t("SOURCE_BUNDLE_INVALID","<entry>","The module bundle entry is invalid.");let r=e.max_files??512,o=e.max_file_bytes??1024*1024,i=e.max_total_bytes??8*1024*1024;if([r,o,i].some(k=>!Number.isSafeInteger(k)||k<1))throw new _t("SOURCE_BUNDLE_INVALID","<bundle>","The module bundle budget is invalid.");let s=new Map(e.files),a=new Map(e.external_sources??[]),l=new Set(e.external_packages??[]),c=e.entry_export.kind==="default"?"default":e.entry_export.name,u=(e.invocation_bindings??[]).map(k=>X$.parse(k)),d=u.filter(k=>k.value.kind==="json-literal");if(new Set(d.map(k=>k.propName)).size!==d.length)throw new Error("Duplicate invocation input");let m=`components/site/portable/${g_("sha256").update(JSON.stringify([e.entry_file,c,d])).digest("hex").slice(0,24)}/entry.tsx`;if(s.has(m)||a.has(e.entry_file))throw new _t("SOURCE_BUNDLE_INVALID",m,"The module bundle entry collides with existing or host source.");s.set(m,d.length?`import { ${c} as __PortableSelected } from ${JSON.stringify(`@/${e.entry_file}`)}; function __PortableBound(${u.some(k=>k.value.kind!=="json-literal")?"props":""}){return <__PortableSelected ${u.map(k=>`${k.propName}={${k.value.kind==="json-literal"?Fu(k.value.value):`props.${k.propName}`}}`).join(" ")} />;} export { __PortableBound as ${c} };
|
|
49
|
+
`:`export { ${c} } from ${JSON.stringify(`@/${e.entry_file}`)};
|
|
50
|
+
`);let g=new Map,p=new Map,h=new Set,x=0,b=(k,T)=>{throw new _t("SOURCE_BUNDLE_UNRESOLVED",k,T)},E=k=>k.startsWith(qi)?k.slice(qi.length):"<bundle>";t=await K$({input:qi+m,jsx:"preserve",preserveEntrySignatures:"strict",makeAbsoluteExternalsRelative:!1,treeshake:{preset:"safest",annotations:!1},onwarn(k){if(!["MODULE_LEVEL_DIRECTIVE","CIRCULAR_DEPENDENCY","INVALID_ANNOTATION","UNUSED_EXTERNAL_IMPORT"].includes(k.code??""))throw new _t("SOURCE_BUNDLE_INVALID",k.id?E(k.id):"<bundle>",`The source linker could not preserve module semantics (${k.code??"UNKNOWN"}).`)},plugins:[{name:"vcp-pinned-snapshot",resolveId(k,T){if(n(),k===qi+m)return k;if(!kt(k))return!/[\\\0%?#:]/u.test(k)&&k.split("/").every(z=>z&&z!=="."&&z!=="..")&&[...l].some(z=>k===z||k.startsWith(`${z}/`))?{id:k,external:!0}:b(T?E(T):"<entry>","A source dependency is outside the pinned Snapshot and host contract.");let L=T?E(T):m,$=At(L,k,s);if(!$||!Lu($))return b(L,"A source dependency could not be resolved inside the pinned Snapshot.");let J=a.get($);return J?{id:J,external:!0}:!p_.test($)&&!$.endsWith(".json")?(h.add($),{id:`@/${$}`,external:!0,moduleSideEffects:/\.(?:css|scss|sass|less)$/iu.test($)}):qi+$},load(k){if(n(),!k.startsWith(qi))return b("<bundle>","Reading host files is not allowed.");let T=E(k),L=s.get(T);if(L===void 0)return b(T,"A pinned source module is missing.");let $;try{$=typeof L=="string"?L:new TextDecoder("utf-8",{fatal:!0}).decode(L)}catch{throw new _t("SOURCE_BUNDLE_INVALID",T,"A source module is not UTF-8 text.")}if(!g.has(T)){let Z=Buffer.byteLength($);if(x+=Z,g.size>=r||Z>o||x>i)throw new _t("SOURCE_BUDGET_EXCEEDED",T,"The pinned module graph exceeds its source budget.");g.set(T,$)}if(T.endsWith(".json"))try{return`export default ${Fu(JSON.parse($))};`}catch{throw new _t("SOURCE_BUNDLE_INVALID",T,"A JSON dependency is invalid.")}let J=Te(T,$);if(!J.ok)throw new _t("SOURCE_BUNDLE_INVALID",T,"A source module could not be parsed.");z$(J.module.ast,{ReferencedIdentifier(Z){if(["eval","Function","require"].includes(Z.node.name)&&!Z.scope.getBinding(Z.node.name))throw new _t("SOURCE_BUNDLE_UNSAFE",T,"Reflective code or unbounded module loading cannot be linked in isolation.")},CallExpression(Z){if(Na.isImport(Z.node.callee)&&!Na.isStringLiteral(Z.node.arguments[0]))throw new _t("SOURCE_BUNDLE_UNSAFE",T,"A dynamic module dependency requires a finite literal module identity.")},ImportExpression(Z){if(!Na.isStringLiteral(Z.node.source))throw new _t("SOURCE_BUNDLE_UNSAFE",T,"A dynamic module dependency requires a finite literal module identity.")}}),p.set(T,J.module.ast.program.directives.map(Z=>Z.value.value));let z=Zi.transpileModule($,{fileName:T,reportDiagnostics:!0,compilerOptions:{target:Zi.ScriptTarget.ESNext,module:Zi.ModuleKind.ESNext,jsx:Zi.JsxEmit.Preserve,verbatimModuleSyntax:!0,sourceMap:!0,inlineSourceMap:!1}});if(z.diagnostics?.some(Z=>Z.category===Zi.DiagnosticCategory.Error))throw new _t("SOURCE_BUNDLE_INVALID",T,"A source module could not be transpiled.");return{code:z.outputText,map:z.sourceMapText??null}},renderChunk(k,T){if(n(),T.moduleIds.filter(L=>g.has(E(L))).length>1)throw new _t("SOURCE_BUNDLE_INVALID","<bundle>","Source module boundaries were not preserved.");return null}}]});let S=await t.generate({format:"es",preserveModules:!0,minifyInternalExports:!1,sourcemap:"hidden",sourcemapExcludeSources:!0,banner(k){return[...new Set(k.moduleIds.flatMap(L=>p.get(E(L))??[]))].map(L=>`${JSON.stringify(L)};`).join(`
|
|
51
|
+
`)},entryFileNames(k){let T=k.facadeModuleId?E(k.facadeModuleId):"";if(!Lu(T))throw new _t("SOURCE_BUNDLE_INVALID","<bundle>","The linker emitted an unmapped module.");return T.endsWith(".json")?`${T}.ts`:T}});n();let v=[],A=[],I=0;for(let k of S.output){if(k.type==="asset"&&k.fileName.endsWith(".map"))continue;if(k.type!=="chunk"||!Lu(k.fileName)||!k.facadeModuleId)throw new _t("SOURCE_BUNDLE_INVALID","<bundle>","The linker emitted an undeclared output.");let T=E(k.facadeModuleId),L=g.get(T),$=Buffer.byteLength(k.code);if(I+=$,L===void 0||$>o||I>i)throw new _t("SOURCE_BUDGET_EXCEEDED",k.fileName,"The projected source exceeds its export budget.");if(!k.map||Object.values(k.modules).some(J=>J.originalLength>0)&&!f_({file_path:T,source:L,rendered_exports:k.modules[k.facadeModuleId]?.renderedExports??[],mappings:k.map.mappings}))throw new _t("SOURCE_BUNDLE_ISOLATION_UNPROVEN",T,"Required initialization would disclose an unselected exported source.");v.push({path:k.fileName,content:k.code}),A.push({source_path:T,source_digest:m_(L),output_path:k.fileName,output_digest:m_(k.code)})}if(!v.some(k=>k.path===m))throw new _t("SOURCE_BUNDLE_INVALID",m,"The selected module entry was not emitted.");let _=!d.length&&v.some(k=>k.path===e.entry_file)?e.entry_file:m;return{complete:!0,entry_file:_,entry_export:e.entry_export,files:v.filter(k=>_===m||k.path!==m).sort((k,T)=>k.path.localeCompare(T.path)),asset_paths:[...h].filter(k=>S.output.some(T=>T.type==="chunk"&&[...T.imports,...T.dynamicImports].includes(`@/${k}`))).sort(),source_projections:A.filter(k=>_===m||k.output_path!==m).sort((k,T)=>k.output_path.localeCompare(T.output_path)),compiler:{name:"rollup-typescript",rollup_version:J$,typescript_version:Zi.version}}}catch(n){let r=n instanceof _t?n:n&&typeof n=="object"&&"cause"in n&&n.cause instanceof _t?n.cause:null;return{complete:!1,errors:[r?r.diagnostic:{code:"SOURCE_BUNDLE_INVALID",path:"<bundle>",message:"The pinned source graph could not be linked."}]}}finally{await t?.close()}}import{createHash as y_}from"node:crypto";import Ag from"node:path";import Tg from"@babel/traverse";import*as Fg from"@babel/types";import{PortableAssetCatalogSchema as H$,PortableAssetSourcePathSchema as wg}from"@vcp-dev/contracts";var W$=typeof Tg=="function"?Tg:Tg.default,G$=/\.[cm]?[jt]sx?$/iu,Og=/\.(?:png|jpe?g|gif|webp|svg|avif|ico|bmp|woff2?|ttf|otf|eot|mp4|webm|mp3|wav|ogg|pdf)$/iu,Lg=e=>`sha256:${y_("sha256").update(e).digest("hex")}`;function x_(e){let t=new Map,n=[],r=[],o=new Map,i=new Map(e.source_files.map(x=>[x.path,x.content])),s=new Map((e.host_sources??[]).map(x=>[x.path,x])),a=[...i.keys(),...s.keys()],l=new Set,c=0,u=(x,b,E)=>{r.length<256&&r.push({code:x,path:b,message:E})},d=x=>{let b=i.get(x)??s.get(x)?.content??e.snapshot_files.get(x);try{return typeof b=="string"?b:b instanceof Uint8Array?new TextDecoder("utf-8",{fatal:!0}).decode(b):null}catch{return null}},f=(x,b,E)=>{if(x.startsWith("#"))return null;if(/^https?:\/\//iu.test(x)){try{let A=new URL(x),I=e.declared_remote_urls?.has(x),_=/\/media\/assets\/[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/iu.test(A.pathname);if(E!=="literal"||Og.test(A.pathname)||I||_)return{kind:"remote",url:x}}catch{u("ASSET_ORIGIN_INVALID",b,"A declared resource has an invalid URL.")}return null}if(!(E!=="literal"||Og.test(x)||x.startsWith("/")&&e.snapshot_files.has(`public${x}`)))return null;if(/[\\\0%?#]/u.test(x)||x.startsWith("//"))return u("ASSET_ORIGIN_INVALID",b,"A resource locator is outside the safe Snapshot path contract."),null;let v=x.startsWith("/")?`public${x}`:E==="module"?At(b,x,e.snapshot_files):E==="css"?Ag.posix.normalize(Ag.posix.join(Ag.posix.dirname(b),x)):null;return!v||!wg.safeParse(v).success?(u("ASSET_DOCUMENT_BASE_REQUIRED",b,"A relative resource requires an explicit, relocatable Snapshot or directory identity."),null):e.snapshot_files.has(v)?{kind:"snapshot",path:v}:(u("ASSET_SOURCE_MISSING",b,"A declared resource is missing from the pinned Snapshot."),null)},m=(x,b,E,S,v,A,I)=>{let _=`asset-${y_("sha256").update(JSON.stringify(x)).digest("hex")}`;t.set(_,{asset_key:_,origin:x,source_urls:x.kind==="remote"?[x.url]:x.path.startsWith("public/")?[`/${x.path.slice(7)}`]:[]});let k=s.get(b),T;if(k)T={kind:"host-dependency",asset_key:_,file_path:b,source_digest:k.digest};else{let L=A.slice(S,v),$={asset_key:_,file_path:b,start_offset:S,end_offset:v,original_text:L,content_digest:Lg(L)};T=I?{...$,kind:"source-string-url",value_start:I.start_offset,value_end:I.end_offset,value_text:I.original_text}:{...$,kind:E}}n.some(L=>JSON.stringify(L)===JSON.stringify(T))||n.push(T),(t.size>4096||n.length>4096)&&u("ASSET_BUDGET_EXCEEDED",b,"The resource directory exceeds its identity or binding budget.")},g=(x,b)=>{if(/^https?:/iu.test(x)){u("ASSET_STYLESHEET_UNSUPPORTED",b,"Remote executable stylesheet dependencies require an explicit source directory.");return}let E=x.startsWith("/")?`public${x}`:At(b,x.startsWith("@/")||x.startsWith(".")?x:`./${x}`,e.snapshot_files);if(!E||!E.endsWith(".css")||!wg.safeParse(E).success){u("ASSET_STYLESHEET_MISSING",b,"A stylesheet import is not closed inside the pinned Snapshot.");return}a.push(E)};for(;a.length&&r.length<256;){let x=a.shift();if(l.has(x))continue;l.add(x);let b=d(x);if(!wg.safeParse(x).success||b===null){u("ASSET_SOURCE_INVALID",x,"A resource-owning module is unavailable as safe UTF-8 source.");continue}let E=Buffer.byteLength(b);if(c+=E,l.size>512||E>1024*1024||c>8*1024*1024){u("ASSET_BUDGET_EXCEEDED",x,"The resource source graph exceeds its bounded export budget.");continue}let S=s.get(x);if(S&&Lg(b)!==S.digest){u("HOST_IMPLEMENTATION_UNPROVEN",x,"The resource host source does not match its trusted digest.");continue}if(x.endsWith(".css")){let I=Ki(b);if(!I.complete){u("ASSET_CSS_UNRESOLVED",x,"A stylesheet resource dependency is invalid or lacks a finite declaration.");continue}S||o.set(x,b);for(let _ of I.references)if(_.kind==="stylesheet")g(_.value,x);else{let k=f(_.value,x,"css");k&&m(k,x,"css-url",_.start_offset,_.end_offset,b)}continue}if(!G$.test(x)){u("ASSET_SOURCE_INVALID",x,"A resource-owning source module has an unsupported source type.");continue}let v=Te(x,b);if(!v.ok){u("ASSET_SOURCE_INVALID",x,"A resource-owning module could not be parsed.");continue}let A=(I,_,k=!1)=>{if(I.start==null||I.end==null||e.excluded_source_ranges?.some($=>$.file_path===x&&$.source_hash===Lg(b)&&$.start<=I.start&&$.end>=I.end))return;let T=f(_,x,k?"resource":"literal");if(T){m(T,x,"source-token",I.start,I.end,b);return}let L=Ki(_,{value_only:!0});if(!L.complete){L.resource_syntax&&u("ASSET_CSS_UNRESOLVED",x,"An embedded CSS resource lacks a finite declaration.");return}for(let $ of L.references){if($.kind==="stylesheet"){u("ASSET_STYLESHEET_UNSUPPORTED",x,"Embedded stylesheet imports require a module dependency.");continue}let J=f($.value,x,"css");J&&m(J,x,"source-token",I.start,I.end,b,$)}};W$(v.module.ast,{ImportDeclaration(I){if(I.node.importKind==="type")return;let _=I.node.source.value;if(_.endsWith(".css")){g(_,x);return}if(!Og.test(_))return;let k=f(_,x,"module");k&&I.node.source.start!=null&&I.node.source.end!=null&&m(k,x,"module-import",I.node.source.start,I.node.source.end,b)},StringLiteral(I){if(I.parentPath.isImportDeclaration()||I.parentPath.isExportAllDeclaration()||I.parentPath.isExportNamedDeclaration())return;let _=I.parentPath.isJSXExpressionContainer()?I.parentPath.parentPath:I.parentPath,k=_.isJSXAttribute()&&Fg.isJSXIdentifier(_.node.name)&&["src","poster","fallbackSrc","thumbnail"].includes(_.node.name.name);A(I.node,I.node.value,k)},TemplateLiteral(I){let _=I.parentPath.isJSXExpressionContainer()?I.parentPath.parentPath:I.parentPath,k=_.isJSXAttribute()&&Fg.isJSXIdentifier(_.node.name)&&["src","poster","fallbackSrc","thumbnail"].includes(_.node.name.name);I.node.expressions.length||A(I.node,I.node.quasis[0]?.value.cooked??"",k)}})}if(r.length)return{complete:!1,errors:r};let p={assets:[...t.values()].sort((x,b)=>x.asset_key.localeCompare(b.asset_key)),bindings:n.sort((x,b)=>x.file_path.localeCompare(b.file_path)||x.asset_key.localeCompare(b.asset_key))},h=H$.safeParse(p);return h.success?{complete:!0,catalog:h.data,stylesheets:[...o].map(([x,b])=>({path:x,content:b})).sort((x,b)=>x.path.localeCompare(b.path))}:{complete:!1,errors:[{code:"ASSET_CATALOG_INVALID",path:"<assets>",message:"The resource identity graph failed its bounded binding contract."}]}}import jr from"node:path";import M from"typescript";import{tokenize as Y$,isTokenFunction as Z$,isTokenCloseParen as q$,isTokenURL as Q$,TokenType as eU}from"@csstools/css-tokenizer";var An="/__vcp_resources__/",Dg=1,Aa=2,Ta=4,Ot=8,$r=16,wa=32,Mg=new Map;function b_(e){try{return tU(e)}catch{return{complete:!1,errors:[{code:"ASSET_ANALYSIS_UNPROVEN",path:"<resources>",message:"The bounded compiler could not prove resource provenance."}]}}}function tU(e){let t={target:M.ScriptTarget.ESNext,module:M.ModuleKind.ESNext,jsx:M.JsxEmit.Preserve,allowJs:!0,checkJs:!0,noEmit:!0,skipLibCheck:!0,lib:["lib.es2023.d.ts"],types:[]},n=jr.dirname(M.getDefaultLibFilePath(t)),r=0,o=0,i=!1,s=N=>{if(N.startsWith(An)){let B=N.slice(An.length),K=e.sources.get(B);if(K!==void 0)return K;let X=e.files.get(B);return typeof X=="string"&&/\.[cm]?[jt]sx?$/iu.test(B)&&Buffer.byteLength(X)<=1024*1024?X:void 0}if(!(jr.dirname(N)!==n||!/^lib\.[a-z0-9.]+\.d\.ts$/u.test(jr.basename(N)))){if(!Mg.has(N)){let B=M.sys.readFile(N);B!==void 0&&Mg.set(N,B)}return Mg.get(N)}},a={getSourceFile:(N,B)=>{let K=s(N);if(K!==void 0&&N.startsWith(An)){let X=Buffer.byteLength(K);if(r+=X,o++,X>1024*1024||o>512||r>8*1024*1024){i=!0;return}}return K===void 0?void 0:M.createSourceFile(N,K,B,!0,N.endsWith(".tsx")||N.endsWith(".jsx")?M.ScriptKind.TSX:M.ScriptKind.TS)},getDefaultLibFileName:()=>M.getDefaultLibFilePath(t),writeFile:()=>{throw new Error("Resource analysis is read-only")},getCurrentDirectory:()=>An,getDirectories:()=>[],getCanonicalFileName:N=>N,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`
|
|
52
|
+
`,fileExists:N=>s(N)!==void 0,readFile:s,resolveModuleNames:(N,B)=>N.map(K=>{let X=At(B.slice(An.length),K,e.files);return X&&/\.[cm]?[jt]sx?$/iu.test(X)?{resolvedFileName:An+X}:void 0})},l=M.createProgram([...e.sources.keys()].filter(N=>/\.[cm]?[jt]sx?$/iu.test(N)).map(N=>An+N),t,a);if(i)return{complete:!1,errors:[{code:"ASSET_ANALYSIS_BUDGET_EXCEEDED",path:"<resources>",message:"Resource provenance exceeds its compiler source budget."}]};let c=l.getTypeChecker(),u=N=>N.getSourceFile().fileName.startsWith(An),d=N=>u(N)&&!M.isTypeElement(N)&&!M.isTypeAliasDeclaration(N)&&!M.isInterfaceDeclaration(N),f=N=>N.getSourceFile().fileName.slice(An.length),m=new Map,g=new Map,p=new Set,h=new Set,x=new Set,b=new Map,E=new Map,S=new Map,v=new Set,A=new Map,I=(N,B)=>{v.add(N),A.set(N,B)},_=[],k=[],T=!1,L=new Map,$=new Set,J=[],z=[],Z=new Set,W=new Set,Ee=N=>["src","srcset","poster","fallbacksrc","thumbnail"].includes(N.toLowerCase()),xe=N=>["background","backgroundimage","mask","maskimage","borderimagesource","liststyleimage","cssText".toLowerCase()].includes(N.replace(/-/gu,"").toLowerCase()),Ce=(N,B=!1)=>{J.push(N),B&&Z.add(N)},Me=N=>{let B=c.getSymbolAtLocation(N);if(B&&B.flags&M.SymbolFlags.Alias){let K=c.getAliasedSymbol(B);K.declarations?.length&&(B=K)}return B},bt=(N,B)=>{let K=b.get(N)??new Set;K.add(B),b.set(N,K)},Ie=N=>{if(!M.isIdentifier(N))return null;let B=c.getSymbolAtLocation(N)?.declarations?.[0],K=B;for(;K&&!M.isImportDeclaration(K);)K=K.parent;if(!K||!M.isImportDeclaration(K)||!M.isStringLiteral(K.moduleSpecifier))return null;let X=B&&M.isImportSpecifier(B)?(B.propertyName??B.name).text:"default",te=K.moduleSpecifier.text;return te==="clsx"&&["default","clsx"].includes(X)||te==="tailwind-merge"&&X==="twMerge"?"merge":te==="tailwind-merge"&&X==="extendTailwindMerge"?"factory":te==="class-variance-authority"&&X==="cva"?"variants":null},ot=N=>{if(Ie(N.expression)==="merge")return N.arguments;if(!M.isIdentifier(N.expression))return null;let B=Me(N.expression);if(!B||v.has(B)||E.has(B))return null;let X=B.declarations?.find(M.isVariableDeclaration)?.initializer;if(!X||!M.isCallExpression(X))return null;let te=Ie(X.expression);return te==="factory"?N.arguments:te!=="variants"?null:[...X.arguments,...N.arguments.flatMap(Re=>M.isObjectLiteralExpression(Re)?Re.properties.filter(Qe=>!M.isPropertyAssignment(Qe)&&!M.isShorthandPropertyAssignment(Qe)||Qe.name&&(!M.isIdentifier(Qe.name)&&!M.isStringLiteral(Qe.name)||["class","className"].includes(Qe.name.text))):[Re])]},Ve=(N,B)=>{B(N),M.forEachChild(N,K=>Ve(K,B))},F=N=>{if(!M.isCallExpression(N))return!1;let B=N.getSourceFile().getLineAndCharacterOfPosition(N.getStart());return e.cms_sources.some(K=>K.source_path===f(N)&&K.call_site.line===B.line+1&&K.call_site.column===B.character)},q=N=>{let B=S.get(N);if(!B||B===N)return N;let K=q(B);return S.set(N,K),K},ee=N=>{let B=new Set,K=new Set,X=te=>{if(!M.isFunctionLike(te)){if(M.isCallExpression(te)||M.isNewExpression(te)){if(F(te))return;M.isCallExpression(te)&&M.isPropertyAccessExpression(te.expression)&&h.has(te.expression.name.text)&&X(te.expression.expression);let Re=c.getResolvedSignature(te)?.declaration;if(Re&&e.trusted_data_adapters?.has(f(Re))){for(let Qe of te.arguments??[])X(Qe);return}if(Re&&u(Re)&&"body"in Re&&Re.body&&!K.has(Re)){K.add(Re);let Qe=ve=>{if(M.isReturnStatement(ve)){ve.expression&&X(ve.expression);return}M.isFunctionLike(ve)||M.forEachChild(ve,Qe)},ue=Re.body;M.isBlock(ue)?M.forEachChild(ue,Qe):X(ue)}return}if(M.isIdentifier(te)||M.isPropertyAccessExpression(te)){let Re=Me(te);Re?.declarations?.some(d)&&B.add(Re)}M.forEachChild(te,X)}};return X(N),B},qe=N=>{let B;for(let K of N){let X=q(K);B?S.set(X,B):B=X}},ht=0;for(let N of l.getSourceFiles())jr.dirname(N.fileName)===n&&Ve(N,B=>{if(M.isInterfaceDeclaration(B)&&["String","Number","Boolean"].includes(B.name.text))for(let K of B.members)M.isMethodSignature(K)&&x.add(K.name.getText());if(M.isInterfaceDeclaration(B)&&["Array","ReadonlyArray","Promise","PromiseLike"].includes(B.name.text)){for(let K of B.members)if(M.isMethodSignature(K)){K.parameters.some(te=>te.type&&M.isFunctionTypeNode(te.type))&&p.add(K.name.getText());let X=new Set([...B.typeParameters??[],...K.typeParameters??[]].map(te=>te.name.text));K.type&&Ve(K.type,te=>{M.isTypeReferenceNode(te)&&M.isIdentifier(te.typeName)&&X.has(te.typeName.text)&&h.add(K.name.getText())})}}});for(let N of l.getSourceFiles())!N.fileName.startsWith(An)||!e.sources.has(N.fileName.slice(An.length))||Ve(N,B=>{if(ht++,(M.isElementAccessExpression(B)||M.isSpreadAssignment(B)||M.isSpreadElement(B))&&z.push(B),!(e.excluded_sources?.has(f(B))||e.trusted_data_adapters?.has(f(B)))){if(M.isVariableDeclaration(B)&&B.initializer&&qe([...ee(B.name),...ee(B.initializer)]),M.isCallExpression(B)){if(M.isPropertyAccessExpression(B.expression)){let X=B.expression.name.text,te=B.arguments[0],Re=B.arguments[1];X==="setAttribute"&&Re&&(!te||!M.isStringLiteralLike(te)||Ee(te.text)||te.text==="style")&&Ce(Re,!!te&&M.isStringLiteralLike(te)&&te.text==="style"),X==="setProperty"&&Re&&Ce(Re,!0),["insertRule","replaceSync"].includes(X)&&te&&Ce(te,!0)}let K=c.getResolvedSignature(B)?.declaration;if(K&&u(K)&&!e.trusted_data_adapters?.has(f(K))&&K.parameters.forEach((X,te)=>{let Re=B.arguments[te];Re&&M.isParameter(X)&&bt(X,Re)}),M.isPropertyAccessExpression(B.expression)&&p.has(B.expression.name.text)){let X=B.expression.expression;for(let te of B.arguments){let Re=M.isArrowFunction(te)||M.isFunctionExpression(te)?te:Me(te)?.declarations?.find(M.isFunctionDeclaration);if(Re)for(let Qe of Re.parameters)bt(Qe,X),(!K||u(K))&&g.set(Qe,X)}}}if(M.isBinaryExpression(B)&&B.operatorToken.kind>=M.SyntaxKind.FirstAssignment&&B.operatorToken.kind<=M.SyntaxKind.LastAssignment){if(M.isPropertyAccessExpression(B.left)){let te=B.left.name.text;(Ee(te)||xe(te)||["innerHTML","outerHTML","srcdoc"].includes(te))&&Ce(B.right,xe(te))}let K=B.left;for(;M.isPropertyAccessExpression(K)||M.isElementAccessExpression(K);)K=K.expression;let X=Me(K);if(X){let te=E.get(X)??new Set;te.add(B.right),E.set(X,te)}for(let te of ee(B.left))I(te,B);X?.declarations?.some(te=>jr.dirname(te.getSourceFile().fileName)===n)&&(T=!0)}if(M.isJsxOpeningElement(B)||M.isJsxSelfClosingElement(B)){let X=Me(B.tagName)?.declarations?.find(M.isFunctionDeclaration);if(X){let ue=L.get(X)??new Map;for(let ve of B.attributes.properties)if(M.isJsxAttribute(ve)&&ve.initializer){let it=ve.name.getText(),pt=ue.get(it)??new Set;pt.add(ve.initializer),ue.set(it,pt)}else M.isJsxSpreadAttribute(ve)&&$.add(X);L.set(X,ue)}if(e.excluded_sources?.has(f(B)))return;let te=B.tagName.getText(),Re=te==="script"&&B.attributes.properties.some(ue=>M.isJsxAttribute(ue)&&ue.name.getText()==="type"&&ue.initializer&&M.isStringLiteral(ue.initializer)&&["application/ld+json","application/json"].includes(ue.initializer.text)),Qe=/^(?:img|image|source|video|audio|SafeImage)$/u.test(te);for(let ue of B.attributes.properties){if(M.isJsxSpreadAttribute(ue)){Qe&&J.push(ue.expression);continue}let ve=ue.name.getText().toLowerCase();ue.initializer&&(ve==="style"||ve==="classname"||ve==="dangerouslysetinnerhtml"&&!Re||Ee(ve))&&(J.push(ue.initializer),(ve==="style"||ve==="classname")&&Z.add(ue.initializer),ve==="classname"&&W.add(ue.initializer))}}}});for(let[N,B]of b)qe([...ee(N.name),...[...B].flatMap(K=>[...ee(K)])]);for(let N of l.getSourceFiles())!N.fileName.startsWith(An)||!e.sources.has(N.fileName.slice(An.length))||e.excluded_sources?.has(f(N))||e.trusted_data_adapters?.has(f(N))||Ve(N,B=>{if(!M.isCallExpression(B)||ot(B)||["factory","variants"].includes(Ie(B.expression)??""))return;let K=c.getResolvedSignature(B)?.declaration;if(!(K&&u(K))){if(!K&&M.isPropertyAccessExpression(B.expression)&&x.has(B.expression.name.text)){let X=[B.expression.expression,...B.arguments];k.push({inputs:X,aliases:new Set(X.flatMap(te=>[...ee(te)]))});return}if(K&&jr.dirname(K.getSourceFile().fileName)===n&&M.isPropertyAccessExpression(B.expression)&&M.isInterfaceDeclaration(K.parent)){let X=K.parent.name.text,te=["String","Number","Boolean"].includes(X)?[B.expression.expression,...B.arguments]:X==="ObjectConstructor"&&B.expression.name.text==="keys"?[...B.arguments]:null;if(te){k.push({inputs:te,aliases:new Set(te.flatMap(Re=>[...ee(Re)]))});return}}if(!(K&&jr.dirname(K.getSourceFile().fileName)===n&&M.isPropertyAccessExpression(B.expression)&&h.has(B.expression.name.text))){if(!K&&M.isPropertyAccessExpression(B.expression)&&h.has(B.expression.name.text)){_.push({receiver:B.expression.expression,aliases:new Set([...ee(B.expression.expression),...B.arguments.flatMap(X=>[...ee(X)])])});return}for(let X of B.arguments)for(let te of ee(X))I(te,B);if(M.isPropertyAccessExpression(B.expression))for(let X of ee(B.expression.expression))I(X,B)}}});let nn=new Set([...v].map(q)),tr=N=>M.isVariableDeclaration(N)||M.isParameter(N)||M.isBindingElement(N)||M.isPropertyAssignment(N)||M.isShorthandPropertyAssignment(N)?N.name:N;if(ht>2e5)return{complete:!1,errors:[{code:"ASSET_ANALYSIS_BUDGET_EXCEEDED",path:"<resources>",message:"Resource provenance exceeds its compiler graph budget."}]};let ts=N=>e.bindings.some(B=>B.file_path===f(N)&&B.kind!=="host-dependency"&&B.start_offset===N.getStart()&&B.end_offset===N.end),_r=N=>{let B=m.get(N);if(B)return B;let K={flags:0,dependencies:new Set};m.set(N,K);let X=(...ue)=>{for(let ve of ue)ve&&(K.dependencies.add(ve),_r(ve))},te=ue=>{let ve=Me(ue),it=ve?.declarations?.filter(d)??[];it.length?X(...it):K.flags|=Ot,ve&&X(...E.get(ve)??[])},Re=(ue,ve)=>{let it=new Set,pt=cn=>{if(it.has(cn))return;it.add(cn);let Jn=Me(tr(cn));if(Jn&&nn.has(q(Jn))){K.flags|=Ot;return}let os=_r(cn);if(os.flags){X(cn);return}let $a=c.getTypeAtLocation(cn).getProperty(ve)?.declarations?.filter(d);if($a?.length)X(...$a);else if(os.dependencies.size)for(let is of os.dependencies)pt(is);else X(cn)};pt(ue)};if(ts(N))return K.flags=Dg,K;if(F(N))return K.flags=wa,K;if(M.isStringLiteralLike(N))K.flags=N.text===""?Aa:Ta;else if(N.kind===M.SyntaxKind.NullKeyword||N.kind===M.SyntaxKind.UndefinedKeyword||N.kind===M.SyntaxKind.FalseKeyword||N.kind===M.SyntaxKind.TrueKeyword||M.isNumericLiteral(N))K.flags=Aa;else if(M.isIdentifier(N))N.text==="undefined"?K.flags=Aa:te(N);else if(M.isVariableDeclaration(N))X(N.initializer);else if(M.isPropertyAssignment(N)||M.isShorthandPropertyAssignment(N))X(M.isShorthandPropertyAssignment(N)?N.name:N.initializer),M.isComputedPropertyName(N.name)&&!M.isStringLiteralLike(N.name.expression)&&!M.isNumericLiteral(N.name.expression)&&X(N.name.expression);else if(M.isBindingElement(N)){let ue=N.parent.parent,ve=N.propertyName??(M.isIdentifier(N.name)?N.name:void 0);if(M.isVariableDeclaration(ue)&&ue.initializer)ve?Re(ue.initializer,ve.getText().replace(/^["']|["']$/gu,"")):X(ue.initializer);else if(M.isParameter(ue)){let it=ue.parent,pt=ve?L.get(it)?.get(ve.getText()):void 0;pt?.size?X(...pt):L.has(it)&&!$.has(it)&&!b.has(ue)?K.flags=Aa:X(ue)}else K.flags=Ot;X(N.initializer)}else if(M.isParameter(N)){let ue=b.get(N);if(ue?.size)X(...ue);else{let ve=N.parent,it=ve.parent;if((M.isArrowFunction(ve)||M.isFunctionExpression(ve))&&M.isCallExpression(it)&&M.isPropertyAccessExpression(it.expression)){let pt=c.getResolvedSignature(it)?.declaration;pt&&!u(pt)&&jr.dirname(pt.getSourceFile().fileName)===n?X(it.expression.expression):p.has(it.expression.name.text)?(X(it.expression.expression),g.set(N,it.expression.expression)):K.flags|=Ot}else K.flags|=Ot}X(N.initializer)}else if(M.isPropertyAccessExpression(N))Re(N.expression,N.name.text);else if(M.isElementAccessExpression(N))N.argumentExpression&&M.isStringLiteralLike(N.argumentExpression)?Re(N.expression,N.argumentExpression.text):X(N.expression);else if(M.isConditionalExpression(N))X(N.whenTrue,N.whenFalse);else if(M.isBinaryExpression(N))[M.SyntaxKind.BarBarToken,M.SyntaxKind.QuestionQuestionToken,M.SyntaxKind.AmpersandAmpersandToken].includes(N.operatorToken.kind)||(K.flags=$r),X(N.left,N.right);else if(M.isTemplateExpression(N))K.flags=$r,X(...N.templateSpans.map(ue=>ue.expression));else if(M.isCallExpression(N)&&!T&&ot(N))X(...ot(N));else if(M.isCallExpression(N)||M.isNewExpression(N)){let ue=c.getResolvedSignature(N)?.declaration;if(ue&&u(ue))e.trusted_data_adapters?.has(f(ue))?X(...N.arguments??[]):X(ue);else if(ue&&jr.dirname(ue.getSourceFile().fileName)===n&&M.isCallExpression(N)&&M.isPropertyAccessExpression(N.expression)){let ve=ue.type,it=new Set;if(ve&&Ve(ve,pt=>{M.isTypeReferenceNode(pt)&&M.isIdentifier(pt.typeName)&&it.add(pt.typeName.text)}),it.size){if(X(N.expression.expression),ue.typeParameters?.some(pt=>M.isTypeParameterDeclaration(pt)&&it.has(pt.name.text)))for(let pt of N.arguments)X(pt)}else K.flags=$r}else M.isCallExpression(N)&&M.isPropertyAccessExpression(N.expression)&&h.has(N.expression.name.text)?(X(N.expression.expression),p.has(N.expression.name.text)&&X(...N.arguments),g.set(N,N.expression.expression)):K.flags=Ot}else if(M.isFunctionDeclaration(N)||M.isFunctionExpression(N)||M.isArrowFunction(N)||M.isMethodDeclaration(N)||M.isGetAccessor(N))if(!N.body)K.flags=Ot;else if(!M.isBlock(N.body))X(N.body);else{let ue=ve=>{if(M.isReturnStatement(ve)){X(ve.expression);return}M.isFunctionLike(ve)||M.forEachChild(ve,ue)};M.forEachChild(N.body,ue)}else if(M.isAwaitExpression(N)||M.isParenthesizedExpression(N)||M.isNonNullExpression(N)||M.isAsExpression(N)||M.isTypeAssertionExpression(N))X(N.expression);else if(M.isJsxExpression(N))X(N.expression);else if(M.isArrayLiteralExpression(N))X(...N.elements);else if(M.isObjectLiteralExpression(N))X(...N.properties);else if(M.isSpreadElement(N)||M.isSpreadAssignment(N))X(N.expression);else if(M.isImportClause(N)||M.isImportSpecifier(N)||M.isNamespaceImport(N)){let ue=N;for(;ue&&!M.isImportDeclaration(ue);)ue=ue.parent;ue&&M.isImportDeclaration(ue)&&ts(ue.moduleSpecifier)?K.flags=Dg:K.flags=Ot}else K.flags=Ot;let Qe=Me(tr(N));return Qe&&nn.has(q(Qe))&&(K.flags|=Ot),T&&(M.isPropertyAccessExpression(N)||M.isElementAccessExpression(N)||M.isParameter(N))&&(K.flags|=Ot),K};for(let N of J)_r(N);for(let N of z)_r(N);if(J.length)for(let N of _)_r(N.receiver);if(J.length)for(let N of k)for(let B of N.inputs)_r(B);let ri=new Map;for(let[N,B]of m)for(let K of B.dependencies){let X=ri.get(K)??new Set;X.add(N),ri.set(K,X)}let Kn=[...m.keys()];for(let N=0;N<Kn.length;N++){let B=Kn[N],K=m.get(B);for(let X of ri.get(B)??[]){let te=m.get(X),Re=te.flags|K.flags;Re!==te.flags&&(te.flags=Re,Kn.push(X))}}let Io=N=>{let B=m.get(N)?.flags??0;return!T&&!!B&&!(B&(Ot|$r))};for(let[N,B]of g){let K=m.get(N);if(!K)continue;let X=m.get(B)?.flags??Ot;(!(X&wa)||X&(Ot|$r|Ta))&&!Io(B)&&(K.flags|=Ot,Kn.push(N))}let ns=N=>{let B=new Set([...N].map(q));for(let[K,X]of m){let te=Me(tr(K));te&&B.has(q(te))&&!(X.flags&Ot)&&(X.flags|=Ot,Kn.push(K))}};for(let N of _){let B=m.get(N.receiver)?.flags??Ot;B&wa&&!(B&(Ot|$r|Ta))||Io(N.receiver)||ns(N.aliases)}for(let N of k)(!N.inputs.length||!N.inputs.every(Io))&&ns(N.aliases);for(let N=0;N<Kn.length;N++){let B=Kn[N];for(let K of ri.get(B)??[]){let X=m.get(K),te=X.flags|m.get(B).flags;te!==X.flags&&(X.flags=te,Kn.push(K))}}for(let N of z)Io(N)&&!(m.get(N).flags&wa)&&e.on_finite_data?.({file_path:f(N),start:N.getStart(),end:N.end});let rs=(N,B=new Set)=>{if(B.has(N))return!1;let K=m.get(N);if(!K||K.flags&(Ot|Dg|wa))return!1;let X=Re=>{if(/[\\'"\u0000]/u.test(Re))return!1;let Qe=0,ue=!0;for(let ve of Y$({css:Re},{onParseError:()=>{ue=!1}})){if(Q$(ve))return!1;if(Z$(ve)){if(!["var","calc","min","max","clamp"].includes(ve[4].value.toLowerCase()))return!1;Qe++}else if(ve[0]===eU.OpenParen){if(!Qe)return!1;Qe++}else if(q$(ve)&&--Qe<0)return!1}return ue&&Qe===0};if(M.isStringLiteralLike(N))return X(N.text);if(M.isTemplateExpression(N)&&![N.head,...N.templateSpans.map(Re=>Re.literal)].every(Re=>X(Re.text))||K.flags&$r&&!(M.isTemplateExpression(N)||M.isBinaryExpression(N)&&N.operatorToken.kind===M.SyntaxKind.PlusToken||K.dependencies.size))return!1;let te=new Set(B).add(N);return K.dependencies.size?[...K.dependencies].every(Re=>rs(Re,te)):!!(K.flags&Aa)},ja=J.flatMap(N=>{let B=m.get(N).flags;if(W.has(N)&&rs(N)||B&&!(B&(Ot|$r|(Z.has(N)?0:Ta))))return[];let K=N.getSourceFile().getLineAndCharacterOfPosition(N.getStart()),X=[N],te=new Set,Re="";for(;X.length;){let Qe=X.pop();if(te.has(Qe))continue;te.add(Qe);let ue=m.get(Qe),ve=Me(tr(Qe)),it=ve&&nn.has(q(ve));if(it||!ue.dependencies.size&&ue.flags&(Ot|$r|Ta)){let pt=Qe.getSourceFile().getLineAndCharacterOfPosition(Qe.getStart());if(Re=` ${it?"Mutable or escaped":"Unproven"} ${M.SyntaxKind[Qe.kind]} at ${f(Qe)}:${pt.line+1}:${pt.character}.`,it){let cn=[...A].find(([Jn])=>q(Jn)===q(ve))?.[1];if(cn){let Jn=cn.getSourceFile().getLineAndCharacterOfPosition(cn.getStart());Re+=` Boundary at ${f(cn)}:${Jn.line+1}:${Jn.character}.`}}break}X.push(...ue.dependencies)}return[{code:"ASSET_DIRECTORY_REQUIRED",path:f(N),message:`Resource input at ${K.line+1}:${K.character} requires a finite, source-bound resource directory and deterministic relocation.${Re}`.slice(0,500)}]});return{complete:ja.length===0,errors:ja.slice(0,256)}}async function S_(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=Ft(n.get(t.ownerFile)),s=Ft(n.get(t.descriptor.source.file));if(i===null||s===null)return[];let a=async l=>{let c=Ft(n.get(l));if(c===null)throw new Error("Snapshot source unavailable");return c};try{let l=await pi(t.ownerFile,i,a,async p=>n.has(p));if(!l.entryModule||l.diagnostics.length)return[];let c=[...l.graph.elements.values()].filter(p=>p.importedFrom===t.descriptor.source.file);if(c.length!==1||c[0].sourceFile!==o.sourceFile||c[0].exportName!==o.exportName||!nU(c[0].sourceRange,o.callLocator.sourceRange))return[];let u=[...l.graph.elements.values()].filter(p=>p.sourceFile===t.descriptor.source.file&&E_(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 h=l.parsedModules.get(p.sourceFile);if(!h)continue;let x=lr({module:h,componentName:p.tag,callSourceRange:p.sourceRange,...p.importedFrom?{imported:{file:p.importedFrom,module:l.parsedModules.get(p.importedFrom),exportName:p.exportName??p.tag,parsedModules:l.parsedModules}}:{}});if(!x.ok||x.metadataOnly)continue;let b=[...x.roots,...x.returnAlternatives??[]];for(let E of l.graph.fileIndex.get(x.sourceFile)??[]){let S=l.graph.elements.get(E);if(!(!S||d.has(E)||!b.some(v=>{let A=v.node.loc;return A&&E_({startLine:A.start.line,startColumn:A.start.column,endLine:A.end.line,endColumn:A.end.column},S.sourceRange)}))&&(d.add(E),u.push(S),u.length>256))return[]}}d.add(c[0].identity.key);let f={...l.graph,elements:new Map([...l.graph.elements].filter(([p])=>d.has(p))),regions:l.graph.regions.filter(p=>d.has(p.ownerKey))},m=new Set,g=new Map;for(let p of u){let h=await zl({element:p,graph:f,file:p.sourceFile,source:await a(p.sourceFile),readFile:a,exists:async x=>n.has(x),fileCache:g});for(let x of h.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(b=>b.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(b=>b.reason==="VCP CMS fetch helper"))&&m.add(x.collection);if(m.size>16)return[]}return[...m].sort()}catch{return[]}}function nU(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function E_(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 Bg from"@babel/traverse";import*as ze from"@babel/types";import*as hn from"@babel/types";function I_(e){let t=new Set,n=new Map,r=l=>{let c=l.get("arguments");return c.length===1&&c[0].isArrowFunctionExpression()&&!c[0].node.async&&c[0].node.params.length<=2&&!c[0].node.params.some(u=>hn.isRestElement(u))},o=l=>{let c=l;for(;c.parentPath&&(c.parentPath.isTSAsExpression()||c.parentPath.isTSTypeAssertion()||c.parentPath.isTSSatisfiesExpression()||c.parentPath.isTSNonNullExpression()||c.parentPath.isParenthesizedExpression());)c=c.parentPath;let u=c.parentPath;return u?u.isAssignmentExpression()&&u.node.left===c.node||u.isUpdateExpression()||u.isUnaryExpression({operator:"delete"})||(u.isCallExpression()||u.isOptionalCallExpression())&&u.node.callee===c.node||(u.isMemberExpression()||u.isOptionalMemberExpression())&&u.node.object===c.node&&["call","apply","bind"].includes(Du(u.node)??"")||u.isNewExpression()&&u.node.callee===c.node||u.isTaggedTemplateExpression()&&u.node.tag===c.node||u.isForInStatement()&&u.node.left===c.node||u.isForOfStatement()&&u.node.left===c.node:!0},i=l=>{if(!l.node.computed||!hn.isIdentifier(l.node.object))return!1;let c=l.get("property");if(!c.isBinaryExpression({operator:"-"})||!hn.isNumericLiteral(c.node.right)||!Number.isSafeInteger(c.node.right.value)||c.node.right.value<=0)return!1;let u=c.get("left");return!u.isMemberExpression()||Du(u.node)!=="length"||!hn.isIdentifier(u.node.object)?!1:l.scope.getBinding(l.node.object.name)===u.scope.getBinding(u.node.object.name)},s=l=>{let c=n.get(l.identifier);if(c!==void 0)return c;if(t.has(l.identifier))return!0;t.add(l.identifier);let u=l.referencePaths.every(d=>{let f=d.parentPath;if(!f?.isMemberExpression()||f.node.object!==d.node)return!1;let m=Du(f.node);if(m==="map"||m==="forEach"){let g=f.parentPath;return g.isCallExpression()&&g.node.callee===f.node&&r(g)}return(m==="length"||f.node.computed&&hn.isNumericLiteral(f.node.property)||i(f))&&!o(f)});return t.delete(l.identifier),n.set(l.identifier,u),u},a=(l,c)=>{if(!l.node||c.has(l.node)||c.size>=32)return!1;let u=new Set(c).add(l.node);if(l.isTSAsExpression()||l.isTSTypeAssertion()||l.isTSSatisfiesExpression()||l.isTSNonNullExpression()||l.isParenthesizedExpression())return a(l.get("expression"),u);if(l.isIdentifier()){let d=l.scope.getBinding(l.node.name);return!!(d?.constant&&d.kind==="const"&&!d.constantViolations.length&&d.path.isVariableDeclarator()&&hn.isIdentifier(d.path.node.id)&&d.path.node.start!=null&&l.node.start!=null&&d.path.node.start<l.node.start&&s(d)&&a(d.path.get("init"),u))}if(l.isArrayExpression())return l.node.elements.every(d=>d!==null&&!hn.isSpreadElement(d));if(l.isCallExpression()){let d=l.get("callee");return d.isMemberExpression()&&Du(d.node)==="map"&&r(l)&&a(d.get("object"),u)}return!1};return i(e)&&!o(e)&&a(e.get("object"),new Set)}function Du(e){return!e.computed&&hn.isIdentifier(e.property)?e.property.name:hn.isStringLiteral(e.property)?e.property.value:null}var v_=typeof Bg=="function"?Bg:Bg.default;function k_(e){let t=new Map;for(let[n,r]of e.sources){if(!/\.[cm]?[jt]sx?$/iu.test(n))continue;let o=Te(n,r);o.ok&&v_(o.module.ast,{ImportDeclaration(i){if(i.node.importKind==="type")return;let s=At(n,i.node.source.value,e.files);if(!(!s||!e.sources.has(s)))for(let a of i.node.specifiers){if(ze.isImportSpecifier(a)&&a.importKind==="type")continue;let l=i.scope.getBinding(a.local.name);if(!l?.referencePaths.length)continue;let c=!ze.isImportNamespaceSpecifier(a)&&l.constant&&l.referencePaths.every(u=>(u.parentPath?.isJSXOpeningElement()||u.parentPath?.isJSXClosingElement())&&u.parentPath.node.name===u.node);t.set(s,(t.get(s)??!0)&&c)}}})}return new Set([...t].filter(([,n])=>n).map(([n])=>n))}function __(e){let t=Te(e.file_path,e.source),n=[],r=new Set,o=(s,a)=>{n.some(l=>l.code===s&&l.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&&iU(s,e.current_route)){r.add(e.current_route);return}if(ze.isTemplateLiteral(s)&&C_(s,e.current_route,"#"))return;if(!ze.isStringLiteral(s)){o("ROUTE_VALUE_UNRESOLVED","A navigation destination is not a proven literal.");return}let a=R_(s.value);a==="host-route"?r.add(s.value):a==="unknown"&&o("ROUTE_VALUE_UNRESOLVED","A navigation destination is unsafe or unsupported.")};return v_(t.module.ast,{JSXOpeningElement(s){let a=ze.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."),!e.allow_unassociated_form_controls&&(a==="button"||a==="input")){let l=s.node.attributes.filter(d=>ze.isJSXAttribute(d)&&ze.isJSXIdentifier(d.name)&&d.name.name.toLowerCase()==="type"),c=l.length===1&&ze.isJSXAttribute(l[0])?l[0].value:null,u=ze.isStringLiteral(c)?c.value.toLowerCase():null;(a==="button"&&u!=="button"||a==="input"&&(l.length>1||l.length===1&&!u||u==="submit"||u==="image"))&&o("ROUTE_VALUE_UNRESOLVED","A form control may submit an unproven host form.")}},JSXAttribute(s){if(!ze.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 l=s.node.value;i(ze.isJSXExpressionContainer(l)?l.expression:l)},JSXSpreadAttribute(s){e.allow_props_forwarding&&rU(s)||o("ROUTE_VALUE_UNRESOLVED","A JSX spread may contain an unproven navigation destination.")},ObjectProperty(s){let a=Oa(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=Oa(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(s){e.finite_data_ranges?.some(a=>a.start===s.node.start&&a.end===s.node.end)||o("ROUTE_VALUE_UNRESOLVED","A spread may contain an unproven navigation destination.")},MemberExpression(s){let a=Oa(s.node.property,s.node.computed);s.node.computed&&a===null&&!I_(s)&&!oU(s)&&!e.finite_data_ranges?.some(l=>l.start===s.node.start&&l.end===s.node.end)&&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)&&ze.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"&&ze.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){(ze.isIdentifier(s.node.left,{name:"location"})||ze.isMemberExpression(s.node.left)&&(Oa(s.node.left.property,s.node.left.computed)==="href"||s.node.left.computed&&Oa(s.node.left.property,!0)===null))&&o("ROUTE_VALUE_UNRESOLVED","Imperative navigation is not proven.")},CallExpression(s){ze.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 rU(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 oU(e){let t=e.get("object");if(!t.isIdentifier())return!1;let n=t.scope.getBinding(t.node.name);if(!n||!n.constant||n.kind!=="const"||!n.path.isVariableDeclarator())return!1;let r=o=>!!o&&(ze.isStringLiteral(o)||ze.isNumericLiteral(o)||ze.isBooleanLiteral(o)||ze.isNullLiteral(o)||ze.isArrayExpression(o)&&o.elements.every(r)||ze.isObjectExpression(o)&&o.properties.every(i=>ze.isObjectProperty(i)&&!i.computed&&r(i.value)));return r(n.path.node.init)?n.referencePaths.every(o=>{let i=o.parentPath;if(!i?.isMemberExpression()||i.node.object!==o.node)return!1;for(;i.parentPath?.isMemberExpression()&&i.parentPath.node.object===i.node;)i=i.parentPath;for(;i.parentPath&&(i.parentPath.isTSAsExpression()||i.parentPath.isTSNonNullExpression()||i.parentPath.isTSTypeAssertion()||i.parentPath.isParenthesizedExpression());)i=i.parentPath;let s=i.parentPath;return!s?.isUpdateExpression()&&!(s?.isAssignmentExpression()&&s.node.left===i.node)&&!s?.isUnaryExpression({operator:"delete"})&&!(s?.isCallExpression()&&s.node.callee===i.node)&&!(s?.isOptionalCallExpression()&&s.node.callee===i.node)&&!s?.isMemberExpression()&&!s?.isOptionalMemberExpression()}):!1}function iU(e,t){return C_(e,t,"?")}function C_(e,t,n){if(!t||t.includes("?")||t.includes("#")||R_(t)!=="host-route")return!1;let r=ze.isStringLiteral(e)?[e.value]:ze.isTemplateLiteral(e)?e.quasis.map(o=>o.value.cooked):[];return r.length>0&&typeof r[0]=="string"&&r[0].startsWith(n)&&r.every(o=>typeof o=="string"&&o.length<=2048&&!/[\s\u0000-\u0020\u007f-\u009f\\]/u.test(o))}function Oa(e,t){return ze.isStringLiteral(e)?e.value:!t&&ze.isIdentifier(e)?e.name:t&&ze.isNumericLiteral(e)?String(e.value):null}function R_(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 N_=512,fU=1024*1024,pU=8*1024*1024,A_=256;function mU(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||T_(e.snapshot_files)!==e.snapshot_digest||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset%P_!==0)return t();let n=e.exported.asset_catalog.filter(l=>l.asset_key===e.asset_key);if(n.length!==1)return t();let r=n[0];if(r.origin.kind!=="snapshot")return t();let o=r.origin.path;if(!o||/[\\\0%?#:]/u.test(o)||o.startsWith("/")||o.split("/").some(l=>!l||l.startsWith(".")||l==="node_modules"))return t();let i=e.snapshot_files.get(o);if(!(i instanceof Uint8Array)||!i.byteLength||i.byteLength>lU||e.offset>=i.byteLength)return t();let s=gU(o,i);if(!s)return t();let a=Buffer.from(i);return{complete:!0,snapshot_digest:e.snapshot_digest,asset_key:e.asset_key,path:o,mime_type:s,byte_size:a.byteLength,digest_sha256:Bu("sha256").update(a).digest("hex"),offset:e.offset,data_base64:a.subarray(e.offset,e.offset+P_).toString("base64")}}function gU(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===Da.path&&t.byteLength===Da.byte_size&&Bu("sha256").update(t).digest("hex")===Da.digest_sha256?"image/svg+xml":null}async function hU(e){if(e.snapshot.site_id!==e.site_id||e.snapshot.snapshot_id!==e.base_snapshot_id)return yn("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=uU.safeParse(e.target),l=sU.safeParse(e.selection_ref);if(!a.success||!l.success)return yn("BLOCK_SELECTION_INVALID","<selection>","The block target or render occurrence is invalid.");let c=a.data,u=l.data,d=Mu(o,t,n,r);if(d)return d;let f=aU.safeParse(e.host_capabilities);if(!f.success)return yn("HOST_CAPABILITIES_INVALID","<host-capabilities>","The host capability contract is invalid.");let m=new Map;for(let[F,q]of e.snapshot.files){if(typeof q!="string"&&!(q instanceof Uint8Array))return yn("SNAPSHOT_CONTENT_MISMATCH",F,"A Snapshot file has an unsupported content type.");m.set(F,typeof q=="string"?q:new Uint8Array(q))}if(!xU(e.snapshot.manifest,t,n,m))return yn("SNAPSHOT_CONTENT_MISMATCH","<snapshot>","The file mapping does not match the authenticated Snapshot manifest.");let g=T_(m),p=await $m({site_id:t,base_snapshot_id:n,composition:c.composition,document_version:r,target:c,selection_ref:u,files:m});if(!p.ok)return yn(`BLOCK_${p.code}`,c.blockKey,p.message);if(!p.binding.descriptor.capabilities.save)return yn("BLOCK_EXPORT_NOT_ALLOWED",c.blockKey,"The selected block is not exportable.");let h=s_({binding:p.binding,files:m,hostCapabilities:f.data}),x;if(!h.complete){let F=La(h.errors.map(({code:ht,path:nn,message:tr})=>({code:ht,path:nn,message:tr})));if(!h.errors.some(ht=>ht.code==="INVOCATION_VALUE_UNRESOLVED"))return F;let q=Qo(m,i)?Ik({binding:p.binding,target:c,files:m,trusted_host_file_hashes:i}):null,ee=q?.complete?[]:await S_({binding:p.binding,files:m}),qe=Mu(o,t,n,r);if(qe)return qe;if(!q?.complete)return ee.length?{...F,cms_candidates:{kind:"partial-unproven",slugs:ee}}:F;h={complete:!0,selection:q.selection},x=q.extracted}let b=x??Ym({selection:h.selection,files:m,defer_module_closure:!0});if(!b.complete)return La(b.errors.map(({code:F,path:q,message:ee})=>({code:F,path:q,message:ee})));let E=new Map(m);for(let F of b.source_files){let q=E.get(F.path);if(q!==void 0&&!yU(q,F.content))return yn("SOURCE_COLLISION",F.path,"An extracted entry conflicts with the pinned Snapshot.");E.set(F.path,F.content)}let S=vr({entry_files:[b.entry_file],files:E,max_nodes:N_}),v=S.nodes.filter(F=>jg(F.path)&&i.get(F.path)===Fa(E.get(F.path))).map(F=>F.path),A=yu({closure:S,host_capabilities:f.data,platform_managed_paths:v,platform_managed_packages:["server-only"]}),I=await h_({files:E,entry_file:b.entry_file,entry_export:h.selection.entry_export,invocation_bindings:b.invocation_bindings,external_packages:[...f.data.runtime_dependencies.map(F=>F.name),"server-only"],external_sources:new Map(A.nodes.filter(F=>F.kind==="source"&&["host-public","platform-managed"].includes(F.ownership)&&i.get(F.path)===Fa(E.get(F.path))).map(F=>[F.path,`@/${F.path}`]))});if(!I.complete)return La(I.errors);for(let F of I.files)E.set(F.path,F.content);let _=vr({entry_files:[I.entry_file],files:E,max_nodes:N_}),k=yu({closure:_,host_capabilities:f.data,platform_managed_paths:v,platform_managed_packages:["server-only"]}),T=[],L=_k({entry_file:I.entry_file,entry_export:I.entry_export,files:E,confirmed_slugs:new Set(s.map(F=>F.source_slug)),allow_build_sample:mk(E,i),on_build_only_value:F=>T.push(F)}),$=L.dependencies.length>0,J=[...k.errors.map(({code:F,path:q,message:ee})=>({code:F,path:q,message:ee})),...L.unresolved.map(({code:F,source_path:q,message:ee,call_site:qe})=>({code:F,path:q,message:ee,...qe?{call_site:qe}:{}}))];if(L.complete){let F=new Set(L.dependencies.map(ee=>ee.slug)),q=new Set;$&&s.length>0&&s.length!==L.dependencies.length&&J.push({code:"CMS_SCHEMA_DEPENDENCY_UNPROVEN",path:"<cms-schema>",message:"Every selected application requires exactly one matching schema."});for(let ee of s){if(q.has(ee.source_slug)||!F.has(ee.source_slug)){J.push({code:"CMS_SCHEMA_DEPENDENCY_UNPROVEN",path:"<cms-schema>",message:"The schema proof does not identify a unique CMS dependency used by the selected block."});break}q.add(ee.source_slug)}}let z=new Set(v);for(let F of _.nodes)$&&/^(?:src\/)?lib\/cms\/jsonld\.tsx$/u.test(F.path)&&!ku(E,i,F.path)&&J.push({code:"HOST_CMS_IMPLEMENTATION_UNPROVEN",path:F.path,message:"A modified CMS helper cannot be omitted from the exported code dependencies."}),jg(F.path)&&!z.has(F.path)&&J.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 k.nodes)F.kind==="external"||F.ownership!=="host-public"||jg(F.path)||i.get(F.path)!==Fa(m.get(F.path))&&J.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 Z=new Map(k.nodes.map(F=>[F.path,F.ownership])),W=[],Ee=new Set(I.files.map(F=>F.path));for(let F of _.nodes){if(Z.get(F.path)!=="private"||F.kind==="asset"&&!F.path.endsWith(".css"))continue;if(F.kind==="source"&&!Ee.has(F.path)){J.push({code:"SOURCE_BUNDLE_UNPROJECTED",path:F.path,message:"A private dependency bypassed the isolated source projection."});continue}let q=E.get(F.path),ee=null;try{typeof q=="string"?ee=q:q instanceof Uint8Array&&(ee=new TextDecoder("utf-8",{fatal:!0}).decode(q))}catch{}ee===null?J.push({code:"SOURCE_TEXT_UNSUPPORTED",path:F.path,message:"A private source dependency is not valid UTF-8 text."}):W.push({path:F.path,content:ee})}for(let F of W)(/^(?:src\/)?components\/site\/generated\/(?:forms|product-search)\//u.test(F.path)||F.path==="lib/generated/product-search-config.json")&&J.push({code:"MANAGED_REQUIREMENT_UNPROVEN",path:F.path,message:"A managed capability requires a proven requirement before exporting the block."});W.some(F=>F.path===I.entry_file)||J.push({code:"ENTRY_NOT_PRIVATE",path:I.entry_file,message:"The selected entry is not site-owned source."});let xe=0;for(let F of W){let q=Buffer.byteLength(F.content,"utf8");xe+=q,(q>fU||xe>pU)&&J.push({code:"SOURCE_BUDGET_EXCEEDED",path:F.path,message:"The selected source exceeds its export byte budget."})}let Ce=x_({source_files:W,snapshot_files:m,host_sources:k.nodes.flatMap(F=>{if(F.kind!=="source"||!["host-public","platform-managed"].includes(F.ownership))return[];let q=Ft(E.get(F.path)),ee=i.get(F.path);return q!==null&&ee?[{path:F.path,content:q,digest:ee}]:[]}),excluded_source_ranges:L.complete?T:[]});Ce.complete||J.push(...Ce.errors);let Me=[];if(Ce.complete){let F=new Map(W.map(ee=>[ee.path,ee.content])),q=new Set;for(let ee of k.nodes){if(ee.kind!=="source"||!["host-public","platform-managed"].includes(ee.ownership))continue;let qe=Ft(E.get(ee.path));qe!==null&&F.set(ee.path,qe),/^(?:src\/)?components\/ui\/safe-image\.tsx$/u.test(ee.path)&&i.get(ee.path)===`sha256:${cU.digest_sha256}`&&q.add(ee.path)}for(let ee of Ce.catalog.bindings){if(ee.kind!=="host-dependency")continue;let qe=Ce.catalog.assets.find(ht=>ht.asset_key===ee.asset_key);(!q.has(ee.file_path)||qe.origin.kind!=="snapshot"||qe.origin.path!==Da.path||Fa(m.get(qe.origin.path))!==`sha256:${Da.digest_sha256}`)&&J.push({code:"ASSET_HOST_RELOCATION_REQUIRED",path:ee.file_path,message:"An omitted host resource requires an explicit deterministic relocation contract."})}J.push(...b_({sources:F,files:E,bindings:Ce.catalog.bindings,on_finite_data:ee=>Me.push(ee),cms_sources:L.complete?L.dependencies.flatMap(ee=>ee.evidence):[],excluded_sources:q,trusted_data_adapters:Qo(E,i)?new Set(["lib/cms/field.ts","src/lib/cms/field.ts"]):new Set}).errors)}let bt=new Map;if(L.complete){let F=new Map(W.map(ee=>[ee.path,ee.content]));for(let ee of k.nodes){if(ee.kind!=="source"||!["host-public","platform-managed"].includes(ee.ownership))continue;let qe=E.get(ee.path);try{if(typeof qe=="string")F.set(ee.path,qe);else if(qe instanceof Uint8Array)F.set(ee.path,new TextDecoder("utf-8",{fatal:!0}).decode(qe));else throw new Error("missing source")}catch{L.dependencies.length===0&&J.push({code:"ROUTE_SOURCE_UNAVAILABLE",path:ee.path,message:"A host source cannot be inspected for navigation."})}}let q=k_({sources:F,files:E});for(let[ee,qe]of F){if(!/\.[cm]?[jt]sx?$/iu.test(ee))continue;let ht=__({file_path:ee,source:qe,current_route:c.composition.routeId,finite_data_ranges:Me.filter(nn=>nn.file_path===ee),allow_unassociated_form_controls:!0,allow_props_forwarding:ee!==b.entry_file&&q.has(ee)});L.dependencies.length===0&&J.push(...ht.errors);for(let nn of ht.dependencies)bt.set(nn.href,nn)}bt.size>256&&L.dependencies.length===0&&J.push({code:"ROUTE_BUDGET_EXCEEDED",path:"<routes>",message:"The selected source exceeds its route dependency limit."})}let Ie=L.complete&&L.dependencies.length>0&&s.length===L.dependencies.length&&new Set(s.map(F=>F.source_slug)).size===s.length&&L.dependencies.every(F=>s.some(q=>q.source_slug===F.slug)&&F.evidence.every(q=>["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"].includes(q.operation)))&&Qo(E,i);if(J.length>0||!_.complete||!k.complete||!L.complete){let F=[...new Set([...L.dependencies.map(qe=>qe.slug)])].sort();if(!(F.length>0&&F.length<=16&&new Set(F).size===F.length&&F.every(qe=>/^[a-z0-9][a-z0-9_-]{0,123}$/u.test(qe))))return La(J);let ee=Mu(o,t,n,r);return ee||{...La(J),cms_candidates:{kind:"partial-unproven",slugs:F}}}let ot=Mu(o,t,n,r);if(ot)return ot;let Ve={complete:!0,export_schema_version:2,site_id:t,base_snapshot_id:n,snapshot_digest:g,document_version:r,target:h.selection.target,selection_ref:b.selected_root_ref,entry:{file:I.entry_file,export:I.entry_export},files:W.map(({path:F,content:q})=>({path:F,content:q})),source_closure:_,dependency_audit:k,cms:L,asset_catalog:Ce.complete?Ce.catalog.assets:[],asset_bindings:Ce.complete?Ce.catalog.bindings:[],source_projections:I.source_projections,compiler:I.compiler,invocation_bindings:b.invocation_bindings,host_contract_digest:f.data.host_contract_digest,...L.dependencies.length===0?{route_dependencies:[...bt.values()].sort((F,q)=>F.href.localeCompare(q.href))}:{},...Ie?{cms_sample_proof:{kind:"whole-application"}}:{}};return dU.safeParse(Ve).success?Ve:yn("PORTABLE_EXPORT_RESULT_INVALID","<export>","The selected source result failed its bounded export contract.")}function Mu(e,t,n,r){if(!Number.isSafeInteger(r)||r<0)return yn("DOCUMENT_VERSION_STALE","<document>","The selected document version is invalid.");try{let o=e();return o.site_id!==t||o.snapshot_id!==n?yn("SNAPSHOT_MISMATCH","<snapshot>","The live runtime no longer matches the requested Snapshot."):o.document_version!==r?yn("DOCUMENT_VERSION_STALE","<document>","The live document version changed during export."):null}catch{return yn("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live runtime identity could not be verified.")}}function T_(e){let t=Bu("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 yU(e,t){return typeof e=="string"?e===t:Buffer.from(e).equals(Buffer.from(t,"utf8"))}function jg(e){return/^(?:src\/)?lib\/cms(?:\.[cm]?[jt]sx?$|\/(?!generated\/))/u.test(e)}function Fa(e){return e===void 0?null:`sha256:${Bu("sha256").update(e).digest("hex")}`}function xU(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||Fa(s)!==i.hash||(typeof s=="string"?Buffer.byteLength(s,"utf8"):s.byteLength)!==i.size_bytes)return!1}return!0}function yn(e,t,n){return{complete:!1,unresolved:[{code:e,path:t,message:n}]}}function La(e){return e.length?e.length<=A_?{complete:!1,unresolved:e}:{complete:!1,unresolved:[...e.slice(0,A_-1),{code:"PORTABLE_DIAGNOSTICS_TRUNCATED",path:"<selection>",message:"Additional unresolved export diagnostics were omitted."}]}:yn("PORTABLE_EXPORT_INCOMPLETE","<selection>","The selected block's export proof is incomplete.")}import $g from"@babel/generator";import{parse as bU}from"@babel/parser";import EU from"@babel/traverse";import*as Ut from"@babel/types";var Ug=EU,SU=typeof Ug=="function"?Ug:Ug.default,IU=typeof $g=="function"?$g:$g.default,M_="components/site/generated/{{$INSTANCE}}/",B_=new Set([".tsx",".ts",".jsx",".js"]),w_=new Set(["data-site-block-id","data-vcp-block-id","data-vcp-edit-key"]),vU=new Set(["data-site-block-order","data-vcp-order"]);function kU(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 E of e.source_files){let S=Ur(E.path);if(!S||n.has(S)){t.push({code:"SOURCE_INPUT_INVALID",path:E.path,message:"Portable source files must have unique safe paths."});continue}n.set(S,{...E,path:S})}for(let E of e.ownership){let S=Ur(E.path);if(!S||r.has(S)){t.push({code:"SOURCE_INPUT_INVALID",path:E.path,message:"Portable source ownership entries must be unique and safe."});continue}r.set(S,{...E,path:S})}let o=Ur(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 E of n.keys())r.has(E)||t.push({code:"SOURCE_OWNERSHIP_MISSING",path:E,message:"Every source closure file requires an ownership decision."});let s=[...n.keys()].filter(E=>r.get(E)?.ownership==="private").sort((E,S)=>E.localeCompare(S)),a=s.map(E=>({source_path:E,path_template:wU(E)})),l=new Map(a.map(E=>[E.source_path,E.path_template])),c=_U(e.source_mapping??[],l,t),u=CU(e.required_source_paths??[],l,t),d=[],f=new Map,m=[];for(let E of s){let S=n.get(E);if(!S)continue;let v=PU(E,S.content,r,l,d,f,t);v!==null&&m.push({path_template:l.get(E),content:v,...S.role?{role:S.role}:{}})}let g=F_(t).sort(D_);if(g.length>0)return{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:g};let p=m.map(E=>{let S=a.find(A=>A.path_template===E.path_template)?.source_path,v=n.get(S)?.content??"";return{source_path:S,path_template:E.path_template,original_byte_size:O_(v),output_byte_size:O_(E.content),original_line_count:L_(v),output_line_count:L_(E.content)}}),h=[...f.values()].map(E=>({...E,normalized:!0})).sort((E,S)=>E.source_path.localeCompare(S.source_path)),x=l.get(o)??null;if(e.thin_entry_plan){let E=RU(e.thin_entry_plan,l,t);E&&(m.push(E),x=E.path_template)}let b=F_(t).sort(D_);return b.length>0?{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:b}:{complete:!0,entry_path_template:x,files:m.sort((E,S)=>E.path_template.localeCompare(S.path_template)),source_path_mappings:p.sort((E,S)=>E.path_template.localeCompare(S.path_template)),required_path_mappings:u,source_mapping:c,managed_rebindings:d.sort(MU),block_metadata:h,errors:[]}}function _U(e,t,n){let r=new Set,o=[];for(let[i,s]of e.entries()){let a=Ur(s.generated_path),l=Ur(s.source_file),c=a,u=t.get(a);if(!a||a!==s.generated_path||!l||l!==s.source_file||!s.structural_path||r.has(c)){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(c),!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 CU(e,t,n){let r=new Set,o=new Set,i=[];for(let[s,a]of e.entries()){let l=Ur(a.source_path);if(!/^[a-z][a-z0-9-]{0,127}$/u.test(a.key)||!l||r.has(a.key)||o.has(l)){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(l);let c=t.get(l);if(!c){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:l,path_template:c})}return i.sort((s,a)=>s.key.localeCompare(a.key)||s.source_path.localeCompare(a.source_path))}function RU(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(Ur(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=`${M_}__managed-root-entry.tsx`,i=j_(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
53
|
export default function PortableManagedRootEntry(props: Parameters<typeof Root>[0]) {
|
|
50
54
|
return <Root {...props} />;
|
|
51
55
|
}
|
|
52
|
-
`}}function
|
|
53
|
-
`).length}function d_(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function f_(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||(e.specifier??"").localeCompare(t.specifier??"")}function vU(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 IU from"node:path";import{GeneratedSiteCapabilitiesSchema as kU,FormDefinitionIdSchema as _U,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as RU,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as PU,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as CU,SiteEditMaterializationExportSchema as NU,SiteEditMaterializationSchema as AU,SiteEditSourcePathSchema as TU}from"@vcp-dev/contracts";var fu="components/site/generated",wU=/^[a-z][a-z0-9._-]{0,127}$/,mu=/^[a-z][a-z0-9._-]{0,127}$/,OU=new Set(["collection-detail-view","i18n-companion","client-importer"]);function FU(e){if(!Ti(e))return qe("PORTABLE_INPUT_INVALID","Portable materialization input must be an object.","input");if(typeof e.instanceId!="string"||!wU.test(e.instanceId))return qe("PORTABLE_INSTANCE_INVALID","Portable instanceId must be a single safe directory name.","instanceId");let t=kU.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(!BU(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!_U.safeParse(p).success||!pu(e.existingSources,`${m.slice(2)}.tsx`)})))return qe("PORTABLE_INPUT_INVALID","Trusted managed imports must name exact existing canonical form sources.","trustedManagedImports");let n=LU(e.resolved);if(!n.ok)return n;let r=AU.safeParse(n.materialization);if(!r.success)return qe("PORTABLE_INPUT_INVALID","Resolved portable materialization failed the strict contract.","resolved.materialization");let o=DU(n.relatedEntries,r.data);if(!o.ok)return o;let i=MU(e.entryConsumers,o.data,r.data,e.existingSources);if(!i.ok)return i;let s=IU.posix.join(fu,e.instanceId),a=[],l=new Set;for(let m of r.data.files){let p=ns({pathTemplate:m.pathTemplate,generatedRoot:fu,instanceName:e.instanceId,instanceRoot:s});if(!p.ok)return xg(p.error);if(l.has(p.data))return qe("MATERIALIZATION_PATH_INVALID",`Portable materialization resolves duplicate target path: ${p.data}`,p.data);l.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>PU)return qe("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file count exceeds the reusable limit.");let c=0;for(let m of a){let p=Buffer.byteLength(m.content,"utf8");if(p>RU)return qe("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file exceeds the per-file content limit.",m.path);c+=p}if(c>CU)return qe("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization exceeds the reusable total content limit.");let u=b_(r.data.entry.pathTemplate,r.data.entry.export,l,e.instanceId,s);if(!u.ok)return u;let d=[],f=[u.data];for(let m of o.data){let p=b_(m.pathTemplate,m.export,l,e.instanceId,s);if(!p.ok)return p;d.push({...m,path:p.data.path}),f.push(p.data)}if(pu(e.existingSources,s)||a.some(m=>pu(e.existingSources,m.path)))return qe("PORTABLE_INSTANCE_CONFLICT","Portable materialization cannot overwrite an existing instance source.",s);let g=Jd({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:fu,instanceRoot:s,entry:u.data,relatedEntries:d.sort((m,p)=>m.path.localeCompare(p.path)),entryConsumers:i.data,files:a}}):xg(g.error)}function LU(e){if(!Ti(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&&!Ti(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 DU(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,l]of e.entries()){if(!Ti(l))return qe("PORTABLE_INPUT_INVALID","Every related entry must be an object.",`resolved.relatedEntries[${a}]`);let c=l.key,u=l.requirementKey,d=l.pathTemplate,f=l.purpose,g=NU.safeParse(l.export);if(typeof c!="string"||!mu.test(c)||typeof u!="string"||!mu.test(u)||typeof d!="string"||typeof f!="string"||!OU.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(c)||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(c),i.add(d),s.push({key:c,pathTemplate:d,export:g.data,purpose:f,requirementKey:u})}return{ok:!0,data:s}}function MU(e,t,n,r){let o=new Map(t.map(c=>[c.key,c])),i=new Set((n.dataRequirements??[]).map(c=>c.key)),s=new Set,a=[];for(let[c,u]of e.entries()){if(!Ti(u))return qe("PORTABLE_INPUT_INVALID","Every entry consumer must be an object.",`entryConsumers[${c}]`);let d=u.entry_key,f=u.requirement_key,g=u.kind,m=u.consumer_path;if(typeof d!="string"||!mu.test(d)||typeof f!="string"||!mu.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[${c}]`);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"||!TU.safeParse(m).success||!/^app\/.*\/page\.tsx$/u.test(m)||!pu(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 l=t.find(c=>!s.has(c.key));return l?qe("PORTABLE_ENTRY_UNCONSUMED","Every related entry must be consumed by its managed route or capability.",l.key):{ok:!0,data:a.sort((c,u)=>c.entry_key.localeCompare(u.entry_key)||c.consumer_path.localeCompare(u.consumer_path))}}function b_(e,t,n,r,o){let i=ns({pathTemplate:e,generatedRoot:fu,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):xg(i.error)}function pu(e,t){return Array.isArray(e)?e.includes(t):e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function BU(e){return Array.isArray(e)||e instanceof Map||Ti(e)}function Ti(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xg(e){return{ok:!1,error:e}}function qe(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import E_ from"node:path";import{SiteEditSourcePathSchema as bg}from"@vcp-dev/contracts";function jU(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||!bg.safeParse(e.entryFile).success||!bg.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 Tt("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 Tt("INVALID_TARGET","The verified Portable owner is absent from the fixed source map.",t.ownerFile);if(Te(n)!==t.sourceHash)return Tt("VERSION_STALE","The Portable boundary owner changed after resolution.",t.ownerFile);let r=KU(e);return r||(e.binding.root.ownerNode.kind==="route-member"?t.ownerFile!==e.entryFile?Tt("INVALID_TARGET","A route-member block boundary must remain in its route entry file.",t.ownerFile):$U(e,n):VU(e,n))}function $U(e,t){let n=Ee(e.entryFile,t);if(!n.ok)return Tt("PORTABLE_ROUTE_SOURCE_INVALID",n.diagnostic.message,e.entryFile);let r=On({route:e.routeId,composition:e.binding.composition,entryFile:e.entryFile,version:e.documentVersion,source:t,ast:n.module.ast});if(!r.ok)return Tt("PORTABLE_ROUTE_UNSUPPORTED","The route owner does not expose a supported composition boundary.",e.entryFile);let o=UU(r.projection.placements,e.resolvedBoundary.anchorLocator.sourceRange,e.resolvedBoundary.placement);if(!o)return Tt("INVALID_TARGET","The exact route-member boundary has no unique page-composition member.",e.entryFile);let i=af({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 Tt(i.error.code,i.error.message,e.entryFile);if(i.patch.path!==e.resolvedBoundary.ownerFile||i.patch.expectedSourceHash!==e.resolvedBoundary.sourceHash)return Tt("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||!Sg(a,e.resolvedBoundary.anchorLocator.sourceRange))?Tt("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 UU(e,t,n){let r=e.flatMap(o=>o.relation!==n||!o.anchorSourceRange||!Sg(o.anchorSourceRange,t)?[]:S_(o.members).filter(i=>i.sourceRange!==null&&Sg(i.sourceRange,t)));return r.length===1?r[0].label:null}function S_(e){return e.flatMap(t=>[t,...S_(t.children)])}function VU(e,t){let n=e.resolvedBoundary,r=n.parentLocator;if(!r)return Tt("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 Tt("INVALID_TARGET","The verified shared owner parent is not a JSX child container.",n.ownerFile);let o=Dr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!o.ok)return Tt(o.error.code,o.error.message,n.ownerFile);if(o.plan.requiresRouteParams)return Tt("UNSUPPORTED_ROUTE_PARAMS","A captured native detail parameter cannot be injected into an unproven shared owner.",n.ownerFile);let i=JU(t,n.ownerFile,r,o.plan.bindings);if(i)return i;let s=Sn({source:t,locator:Eg(r),anchorLocator:Eg(n.anchorLocator),placement:n.placement,node:{jsx:o.plan.jsx}});if(!s.ok)return Tt("PORTABLE_BLOCK_PATCH_FAILED",s.diagnostic.message,n.ownerFile);let a=vn({source:s.source,moduleSpecifier:XU(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}]}:Tt("PORTABLE_BLOCK_PATCH_FAILED",a.diagnostic.message,n.ownerFile)}function KU(e){return!bg.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)?Tt("INVALID_TARGET","The Portable component source or export is not a safe materialized reference.",e.component.source):null}function JU(e,t,n,r){if(!r.some(s=>s.value.kind==="route-search-params"))return null;let o=Ee(t,e);if(!o.ok)return Tt("INVOCATION_VALUE_UNRESOLVED",o.diagnostic.message,t);let i=Ne(o.module.ast,Eg(n));return!i.ok||!i.match.path.scope.getBinding("searchParams")?Tt("INVOCATION_VALUE_UNRESOLVED","The shared owner has no proven searchParams binding for this invocation.",t):null}function Eg(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 XU(e,t){let n=E_.posix.relative(E_.posix.dirname(e),t.replace(/\.(?:tsx?|jsx?)$/u,""));return n=n.replaceAll("\\","/"),n.startsWith(".")?n:`./${n}`}function Sg(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function Tt(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import{parse as zU}from"@babel/parser";import vg from"@babel/traverse";import*as Pt from"@babel/types";var HU=typeof vg=="function"?vg:vg.default,WU=new Set(["slice","map","trim","toString"]);function GU(e){let t=new Set;try{let n=zU(e,{sourceType:"module",plugins:["jsx","typescript"]});HU(n,{JSXExpressionContainer(r){let o=r.get("expression");oa(o,new Set)==="url"&&t.add(`${r.node.start}:${r.node.end}`)}})}catch{}return t}function oa(e,t){if(e.isMemberExpression()||e.isOptionalMemberExpression()){let a=oa(e.get("object"),t),l=e.node;return!l.computed&&Pt.isIdentifier(l.property,{name:"thumbnail"})&&a==="record"?"array":l.computed&&Pt.isNumericLiteral(l.property)&&Number.isSafeInteger(l.property.value)&&l.property.value>=0&&a==="array"?"item":!l.computed&&Pt.isIdentifier(l.property,{name:"url"})&&a==="item"?"url":null}if(e.isCallExpression()){let a=e.get("callee");return!a.isMemberExpression()||a.node.computed||!Pt.isIdentifier(a.node.property,{name:"slice"})||!e.node.arguments.every(l=>Pt.isNumericLiteral(l)&&Number.isSafeInteger(l.value)&&l.value>=0)?null:oa(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)||!Ig(n,new Set))return null;let r=new Set(t).add(n);if(n.path.isVariableDeclarator()&&Pt.isIdentifier(n.path.node.id))return oa(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=>Pt.isObjectPattern(a)&&a.properties.some(l=>Pt.isObjectProperty(l)&&!l.computed&&Pt.isIdentifier(l.key,{name:"record"})&&Pt.isIdentifier(l.value,{name:"record"}))))return"record";if(!o.isArrowFunctionExpression()||!Pt.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||!Pt.isIdentifier(s.node.property,{name:"map"})?null:oa(s.get("object"),r)==="array"?"item":null}function Ig(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(!Pt.isIdentifier(o.node.id)||o.node.init!==r.node)return!1;let i=o.scope.getBinding(o.node.id.name);return!!i&&Ig(i,t)}if(o.isCallExpression()||o.isOptionalCallExpression()){if(!(o.node.callee===r.node&&(r.isMemberExpression()||r.isOptionalMemberExpression())&&!r.node.computed&&Pt.isIdentifier(r.node.property)&&WU.has(r.node.property.name)))return!1;if((r.isMemberExpression()||r.isOptionalMemberExpression())&&Pt.isIdentifier(r.node.property,{name:"map"})){let s=o.get("arguments.0");if(!s?.isArrowFunctionExpression()||!Pt.isIdentifier(s.node.params[0]))return!1;let a=s.scope.getBinding(s.node.params[0].name);if(!a||!Ig(a,t))return!1}return!0}return r!==n}):!1)}export{ke as FileHistoryStoreError,gs as PageTemplateManagedSourceError,Dl as PreviewFileSystemSiteEditEngineRuntime,ex as SITE_EDIT_RAW_COLOR_LITERAL_RE,Fl as SnapshotSiteEditEngineRuntime,t$ as analyzePortableCollectionInvocation,Pi as analyzePortableInvocation,Um as analyzePortableRelatedEntries,$d as auditGeneratedCode,Ml as auditPortableDependencies,ps as buildPageBlockIndex,Dr as buildPortableInvocation,FU as buildPortableMaterializationPlan,ar as buildPortableSourceClosure,Fi as checkComponentI18nHostCompatibility,Si as classifyPortableDependencyOwnership,dm as cmsFieldAccessor,vb as computeManagedPageTemplatePaths,WB as createPreviewSiteEditEngineRuntime,JB as createSiteEditEngineRuntime,bb as decodePageTemplateKey,$m as discoverPortableCollectionSourceRelation,y0 as discoverPortableExistingCollectionRelation,Af as encodePageTemplateId,tU as exportPortableBlockFromSnapshot,_m as extractPortableBlockEntry,fm as generateCollectionAdapter,lR as instrumentSiteEditRuntimeAttributes,Ib as isManagedPageTemplateSourcePath,YT as normalizePortableBlockMetadata,lU as normalizePortableSource,Ey as openFileHistoryStore,H_ as parseSourceModule,jU as planPortableBlockPatch,af as planPortableRouteCompositionPatch,ss as planRouteCompositionRewrite,GU as provenRecordThumbnailRanges,Q$ as readPortableBlockLocalAssetChunk,W_ as resolveImportBase,MO as resolveManagedPageTemplateComposition,Pc as resolvePageBlockBoundary,mm as resolvePageBlockFromSnapshot,ni as resolvePageBlockTarget,On as resolvePageCompositionProjection,y$ as resolvePortableBlockSelection,YB as resolvePortableDependencyOwnership,ht as resolvePortableSourcePath,Tc as scanManagedPageTemplateCandidates,au as scanPortableMediaReferences,wc as scanSiteEditCompositionsFromFiles,Md as scanSiteEditThemeStyleViolations,e$ as selectPortablePageUnitInvocation};
|
|
56
|
+
`}}function PU(e,t,n,r,o,i,s){if(!DU(e))return t;let a;try{a=bU(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch(c){return s.push({code:"SOURCE_PARSE_FAILED",path:e,message:c instanceof Error?c.message:String(c)}),null}let l=c=>{let u=c.value,d=NU(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}c.value=j_(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 m=AU(d.path,u);c.value=m;let g=f.requirement_key??"host-public";if(!/^[a-z][a-z0-9._-]{0,127}$/u.test(g)){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:m,requirement_key:g})};return SU(a,{ImportDeclaration(c){l(c.node.source)},ExportNamedDeclaration(c){c.node.source&&l(c.node.source)},ExportAllDeclaration(c){l(c.node.source)},CallExpression(c){let u=c.node.callee,d=c.node.arguments[0];(Ut.isImport(u)||Ut.isIdentifier(u,{name:"require"})&&c.node.arguments.length===1)&&Ut.isStringLiteral(d)&&l(d)},JSXAttribute(c){let u=OU(c.node.name);if(!u||!w_.has(u)&&!vU.has(u))return;let d=c.parentPath.parentPath?.node,f=typeof d?.start=="number"?d.start:c.node.start??0,m=`${e}:${f}`,g=i.get(m)??{source_path:e,original_block_attribute:null,original_block_id:null,original_order:null};w_.has(u)?(g.original_block_attribute=u,g.original_block_id=LU(c.node.value)):g.original_order=FU(c.node.value),i.set(m,g),c.remove()}}),IU(a,{jsescOption:{minimal:!0}}).code}function NU(e,t,n){if(!t.startsWith(".")&&!t.startsWith("@/"))return{status:"external"};let r=t.startsWith("@/")?t.slice(2):Ur(`${V_(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 j_(e,t,n){let r=V_(e),o=TU(r,t),i=o.startsWith(".")?o:`./${o}`;return $_(n)?i:U_(i)}function AU(e,t){let n=`@/${e}`;return $_(t)?n:U_(n)}function TU(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 wU(e){let t=Ur(e),n="components/site/generated/",r=t.startsWith(n)?t.slice(n.length):`source/${t}`;return`${M_}${r}`}function OU(e){return Ut.isJSXIdentifier(e)?e.name:Ut.isJSXNamespacedName(e)&&Ut.isJSXIdentifier(e.name)?`${e.namespace.name}:${e.name.name}`:null}function LU(e){return e?Ut.isStringLiteral(e)?e.value:Ut.isJSXExpressionContainer(e)&&Ut.isStringLiteral(e.expression)?e.expression.value:null:null}function FU(e){if(!e)return null;if(Ut.isStringLiteral(e)){let t=Number(e.value);return Number.isFinite(t)?t:null}return Ut.isJSXExpressionContainer(e)&&Ut.isNumericLiteral(e.expression)?e.expression.value:null}function DU(e){return[...B_].some(t=>e.endsWith(t))}function $_(e){return/\.[a-z0-9]+(?:[?#].*)?$/iu.test(e)}function U_(e){for(let t of B_)if(e.endsWith(t))return e.slice(0,-t.length);return e}function Ur(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 V_(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function O_(e){return new TextEncoder().encode(e).byteLength}function L_(e){return e.length===0?0:e.split(`
|
|
57
|
+
`).length}function F_(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function D_(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||(e.specifier??"").localeCompare(t.specifier??"")}function MU(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 BU from"node:path";import{GeneratedSiteCapabilitiesSchema as jU,FormDefinitionIdSchema as $U,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as UU,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as VU,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as KU,SiteEditMaterializationExportSchema as JU,SiteEditMaterializationSchema as XU,SiteEditSourcePathSchema as zU}from"@vcp-dev/contracts";var ju="components/site/generated",HU=/^[a-z][a-z0-9._-]{0,127}$/,Uu=/^[a-z][a-z0-9._-]{0,127}$/,WU=new Set(["collection-detail-view","i18n-companion","client-importer"]);function GU(e){if(!Qi(e))return ct("PORTABLE_INPUT_INVALID","Portable materialization input must be an object.","input");if(typeof e.instanceId!="string"||!HU.test(e.instanceId))return ct("PORTABLE_INSTANCE_INVALID","Portable instanceId must be a single safe directory name.","instanceId");let t=jU.safeParse(e.trustedHostPolicy);if(!t.success)return ct("PORTABLE_INPUT_INVALID","Portable materialization requires valid trusted host capabilities.","trustedHostPolicy");if(!Array.isArray(e.entryConsumers))return ct("PORTABLE_INPUT_INVALID","Portable materialization requires an entry consumer list.","entryConsumers");if(!QU(e.existingSources))return ct("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(g=>{if(typeof g!="string")return!0;let p=/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(g)?.[1];return!$U.safeParse(p).success||!$u(e.existingSources,`${g.slice(2)}.tsx`)})))return ct("PORTABLE_INPUT_INVALID","Trusted managed imports must name exact existing canonical form sources.","trustedManagedImports");let n=YU(e.resolved);if(!n.ok)return n;let r=XU.safeParse(n.materialization);if(!r.success)return ct("PORTABLE_INPUT_INVALID","Resolved portable materialization failed the strict contract.","resolved.materialization");let o=ZU(n.relatedEntries,r.data);if(!o.ok)return o;let i=qU(e.entryConsumers,o.data,r.data,e.existingSources);if(!i.ok)return i;let s=BU.posix.join(ju,e.instanceId),a=[],l=new Set;for(let g of r.data.files){let p=As({pathTemplate:g.pathTemplate,generatedRoot:ju,instanceName:e.instanceId,instanceRoot:s});if(!p.ok)return Vg(p.error);if(l.has(p.data))return ct("MATERIALIZATION_PATH_INVALID",`Portable materialization resolves duplicate target path: ${p.data}`,p.data);l.add(p.data),a.push({kind:"create-only",path:p.data,content:g.content,...g.role?{role:g.role}:{},sourcePathTemplate:g.pathTemplate})}if(a.length>VU)return ct("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file count exceeds the reusable limit.");let c=0;for(let g of a){let p=Buffer.byteLength(g.content,"utf8");if(p>UU)return ct("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file exceeds the per-file content limit.",g.path);c+=p}if(c>KU)return ct("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization exceeds the reusable total content limit.");let u=K_(r.data.entry.pathTemplate,r.data.entry.export,l,e.instanceId,s);if(!u.ok)return u;let d=[],f=[u.data];for(let g of o.data){let p=K_(g.pathTemplate,g.export,l,e.instanceId,s);if(!p.ok)return p;d.push({...g,path:p.data.path}),f.push(p.data)}if($u(e.existingSources,s)||a.some(g=>$u(e.existingSources,g.path)))return ct("PORTABLE_INSTANCE_CONFLICT","Portable materialization cannot overwrite an existing instance source.",s);let m=yf({preserveCapturedStyles:!0,files:a,instanceRoot:s,entries:f,hostCapabilities:t.data,trustedManagedImports:e.trustedManagedImports});return m.ok?(a.sort((g,p)=>g.path.localeCompare(p.path)),{ok:!0,data:{kind:"portable-materialization",instanceId:e.instanceId,generatedRoot:ju,instanceRoot:s,entry:u.data,relatedEntries:d.sort((g,p)=>g.path.localeCompare(p.path)),entryConsumers:i.data,files:a}}):Vg(m.error)}function YU(e){if(!Qi(e))return ct("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 ct("PORTABLE_INPUT_INVALID","Resolved related entries must be an array.","resolved.relatedEntries");if(n!==void 0&&!Qi(n))return ct("PORTABLE_INPUT_INVALID","Resolved portable descriptor must be an object.","resolved.portable");let r=n?.relatedEntries;if(r!==void 0&&!Array.isArray(r))return ct("PORTABLE_INPUT_INVALID","Resolved portable related entries must be an array.","resolved.portable.relatedEntries");let o=t,i=r;return o&&i?ct("PORTABLE_INPUT_INVALID","Resolved portable materialization must expose related entries once.","resolved.relatedEntries"):{ok:!0,materialization:e.materialization,relatedEntries:o??i??[]}}function ZU(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,l]of e.entries()){if(!Qi(l))return ct("PORTABLE_INPUT_INVALID","Every related entry must be an object.",`resolved.relatedEntries[${a}]`);let c=l.key,u=l.requirementKey,d=l.pathTemplate,f=l.purpose,m=JU.safeParse(l.export);if(typeof c!="string"||!Uu.test(c)||typeof u!="string"||!Uu.test(u)||typeof d!="string"||typeof f!="string"||!WU.has(f)||!m.success)return ct("PORTABLE_INPUT_INVALID","Every related entry must have a strict key, purpose, path and export.",`resolved.relatedEntries[${a}]`);if(o.has(c)||i.has(d))return ct("MATERIALIZATION_PATH_INVALID","Portable related entry keys and paths must be unique.",d);if(d===t.entry.pathTemplate)return ct("MATERIALIZATION_ENTRY_INVALID","A related entry cannot reuse the primary materialization entry.",d);if(!n.has(d))return ct("MATERIALIZATION_ENTRY_INVALID","Every related entry must reference a materialization file.",d);if(!r.has(u))return ct("PORTABLE_REQUIREMENT_UNRESOLVED","Every related entry must reference a resolved managed requirement.",u);o.add(c),i.add(d),s.push({key:c,pathTemplate:d,export:m.data,purpose:f,requirementKey:u})}return{ok:!0,data:s}}function qU(e,t,n,r){let o=new Map(t.map(c=>[c.key,c])),i=new Set((n.dataRequirements??[]).map(c=>c.key)),s=new Set,a=[];for(let[c,u]of e.entries()){if(!Qi(u))return ct("PORTABLE_INPUT_INVALID","Every entry consumer must be an object.",`entryConsumers[${c}]`);let d=u.entry_key,f=u.requirement_key,m=u.kind,g=u.consumer_path;if(typeof d!="string"||!Uu.test(d)||typeof f!="string"||!Uu.test(f)||typeof g!="string"||!g.trim()||m!=="route"&&m!=="capability"&&m!=="preserved-route")return ct("PORTABLE_INPUT_INVALID","Entry consumers must declare a strict entry, requirement, kind and path.",`entryConsumers[${c}]`);let p=o.get(d);if(!p)return ct("PORTABLE_ENTRY_UNCONSUMED","An entry consumer must reference a declared related entry.",d);if(m==="preserved-route"&&(p.purpose!=="collection-detail-view"||!zU.safeParse(g).success||!/^app\/.*\/page\.tsx$/u.test(g)||!$u(r,g)))return ct("PORTABLE_ENTRY_UNCONSUMED","A preserved detail entry requires an existing source route proven by the collection recipe.",d);if(s.has(d))return ct("PORTABLE_ENTRY_UNCONSUMED","A related entry must have exactly one managed consumer.",d);if(p.requirementKey!==f)return ct("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must use the related entry requirement.",d);if(!i.has(f))return ct("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:m,consumer_path:g})}let l=t.find(c=>!s.has(c.key));return l?ct("PORTABLE_ENTRY_UNCONSUMED","Every related entry must be consumed by its managed route or capability.",l.key):{ok:!0,data:a.sort((c,u)=>c.entry_key.localeCompare(u.entry_key)||c.consumer_path.localeCompare(u.consumer_path))}}function K_(e,t,n,r,o){let i=As({pathTemplate:e,generatedRoot:ju,instanceName:r,instanceRoot:o});return i.ok?n.has(i.data)?{ok:!0,data:{path:i.data,export:t}}:ct("MATERIALIZATION_ENTRY_INVALID","Portable entry must match one controlled source file.",i.data):Vg(i.error)}function $u(e,t){return Array.isArray(e)?e.includes(t):e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function QU(e){return Array.isArray(e)||e instanceof Map||Qi(e)}function Qi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vg(e){return{ok:!1,error:e}}function ct(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import J_ from"node:path";import{SiteEditSourcePathSchema as Kg}from"@vcp-dev/contracts";function eV(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 Vt("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 Vt("INVALID_TARGET","The verified Portable owner is absent from the fixed source map.",t.ownerFile);if(je(n)!==t.sourceHash)return Vt("VERSION_STALE","The Portable boundary owner changed after resolution.",t.ownerFile);let r=oV(e);return r||(e.binding.root.ownerNode.kind==="route-member"?t.ownerFile!==e.entryFile?Vt("INVALID_TARGET","A route-member block boundary must remain in its route entry file.",t.ownerFile):tV(e,n):rV(e,n))}function tV(e,t){let n=Te(e.entryFile,t);if(!n.ok)return Vt("PORTABLE_ROUTE_SOURCE_INVALID",n.diagnostic.message,e.entryFile);let r=Hn({route:e.routeId,composition:e.binding.composition,entryFile:e.entryFile,version:e.documentVersion,source:t,ast:n.module.ast});if(!r.ok)return Vt("PORTABLE_ROUTE_UNSUPPORTED","The route owner does not expose a supported composition boundary.",e.entryFile);let o=nV(r.projection.placements,e.resolvedBoundary.anchorLocator.sourceRange,e.resolvedBoundary.placement);if(!o)return Vt("INVALID_TARGET","The exact route-member boundary has no unique page-composition member.",e.entryFile);let i=Of({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 Vt(i.error.code,i.error.message,e.entryFile);if(i.patch.path!==e.resolvedBoundary.ownerFile||i.patch.expectedSourceHash!==e.resolvedBoundary.sourceHash)return Vt("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||!Xg(a,e.resolvedBoundary.anchorLocator.sourceRange))?Vt("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 nV(e,t,n){let r=e.flatMap(o=>o.relation!==n||!o.anchorSourceRange||!Xg(o.anchorSourceRange,t)?[]:X_(o.members).filter(i=>i.sourceRange!==null&&Xg(i.sourceRange,t)));return r.length===1?r[0].label:null}function X_(e){return e.flatMap(t=>[t,...X_(t.children)])}function rV(e,t){let n=e.resolvedBoundary,r=n.parentLocator;if(!r)return Vt("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 Vt("INVALID_TARGET","The verified shared owner parent is not a JSX child container.",n.ownerFile);let o=to({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!o.ok)return Vt(o.error.code,o.error.message,n.ownerFile);if(o.plan.requiresRouteParams)return Vt("UNSUPPORTED_ROUTE_PARAMS","A captured native detail parameter cannot be injected into an unproven shared owner.",n.ownerFile);let i=iV(t,n.ownerFile,r,o.plan.bindings);if(i)return i;let s=Fn({source:t,locator:Jg(r),anchorLocator:Jg(n.anchorLocator),placement:n.placement,node:{jsx:o.plan.jsx}});if(!s.ok)return Vt("PORTABLE_BLOCK_PATCH_FAILED",s.diagnostic.message,n.ownerFile);let a=Dn({source:s.source,moduleSpecifier:sV(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}]}:Vt("PORTABLE_BLOCK_PATCH_FAILED",a.diagnostic.message,n.ownerFile)}function oV(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)?Vt("INVALID_TARGET","The Portable component source or export is not a safe materialized reference.",e.component.source):null}function iV(e,t,n,r){if(!r.some(s=>s.value.kind==="route-search-params"))return null;let o=Te(t,e);if(!o.ok)return Vt("INVOCATION_VALUE_UNRESOLVED",o.diagnostic.message,t);let i=De(o.module.ast,Jg(n));return!i.ok||!i.match.path.scope.getBinding("searchParams")?Vt("INVOCATION_VALUE_UNRESOLVED","The shared owner has no proven searchParams binding for this invocation.",t):null}function Jg(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 sV(e,t){let n=J_.posix.relative(J_.posix.dirname(e),t.replace(/\.(?:tsx?|jsx?)$/u,""));return n=n.replaceAll("\\","/"),n.startsWith(".")?n:`./${n}`}function Xg(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function Vt(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import{parse as aV}from"@babel/parser";import zg from"@babel/traverse";import*as Bt from"@babel/types";var cV=typeof zg=="function"?zg:zg.default,lV=new Set(["slice","map","trim","toString"]);function uV(e){let t=new Set;try{let n=aV(e,{sourceType:"module",plugins:["jsx","typescript"]});cV(n,{JSXExpressionContainer(r){let o=r.get("expression");Ma(o,new Set)==="url"&&t.add(`${r.node.start}:${r.node.end}`)}})}catch{}return t}function Ma(e,t){if(e.isMemberExpression()||e.isOptionalMemberExpression()){let a=Ma(e.get("object"),t),l=e.node;return!l.computed&&Bt.isIdentifier(l.property,{name:"thumbnail"})&&a==="record"?"array":l.computed&&Bt.isNumericLiteral(l.property)&&Number.isSafeInteger(l.property.value)&&l.property.value>=0&&a==="array"?"item":!l.computed&&Bt.isIdentifier(l.property,{name:"url"})&&a==="item"?"url":null}if(e.isCallExpression()){let a=e.get("callee");return!a.isMemberExpression()||a.node.computed||!Bt.isIdentifier(a.node.property,{name:"slice"})||!e.node.arguments.every(l=>Bt.isNumericLiteral(l)&&Number.isSafeInteger(l.value)&&l.value>=0)?null:Ma(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()&&Bt.isIdentifier(n.path.node.id))return Ma(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=>Bt.isObjectPattern(a)&&a.properties.some(l=>Bt.isObjectProperty(l)&&!l.computed&&Bt.isIdentifier(l.key,{name:"record"})&&Bt.isIdentifier(l.value,{name:"record"}))))return"record";if(!o.isArrowFunctionExpression()||!Bt.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||!Bt.isIdentifier(s.node.property,{name:"map"})?null:Ma(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(!Bt.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&&Bt.isIdentifier(r.node.property)&&lV.has(r.node.property.name)))return!1;if((r.isMemberExpression()||r.isOptionalMemberExpression())&&Bt.isIdentifier(r.node.property,{name:"map"})){let s=o.get("arguments.0");if(!s?.isArrowFunctionExpression()||!Bt.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)}import{createHash as pV}from"node:crypto";import mV from"@babel/traverse";import*as Ye from"@babel/types";import Wg from"@babel/traverse";import*as Lt from"@babel/types";var dV=typeof Wg=="function"?Wg:Wg.default,fV=new Set(["__proto__","prototype","constructor"]);function z_(e){let t=new Map,n=new WeakMap,r=new Set,o=new Map,i=e.files??new Map,s=(h,x)=>{dV(x,{Program(b){t.set(h,b),n.set(b.node,h),b.stop()}})};s(e.file_path,e.ast);let a=h=>{if(t.has(h))return t.get(h)??null;if(t.size>=512)return null;t.set(h,null);let x=i.get(h);if(x===void 0)return null;let b=typeof x=="string"?x:new TextDecoder("utf-8",{fatal:!0}).decode(x),E=Te(h,b);return E.ok&&s(h,E.module.ast),t.get(h)??null},l=h=>n.get(h.scope.getProgramParent().path.node),c=(h,x)=>{let b=!x&&Lt.isIdentifier(h)?h.name:Lt.isStringLiteral(h)?h.value:Lt.isNumericLiteral(h)&&Number.isSafeInteger(h.value)&&h.value>=0?String(h.value):null;return b!==null&&!fV.has(b)?b:null},u=(h,x)=>{let b=[];for(let E of h.get("body"))if(!(!E.isExportNamedDeclaration()||E.node.source)){Lt.isVariableDeclaration(E.node.declaration)&&E.node.declaration.declarations.some(S=>Lt.isIdentifier(S.id,{name:x}))&&b.push(x);for(let S of E.node.specifiers)Lt.isExportSpecifier(S)&&Lt.isIdentifier(S.local,{name:x})&&b.push(Lt.isIdentifier(S.exported)?S.exported.name:S.exported.value)}return b},d=(h,x)=>{let b=Object.values(h.scope.bindings).filter(E=>u(h,E.identifier.name).includes(x));return b.length===1?b[0]:null},f=h=>{if(!h.path.isImportSpecifier()||h.path.node.importKind==="type")return null;let x=h.path.parentPath,b=l(h.path);if(!b||!x.isImportDeclaration()||x.node.importKind==="type")return null;let E=At(b,x.node.source.value,i),S=E?a(E):null,v=h.path.node.imported,A=S?d(S,Lt.isIdentifier(v)?v.name:v.value):null;return A?.path.isVariableDeclarator()?A:null},m=(h,x=new Set)=>{if(!h.constant||h.constantViolations.length||x.has(h.identifier)||x.size>=32)return null;if(h.path.isImportSpecifier()){let b=f(h);return b?m(b,new Set(x).add(h.identifier)):null}return h.kind==="const"&&h.path.isVariableDeclarator()&&Lt.isIdentifier(h.path.node.id)&&h.path.parentPath.isVariableDeclaration({kind:"const"})?h.path.get("init"):null},g=h=>{let x=o.get(h.identifier);if(x!==void 0)return x;if(r.has(h.identifier))return!0;r.add(h.identifier);let b=h.constant&&h.constantViolations.length===0;for(let A of h.referencePaths){if(!b)break;if(A.isExportNamedDeclaration()||A.parentPath?.isExportSpecifier()&&A.parentPath.node.local===A.node)continue;let I=A;for(;I.parentPath?.isMemberExpression()&&I.parentPath.node.object===I.node;)I=I.parentPath;let _=I.parentPath;if(I===A||_?.isAssignmentExpression()&&_.node.left===I.node||_?.isUpdateExpression()||_?.isUnaryExpression({operator:"delete"})||_?.isForInStatement()||_?.isForOfStatement()){b=!1;break}let k=p(I,new Set);(!k||!(k.isStringLiteral()||k.isTemplateLiteral()&&k.node.expressions.length===0))&&(b=!1)}let E=l(h.path),S=h.path.scope.getProgramParent().path,v=E&&S.isProgram()&&!h.path.isImportSpecifier()?u(S,h.identifier.name):[];if(b&&v.length)for(let[A]of i){if(!b||!/\.[cm]?[jt]sx?$/iu.test(A))continue;let I=a(A);if(!I){b=!1;break}for(let _ of I.get("body"))if(!(!(_.isImportDeclaration()||_.isExportNamedDeclaration()||_.isExportAllDeclaration())||!_.node.source||At(A,_.node.source.value,i)!==E)){if(!_.isImportDeclaration()){b=!1;break}if(_.node.importKind!=="type")for(let k of _.node.specifiers){if(Lt.isImportNamespaceSpecifier(k)){b=!1;break}if(!Lt.isImportSpecifier(k)||k.importKind==="type")continue;let T=Lt.isIdentifier(k.imported)?k.imported.name:k.imported.value;if(!v.includes(T))continue;let L=I.scope.getBinding(k.local.name);if(!L||!g(L)){b=!1;break}}}}return r.delete(h.identifier),o.set(h.identifier,b),b},p=(h,x)=>{if(!h.node||x.has(h.node)||x.size>=32)return null;let b=new Set(x).add(h.node);if(h.isJSXExpressionContainer()||h.isTSAsExpression()||h.isTSTypeAssertion()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()||h.isParenthesizedExpression())return p(h.get("expression"),b);if(h.isIdentifier()){let E=h.scope.getBinding(h.node.name);if(!E||E.path.isVariableDeclarator()&&(E.path.node.start==null||h.node.start==null||E.path.node.start>=h.node.start))return null;let S=m(E),v=S?p(S,b):null;if(v&&(v.isObjectExpression()||v.isArrayExpression())){let A=E.path.isImportSpecifier()?f(E):E;if(!A||!g(A)||!g(E))return null}return v}if(h.isMemberExpression()){let E=c(h.node.property,h.node.computed),S=p(h.get("object"),b);if(E===null||!S)return null;if(S.isArrayExpression()){if(!/^(?:0|[1-9][0-9]*)$/u.test(E)||S.node.elements.some(A=>!A||Lt.isSpreadElement(A)))return null;let v=S.get("elements")[Number(E)];return v?.node?p(v,b):null}if(S.isObjectExpression()){let v=S.get("properties"),A=v.map(_=>_.isObjectProperty()?c(_.node.key,_.node.computed):null);if(A.some(_=>_===null)||new Set(A).size!==A.length)return null;let I=v[A.indexOf(E)];return I?.isObjectProperty()?p(I.get("value"),b):null}return null}return h.isStringLiteral()||h.isTemplateLiteral()&&h.node.expressions.length===0||h.isObjectExpression()||h.isArrayExpression()?h:null};return h=>{let x=p(h,new Set);return x?.isStringLiteral()?{value:x.node.value,complete:!0}:x?.isTemplateLiteral()&&!x.node.expressions.length?{value:x.node.quasis.map(b=>b.value.cooked??b.value.raw).join(""),complete:!0}:{value:null,complete:!1}}}var Gg=mV,gV=typeof Gg=="function"?Gg:Gg.default,hV=new Set(["avif","bmp","gif","jpeg","jpg","mp3","mp4","ogg","png","svg","wav","webm","webp"]),So=new Set(["backgroundimage","fallbacksrc","image","imageurl","media","mediaurl","poster","src","srcset","thumbnail","thumbnailurl"]),Y_=/(?:asset|avatar|gallery|image|media|photo|poster|thumbnail|video)/iu,yV=/^(?:audio|img|image|picture|safeimage|source|video|media|.*(?:audio|image|video))$/iu;function xV(e){let t=Te(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=z_({file_path:e.file_path,ast:t.module.ast,files:e.files}),o=[],i=new Set,s=c=>{if(e.static_only&&!c.complete)return;let u=G_(c.node),d=_V(e.source,u),f=`${u.start_offset}:${u.end_offset}:${c.kind}:${c.value??"<unknown>"}`;i.has(f)||(i.add(f),n.push({file_path:e.file_path,occurrence:n.length,kind:c.kind,source:c.source,value:c.value,expression:d,asset_key:c.assetKey??null,source_range:u,content_digest:CV(d),complete:c.complete}),c.complete||o.push({code:"MEDIA_VALUE_UNKNOWN",file_path:e.file_path,message:"The media expression cannot be resolved without executing user code.",source_range:u}))},a=(c,u)=>{if(!u){s({node:c,kind:"manifest",source:"media-manifest",value:null,complete:!1});return}let d=e.media_manifest?.[u];if(d===void 0){let f=G_(c);o.push({code:"MEDIA_MANIFEST_KEY_UNKNOWN",file_path:e.file_path,message:`The media manifest key ${u} is not available in the supplied snapshot.`,source_range:f})}s({node:c,kind:"manifest",source:"media-manifest",value:d??null,assetKey:u,complete:d!==void 0})};gV(t.module.ast,{ImportDeclaration(c){let u=c.node.source.value;EV(u)&&s({node:c.node.source,kind:"import",source:"import",value:u,complete:!0})},JSXOpeningElement(c){let u=Z_(c.node.name),d=yV.test(u);for(let f of c.get("attributes")){if(f.isJSXSpreadAttribute()){d&&s({node:f.node.argument,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}if(!f.isJSXAttribute())continue;let m=f.node,g=IV(m);if(g==="style"&&!bV(m.value)){s({node:m.value??m,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}if(!g||!SV(g,d))continue;let p=r(f.get("value"));s({node:m.value??m,kind:H_(g),source:"jsx-attribute",value:p.value,complete:p.complete})}},ObjectProperty(c){let u=Ba(c);if(!u.known){s({node:c.node,kind:"object",source:"object-property",value:null,complete:!1});return}let d=u.name;if(!d||!So.has(d)&&!(W_(c)&&Yg(d)))return;let f=c.get("value");if(So.has(d)&&(f.isObjectExpression()||f.isArrayExpression())&&Ku(f))return;let m=r(c.get("value"));s({node:c.node.value,kind:H_(d),source:"object-property",value:m.value,complete:m.complete})},ObjectMethod(c){let u=Ba(c);(!u.known||c.node.kind!=="method"&&u.name&&(So.has(u.name)||W_(c)&&Yg(u.name)))&&s({node:c.node,kind:"object",source:"object-property",value:null,complete:!1})},ArrayExpression(c){if(kV(c))for(let u of c.get("elements")){if(!u.node||(u.isObjectExpression()||u.isArrayExpression())&&Ku(u))continue;let d=r(u);(d.value!==null||!d.complete)&&s({node:u.node,kind:"array-item",source:"array-item",value:d.value,complete:d.complete})}},CallExpression(c){let u=c.node.callee;if(!Ye.isIdentifier(u,{name:"mediaAsset"})||c.node.arguments.length!==1)return;let d=c.node.arguments[0];if(!Ye.isExpression(d)){a(c.node,null);return}let f=es(d);a(c.node,f.complete?f.value:null)},MemberExpression(c){if(!vV(c.node.object))return;let u=c.node.computed?es(c.node.property):Ye.isIdentifier(c.node.property)?{value:c.node.property.name,complete:!0}:{value:null,complete:!1};a(c.node,u.complete?u.value:null)}});let l=RV(o).sort(PV);return{complete:l.length===0,references:n.map((c,u)=>({...c,occurrence:u})),errors:l}}function bV(e){return!Ye.isJSXExpressionContainer(e)||!Ye.isObjectExpression(e.expression)?!1:e.expression.properties.every(t=>{if(!Ye.isObjectProperty(t)||t.computed||!(Ye.isIdentifier(t.key)||Ye.isStringLiteral(t.key)))return!1;let n=Ye.isIdentifier(t.key)?t.key.name:t.key.value;return!n||n==="__proto__"||n.startsWith("--")?!1:Ye.isNumericLiteral(t.value)?Number.isFinite(t.value.value):Ye.isStringLiteral(t.value)&&/^[\w\s#.,%+!-]*$/u.test(t.value.value)})}function EV(e){let n=(e.split(/[?#]/u,1)[0]??"").split(".").pop()?.toLowerCase();return n!==void 0&&hV.has(n)}function SV(e,t){return e!=="src"||t?So.has(e):!1}function H_(e){return e==="srcset"?"srcset":e==="poster"?"poster":e.startsWith("thumbnail")?"thumbnail":e==="src"?"src":"object"}function IV(e){return Ye.isJSXIdentifier(e.name)?e.name.name.toLowerCase():Ye.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`.toLowerCase():null}function Z_(e){return Ye.isJSXIdentifier(e)?e.name:Ye.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:`${Z_(e.object)}.${e.property.name}`}function Ba(e){if(!e.node.computed){let n=e.node.key;return Ye.isIdentifier(n)?{known:!0,name:n.name.toLowerCase()}:Ye.isStringLiteral(n)?{known:!0,name:n.value.toLowerCase()}:{known:!0,name:null}}let t=Vu(e.get("key"));if(t.complete&&t.value!==null)return{known:!0,name:t.value.toLowerCase()};if(Ye.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=[...So,"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 vV(e){return Ye.isIdentifier(e,{name:"mediaAssets"})}function kV(e){let t=e.parentPath;if(t?.isObjectProperty()){let n=Ba(t).name;return n!==null&&So.has(n)}return t?.isVariableDeclarator()&&Ye.isIdentifier(t.node.id)?Y_.test(t.node.id.name):!1}function W_(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=Ba(r).name;if(o&&So.has(o))return!0;t=r.parentPath;continue}return!!(r?.isVariableDeclarator()&&r.node.init===t.node&&Ye.isIdentifier(r.node.id)&&Y_.test(r.node.id.name))}return t!==null}function Yg(e){return e==="src"||e==="srcset"||e==="url"||e==="thumbnail_url"}function Ku(e,t=0){if(t>=32)return!1;if(e.isArrayExpression())return e.get("elements").some(r=>r.node!==null&&(r.isObjectExpression()||r.isArrayExpression()?Ku(r,t+1):!0));let n=!1;for(let r of e.get("properties")){if(!r.isObjectProperty()&&!r.isObjectMethod())return!1;let o=Ba(r);if(!o.known)return!0;let i=o.name;if(r.isObjectMethod()&&r.node.kind==="method")continue;if(i!==null&&(So.has(i)||Yg(i))){n=!0;continue}if(r.isObjectMethod())continue;let s=r.get("value");(s.isObjectExpression()||s.isArrayExpression())&&Ku(s,t+1)&&(n=!0)}return n}function es(e){return e?Ye.isStringLiteral(e)?{value:e.value,complete:!0}:Ye.isJSXExpressionContainer(e)?es(e.expression):Ye.isTemplateLiteral(e)&&e.expressions.length===0?{value:e.quasis.map(t=>t.value.cooked??t.value.raw).join(""),complete:!0}:Ye.isTSAsExpression(e)||Ye.isTSTypeAssertion(e)||Ye.isParenthesizedExpression(e)?es(e.expression):{value:null,complete:!1}:{value:null,complete:!1}}function Vu(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 Vu(e.get("expression"),n);if(e.isIdentifier()){let r=e.scope.getBinding(e.node.name);return!r?.constant||r.kind!=="const"||!r.path.isVariableDeclarator()||!Ye.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}:Vu(r.path.get("init"),n)}return es(e.node)}function G_(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 _V(e,t){return e.slice(t.start_offset,t.end_offset)}function CV(e){return`sha256:${pV("sha256").update(e).digest("hex")}`}function RV(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 PV(e,t){return e.file_path.localeCompare(t.file_path)||(e.source_range?.start_offset??0)-(t.source_range?.start_offset??0)||e.code.localeCompare(t.code)}export{we as FileHistoryStoreError,Ks as PageTemplateManagedSourceError,hu as PreviewFileSystemSiteEditEngineRuntime,Sx as SITE_EDIT_RAW_COLOR_LITERAL_RE,mu as SnapshotSiteEditEngineRuntime,S$ as analyzePortableCollectionInvocation,Wi as analyzePortableInvocation,fg as analyzePortableRelatedEntries,pf as auditGeneratedCode,yu as auditPortableDependencies,Us as buildPageBlockIndex,to as buildPortableInvocation,GU as buildPortableMaterializationPlan,vr as buildPortableSourceClosure,cs as checkComponentI18nHostCompatibility,Vi as classifyPortableDependencyOwnership,Mm as cmsFieldAccessor,Kb as computeManagedPageTemplatePaths,dj as createPreviewSiteEditEngineRuntime,aj as createSiteEditEngineRuntime,$b as decodePageTemplateKey,dg as discoverPortableCollectionSourceRelation,M0 as discoverPortableExistingCollectionRelation,np as encodePageTemplateId,hU as exportPortableBlockFromSnapshot,Ym as extractPortableBlockEntry,Bm as generateCollectionAdapter,CC as instrumentSiteEditRuntimeAttributes,Jb as isManagedPageTemplateSourcePath,pw as normalizePortableBlockMetadata,kU as normalizePortableSource,Uy as openFileHistoryStore,uC as parseSourceModule,eV as planPortableBlockPatch,Of as planPortableRouteCompositionPatch,Ls as planRouteCompositionRewrite,uV as provenRecordThumbnailRanges,mU as readPortableBlockLocalAssetChunk,dC as resolveImportBase,eL as resolveManagedPageTemplateComposition,al as resolvePageBlockBoundary,$m as resolvePageBlockFromSnapshot,vi as resolvePageBlockTarget,Hn as resolvePageCompositionProjection,M$ as resolvePortableBlockSelection,pj as resolvePortableDependencyOwnership,At as resolvePortableSourcePath,dl as scanManagedPageTemplateCandidates,xV as scanPortableMediaReferences,fl as scanSiteEditCompositionsFromFiles,uf as scanSiteEditThemeStyleViolations,E$ as selectPortablePageUnitInvocation};
|