@vcp-dev/site-edit-engine 0.10.10 → 0.10.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
- import{SiteEditOperationRequestSchema as SR,SiteEditPatchPlanSchema as ER}from"@vcp-dev/contracts";function dn(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function Io(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 ko(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,...n.pageCompositionUnitKey?{pageCompositionUnitKey:n.pageCompositionUnitKey}:{},operationSummary:{canUpdateText:n.operationSummary.canUpdateText,canInsertChild:n.operationSummary.canInsertChild,canMove:n.operationSummary.canMove,canRemove:n.operationSummary.canRemove},...n.dynamicDataSummary?{dynamicDataSummary:n.dynamicDataSummary}:{}})),pageComposition:e.pageComposition.status==="unsupported"?{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics}:{status:"supported",containerKey:e.pageComposition.container.key,hasBusinessMembers:e.pageComposition.businessMembers.length>0,placementUnitKeys:e.pageComposition.placementUnits.map(n=>n.key),placements:e.pageComposition.placements.map(n=>({placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,relation:n.relation}))}}}function Co(e){return{composition:e.composition,key:e.key,tag:e.tag,label:e.label,sourceLocator:e.sourceLocator,isOpaque:e.isOpaque,ancestors:e.ancestors,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:lh(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 Ro(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:dn(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 lh(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{computeSiteEditCompositionKey as mC,getSiteEditSourceDeleteProtectionReason as gC,isSiteEditTextSourcePath as hC,parseSiteEditRepeatInstanceKey as yC,SITE_EDIT_SOURCE_DELETE_CAPABILITY as xC,stripSiteEditRepeatInstanceKeys as yt}from"@vcp-dev/contracts";import Hi from"node:path";import{parse as bC}from"yaml";import{createHash as uh}from"node:crypto";var pr=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function be(e){return`sha256:${uh("sha256").update(e).digest("hex")}`}import*as Kl from"@babel/parser";function fn(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function $(e,t,n,r,o){return{ok:!1,source:e,diagnostic:fn(t,n,r,o)}}function ys(e,t,n,r,o){return{ok:!1,source:e,diagnostic:fn(t,n,r,o)}}var dh={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Rt(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Kl.parse(t,{sourceType:"module",plugins:dh[n]})}}catch(r){return{ok:!1,source:t,diagnostic:fn("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function xs(e,t){return Rt({source:e,profile:Jl(t.kind)})}function mr(e,t){return Rt({source:e,profile:Jl(t)})}function Jl(e){return"next-app-entry"}function pn(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"}import bs from"@babel/traverse";import*as wt from"@babel/types";function Oe(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(wt.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(wt.isIdentifier(s)&&s.name==="Fragment"||wt.isStringLiteral(s)&&s.value==="Fragment")&&Xl(i.parentPath)}if(!wt.isJSXMemberExpression(t)||!wt.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!wt.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())&&Xl(r.parentPath)}function Xl(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var Wt=typeof bs=="function"?bs:bs.default,wo=new WeakMap,zl=new WeakMap;function Nt(e,t){let n=xs(e,t);if(!n.ok)return ys(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=ie(n.ast,t);return r.ok?{ok:!0,match:{locatorKind:r.match.locatorKind,node:r.match.node,start:r.match.start,end:r.match.end}}:ys(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ie(e,t){return t.kind==="jsx-node"?Yl(e,t):t.kind==="jsx-attribute"?yh(e,t):t.kind==="value"?xh(e,t):t.kind==="expression"?bh(e,t):t.kind==="directive"?Sh(e,t):t.kind==="export"?Eh(e,t):{ok:!1,diagnostic:fn("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Yl(e,t){return t.strategy==="source-range"?fh(e,t):ph(e,t)}function fh(e,t){let n=null;if(Wt(e,{JSXElement(o){if(!mn(o.node,t.sourceRange))return;let i=_e("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!mn(o.node,t.sourceRange))return;let i=_e("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!mn(o.node,t.sourceRange))return;let i=_e("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!mn(o.node,t.sourceRange))return;let i=_e("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Me("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!_h(r.path,t.expectedIdentity)?Me("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function ph(e,t){if(t.structuralPath===""){let r=gh(e,t.component);if(r){let o=hh(r);if(o)return o}}let n=null;return Wt(e,{JSXElement(r){if(hr(r)!==t.component||Es(r)!==t.structuralPath)return;let i=_e("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(hr(r)!==t.component||Es(r)!==t.structuralPath)return;let i=_e("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=mh(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Me("jsx-node","locator-miss","JSX node not found for structural-path locator")}function mh(e,t,n){let r=null;return Wt(e,{JSXElement(o){if(hr(o)!==t||!mn(o.node,n))return;let i=_e("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(hr(o)!==t||!mn(o.node,n))return;let i=_e("jsx-node",o);i&&(r=i,o.stop())}}),r}function gh(e,t){let n=null;return Wt(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 hh(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 Me("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Me("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 Me("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function yh(e,t){let n=Yl(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Oh(c,t.name));if(!s||!s.isJSXAttribute())return Me("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=_e("jsx-attribute",s);return a?{ok:!0,match:a}:Me("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function xh(e,t){let n=vh(e,t);if(!n.ok)return n;let r=Ih(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Ut(r.match.path.node.loc,t.expectedRange)?Me("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function bh(e,t){let n=null;return Wt(e,{Identifier(r){if(!Ph(r))return;let o=Wl(r);if(!o||!Gl(o,t))return;let i=_e("expression",r);i&&(t.expectedRange&&!Ut(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Wl(r);if(!o||!Gl(o,t))return;let i=_e("expression",r);i&&(t.expectedRange&&!Ut(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Me("expression","locator-miss","Expression not found")}function Sh(e,t){let n=null;return Wt(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Ut(i.node.loc,t.expectedRange))return;let s=_e("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Me("directive","locator-miss",`Directive '${t.value}' not found`)}function Eh(e,t){let n=null;return Wt(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let m=_e("export",c);if(!m||t.expectedRange&&!Ut(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=vs(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let f=_e("export",u);if(!f||t.expectedRange&&!Ut(u.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=vs(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Ut(s.node.loc,t.expectedRange))return;let a=_e("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=_e("export",o);i&&(t.expectedRange&&!Ut(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Me("export","export-not-found",`Export '${Fh(t)}' not found`)}function vh(e,t){let n=null;return Wt(e,{Expression(r){if(n||t.root.kind!=="expression"||!mn(r.node,t.root.sourceRange))return;let o=_e("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 d=r.get("init");if(!d.node)return;let g=_e("value",d);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(d=>d?.type==="Identifier"&&d.name===o.name)!==0)return;let c=s.node.callee;if((c.type==="Identifier"?c.name:c.type==="MemberExpression"&&c.property.type==="Identifier"?c.property.name:null)!==o.hook)return;let u=o.hook==="useReducer"?1:0,f=r.get(`init.arguments.${u}`);if(!f||Array.isArray(f)||!f.node)return;let m=_e("value",f);m&&(n=m,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=vs(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=_e("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=_e("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:Me("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 Ih(e,t){let n=Ss(e);for(let o of t){if(n=Ss(n),o.kind==="property"){if(!n.isObjectExpression())return Me("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return Me("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>Mh(l,o.name));if(!c||!c.isObjectProperty())return Me("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return Me("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return Me("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return Me("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=Ss(n);let r=_e("value",n);return r?{ok:!0,match:r}:Me("value","locator-miss","Resolved value has no source range")}function Ss(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function _e(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 mn(e,t){return Ut(e.loc,t)}function Ut(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 Es(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Oe(n)){let o=Zl(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Hl(n,o)}`):t.unshift(`${o}#${Hl(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||wh(n.parentPath)&&!Nh(n.parentPath))break;n=n.parentPath}return t.join("/")}function Hl(e,t){let n=kh(e);if(!n)return 0;let r=wo.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=wo.get(n.node)?.get(t);if(!i){let s=wo.get(n.node);s||(s=new Map,wo.set(n.node,s)),i=new WeakMap,s.set(t,i)}for(let s of gr(n))if(Zl(s.node.openingElement)===t){if(i.set(s.node,o),s.node===e.node)return o;o++}return i.get(e.node)??0}function kh(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Oe(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function gr(e){let t=zl.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(Oe(o)){n.push(...gr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...gr(o));continue}o.isJSXExpressionContainer()&&n.push(...Vt(o.get("expression")))}return zl.set(e.node,n),n}function Vt(e){if(e.isJSXElement())return Oe(e)?gr(e):[e];if(e.isJSXFragment())return gr(e);if(e.isParenthesizedExpression())return Vt(e.get("expression"));if(e.isLogicalExpression()&&Ch(e.node.operator))return Vt(e.get("right"));if(e.isCallExpression()||e.isOptionalCallExpression()){let t=e.get("callee"),n=!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())?t.get("property"):null;if(!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())&&!t.node.computed&&n!==null&&!Array.isArray(n)&&n.isIdentifier()&&n.node.name==="map"){let r=e.get("arguments").find(o=>!Array.isArray(o)&&(o.isArrowFunctionExpression()||o.isFunctionExpression()));if(r&&!Array.isArray(r)){let o=r.get("body");if(!Array.isArray(o)){if(o.isBlockStatement()){let i=[];for(let s of o.get("body")){if(s.isVariableDeclaration())for(let a of s.get("declarations")){let c=a.get("init");(c.isJSXElement()||c.isJSXFragment())&&i.push(...Vt(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Vt(a));break}}return i}else if(o.node&&o.isExpression())return Vt(o)}}}}return e.isConditionalExpression()?[...Vt(e.get("consequent")),...Vt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Vt(t)):[]}function Ch(e){return e==="&&"||e==="||"||e==="??"}function Zl(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Rh(e.name):null}function Rh(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 hr(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 wh(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Nh(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 Ph(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Wl(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 Gl(e,t){return e.base===t.base&&Ah(e.path,t.path??[])}function Ah(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 Th(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Fh(e){return e.exportKind==="named"?e.name:e.exportKind}function Me(e,t,n,r){return{ok:!1,diagnostic:fn(t,n,e,r)}}function _h(e,t){return hr(e)!==t.component?!1:Es(e)===t.structuralPath}function Oh(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function vs(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Mh(e,t){return e.isObjectProperty()?Th(e.node)===t:!1}import*as ql from"@babel/parser";import{arrayExpression as $h,booleanLiteral as Vh,identifier as Uh,jsxAttribute as Kh,jsxExpressionContainer as Jh,jsxIdentifier as Xh,nullLiteral as zh,numericLiteral as Hh,objectExpression as Wh,objectProperty as Gh,stringLiteral as ks}from"@babel/types";import Is from"@babel/generator";var Dh=typeof Is=="function"?Is:Is.default;function Lh(e){let t=e.split(`
2
- `),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let c=a[1];c.includes(" ")?r=!0:c.length>0&&n.push(c.length)}}if(r&&t.every(a=>{let c=a.match(/^(\s+)/);return!c||c[1].includes(" ")}))return"tab";if(n.length===0)return"2";function o(s,a){return a===0?s:o(a,s%a)}let i=n[0];for(let s=1;s<n.length;s++)i=o(i,n[s]);return i>=4?"4":"2"}function Bh(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 jh(e,t){return e.split(`
3
- `).map(r=>Bh(r,t)).join(`
4
- `)}function No(e){let{ast:t,source:n}=e;try{let r=Lh(n),i=Dh(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=jh(i,r)),{ok:!0,source:i}}catch(r){return $(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function Ql(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 yr(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Ql(e),afterSourceHash:Ql(t),inverse:n.inverse}}}function fe(e,t,n){let r=No({ast:e,source:t});return r.ok?yr(t,r.source,n):r}function ke(e,t){let n=mr(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Po(e,t){return No({ast:e,source:t})}function Yh(e,t,n){let r=ie(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Ao(e,t,n){let r=Yh(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:$(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function Gt(e){return typeof e=="string"?ks(e):typeof e=="number"?Hh(e):typeof e=="boolean"?Vh(e):e===null?zh():Array.isArray(e)?$h(e.map(t=>Gt(t))):Wh(Object.entries(e).map(([t,n])=>{let r=Gh(Cs(t),Gt(n));return t==="__proto__"&&(r.computed=!0),r}))}function Zh(e){return typeof e=="string"?ks(e):Jh(Gt(e))}function xr(e,t){return Kh(Xh(e),Zh(t))}function To(e,t){try{let r=ql.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:$(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:$(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Cs(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?Uh(e):ks(e)}function Fo(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=ke(t,"jsx-node");if(!i.ok)return i.result;let s=ie(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=Qh(s.match.path)[r];if(!c)return $(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=qh(c.path.node.value,o);break;case"string-literal":c.path.node.value=o;break;case"template-literal":{let l=c.quasiIndex;c.path.node.quasis[l].value.raw=o,c.path.node.quasis[l].value.cooked=o;break}}return fe(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function Qh(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=ey(r.get("expression"));o.length>0&&t.push(...o)}}return t}function qh(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function ey(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&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as Rs}from"@babel/types";function Ln(e){let{source:t,locator:n}=e,r=ke(t,"jsx-node");if(!r.ok)return r.result;let o=ie(r.ast,n);return o.ok?(ty(o.match.path),fe(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function ty(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Rs());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Rs());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Rs());return}e.remove()}import{cloneNode as ny}from"@babel/types";function _o(e){let t=ke(e.source,"jsx-node");if(!t.ok)return t.result;let n=ie(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=To(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(ny(r.node,!0)),fe(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as py}from"@babel/types";import ws from"@babel/traverse";import*as Z from"@babel/types";function br(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 ry=typeof ws=="function"?ws:ws.default;function ft(e,t,n,r){if(!e.ok)return e;let o=dt(n,t);if(!o)return e;let i=oy(t,o,r);return i?{...e,selectionRef:i}:e}function oy(e,t,n){let r=iy(e,t);if(!r)return;let o=n.sourceLocator?eu(n.sourceLocator):void 0,i=n.targetParentLocator?eu(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??ay(r)??i?.component??o?.component;if(!(!s||!a))return{key:br(s,a,cy(r))}}function eu(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function iy(e,t){let n=su(e,t);return!n||n.node.type!=="JSXElement"?null:n}function su(e,t){let n=null;return ry(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function dt(e,t){if(!e)return null;if(Z.isJSXElement(e))return fy(t,e)?tu(e.children,t):e;if(Z.isJSXFragment(e))return tu(e.children,t);if(Z.isJSXExpressionContainer(e)||Z.isParenthesizedExpression(e)||Z.isTSAsExpression(e)||Z.isTSSatisfiesExpression(e)||Z.isTSTypeAssertion(e)||Z.isTSNonNullExpression(e))return dt(e.expression,t);if(Z.isLogicalExpression(e))return dt(e.right,t);if(Z.isConditionalExpression(e))return dt(e.consequent,t)??dt(e.alternate,t);if(Z.isCallExpression(e)||Z.isOptionalCallExpression(e))return au(e)?sy(e.arguments[0],t):null;if(Z.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=dt(n,t);if(r)return r}return null}function tu(e,t){for(let n of e){let r=dt(n,t);if(r)return r}return null}function sy(e,t){return!e||!Z.isArrowFunctionExpression(e)&&!Z.isFunctionExpression(e)?null:Z.isBlockStatement(e.body)?Sr(e.body.body,t):dt(e.body,t)}function Sr(e,t){for(let n of e){if(Z.isReturnStatement(n)){let r=dt(n.argument,t);if(r)return r;continue}if(Z.isBlockStatement(n)){let r=Sr(n.body,t);if(r)return r;continue}if(Z.isIfStatement(n)){let r=nu(n.consequent,t);if(r)return r;let o=n.alternate?nu(n.alternate,t):null;if(o)return o;continue}if(Z.isSwitchStatement(n))for(let r of n.cases){let o=Sr(r.consequent,t);if(o)return o}}return null}function nu(e,t){return Z.isBlockStatement(e)?Sr(e.body,t):Sr([e],t)}function ay(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(Z.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&Z.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 ru=new WeakMap,ou=new WeakMap,Ns=new WeakMap;function cy(e){let t=ru.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=ly(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return ru.set(e.node,o),o}function ly(e){let t=cu(e.node.openingElement.name);return!t||Oe(e)?null:/^[A-Z]/.test(t)?`component:${t}#${iu(e,t)}`:`${t}#${iu(e,t)}`}function iu(e,t){let n=uy(e);if(!n)return 0;let r=Ns.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Ns.get(n.node);o||(o=new Map,Ns.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of gn(n))if(cu(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 uy(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Oe(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function gn(e){let t=ou.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(Oe(o)){n.push(...gn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...gn(o));continue}o.isJSXExpressionContainer()&&n.push(...Pt(o.get("expression")))}return ou.set(e.node,n),n}function Pt(e){if(e.isJSXElement())return Oe(e)?gn(e):[e];if(e.isJSXFragment())return gn(e);if(e.isParenthesizedExpression())return Pt(e.get("expression"));if(e.isLogicalExpression())return Pt(e.get("right"));if(e.isConditionalExpression())return[...Pt(e.get("consequent")),...Pt(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Pt(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&au(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?dy(n):[]}return[]}function dy(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Oe(t)?gn(t):[t];if(t.isJSXFragment())return gn(t);if(t.isParenthesizedExpression())return Pt(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Pt(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(...Pt(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...Pt(o)),n}return n}function au(e){let t=e.callee;return(Z.isMemberExpression(t)||Z.isOptionalMemberExpression(t))&&Z.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function fy(e,t){let n=su(e,t);return n?Oe(n):!1}function cu(e){return Z.isJSXIdentifier(e)?e.name:Z.isJSXMemberExpression(e)?lu(e):Z.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function lu(e){return`${Z.isJSXIdentifier(e.object)?e.object.name:lu(e.object)}.${e.property.name}`}function Yt(e,t){if(t.parentPath===e&&t.listKey==="children"&&Ps(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!Ps(n))return null;let r=n;for(;r&&r!==e;){if(!Ps(r)||!Oe(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function Ps(e){return e.isJSXElement()||e.isJSXFragment()}function Bn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ke(t,"jsx-node");if(!a.ok)return a.result;let c=ie(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return $(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let l=c.match.path;if(c.match.path.isJSXElement()){let C=c.match.path.node;if(!C.closingElement||C.openingElement.selfClosing)return $(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=To(t,r.jsx);if(!u.ok)return u.result;let f=py(u.node,!0),m=l.node.children,d={...s,targetParentLocator:n},g=C=>s?ft(C,a.ast,f,d):C;if(o==="append")return m.push(f),g(fe(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(f),g(fe(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=ie(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let E=Yt(c.match.path,h.match.path);if(!E)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=E;let S=l.node.children,v=S.findIndex(C=>C===h.match.path.node);return v===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(S.splice(o==="before"?v:v+1,0,f),g(fe(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as uu from"@babel/parser";import{cloneNode as my}from"@babel/types";function Oo(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ke(t,"jsx-node");if(!a.ok)return a.result;let c=gy(t,r);if(!c.ok)return c.result;let l=ie(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return $(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let S=l.match.path.node;if(!S.closingElement||S.openingElement.selfClosing)return $(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,f=null;if(i){let S=ie(a.ast,i);if(!S.ok)return{ok:!1,source:t,diagnostic:S.diagnostic};let v=Yt(l.match.path,S.match.path);if(!v)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=v,f=S.match.path.node}else if(o==="before"||o==="after")return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=my(c.node,!0),d=u.node.children,g={...s,targetParentLocator:n},h=S=>s?ft(S,a.ast,m,g):S;if(o==="append")return d.push(m),h(fe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return d.unshift(m),h(fe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let E=d.findIndex(S=>S===f);return E===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(d.splice(o==="before"?E:E+1,0,m),h(fe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function gy(e,t){try{let r=uu.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:$(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:$(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as hy,nullLiteral as As}from"@babel/types";import*as Zt from"@babel/types";function jn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ke(t,"jsx-node");if(!a.ok)return a.result;let c=ie(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=ie(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return $(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let u=l.match.path;if(l.match.path.isJSXElement()){let v=l.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return $(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let f=null;if(i){let v=ie(a.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let C=Yt(l.match.path,v.match.path);if(!C)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=C,f=v.match.path}else if(o==="before"||o==="after")return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=f&&typeof f.key=="number"?f.key:-1;if(f&&m===-1)return $(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let d=hy(c.match.path.node,!0);if(!Zt.isJSXElement(d)&&!Zt.isJSXExpressionContainer(d)&&!Zt.isJSXFragment(d)&&!Zt.isJSXText(d))return $(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let g=c.match.path.parentPath?.node===u.node&&typeof c.match.path.key=="number"?c.match.path.key:-1;if(f&&c.match.path.parentPath?.node===f.parentPath?.node&&c.match.path.key===f.key)return $(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");yy(c.match.path);let h=u.node.children,E={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return h.push(d),ft(Po(a.ast,t),a.ast,d,E);if(o==="prepend")return h.unshift(d),ft(Po(a.ast,t),a.ast,d,E);let S=m-(g!==-1&&g<m?1:0);return h.splice(o==="before"?S:S+1,0,d),ft(Po(a.ast,t),a.ast,d,E)}function yy(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(As());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(As());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(As());return}e.remove()}import*as du from"@babel/parser";import{cloneNode as xy,nullLiteral as Ts}from"@babel/types";function Mo(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=ke(t,"jsx-node");if(!c.ok)return c.result;let l=by(t,s);if(!l.ok)return l.result;let u=ie(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let f=ie(c.ast,r);if(!f.ok)return{ok:!1,source:t,diagnostic:f.diagnostic};if(!f.match.path.isJSXElement()&&!f.match.path.isJSXFragment())return $(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(f.match.path.isJSXElement()){let C=f.match.path.node;if(!C.closingElement||C.openingElement.selfClosing)return $(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=f.match.path,d=null;if(i){let C=ie(c.ast,i);if(!C.ok)return{ok:!1,source:t,diagnostic:C.diagnostic};let w=Yt(f.match.path,C.match.path);if(!w)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=w,d=C.match.path.node}else if(o==="before"||o==="after")return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return $(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=m.node,h=xy(l.node,!0);Sy(u.match.path);let E={...a,sourceLocator:n,targetParentLocator:r},S=g.children;if(o==="append")return S.push(h),ft(fe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,E);if(o==="prepend")return S.unshift(h),ft(fe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,E);let v=S.findIndex(C=>C===d);return v===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(S.splice(o==="before"?v:v+1,0,h),ft(fe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,E))}function by(e,t){try{let r=du.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:$(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:$(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Sy(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ts());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ts());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ts());return}e.remove()}import{SiteEditSetPropsParamsSchema as Ey,classifySiteEditPropertyName as vy}from"@vcp-dev/contracts";import*as $n from"@babel/types";function Do(e){let t=Ey.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return $(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=ke(e.source,"jsx-node");if(!n.ok)return n.result;let r=Ao(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=vy(a.name);if(c.owner!=="generic")return $(e.source,"unsupported-syntax",c.diagnostic?.message??`Property '${a.name}' is not owned by the generic JSX primitive`,"jsx-node")}let o=r.match.path.node.openingElement,i=o.attributes.filter($n.isJSXAttribute),s=new Map;for(let a of i){let c=Iy(a);if(!c)continue;let l=s.get(c)??[];l.push(a),s.set(c,l)}for(let a of t.data.changes)if((s.get(a.name)??[]).length>1)return $(e.source,"unsupported-syntax",`JSX attribute '${a.name}' has multiple sources`,"jsx-node");for(let a of t.data.changes){let c=s.get(a.name)?.[0];if(a.operation==="remove"){c&&(o.attributes=o.attributes.filter(u=>u!==c));continue}let l=xr(a.name,a.value).value;c?c.value=l:o.attributes.push(xr(a.name,a.value))}return fe(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function Iy(e){return $n.isJSXIdentifier(e.name)?e.name.name:$n.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import*as je from"@babel/types";import{classifySiteEditPropertyName as fu}from"@vcp-dev/contracts";function Lo(e){let t=fu(e.name),n=fu(e.property);if(t.owner!=="generic"||n.owner!=="generic")return $(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!pu(e.object))return $(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return $(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=ke(e.source,"jsx-node");if(!r.ok)return r.result;let o=Ao(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>je.isJSXAttribute(l)&&Cy(l)===e.name);if(s.length>1)return $(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=ky(e.object,e.property),c=s[0];if(c)c.value=je.jsxExpressionContainer(a);else{let l=xr(e.name,"");l.value=je.jsxExpressionContainer(a),i.attributes.push(l)}return fe(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function ky(e,t){return pu(t)?je.memberExpression(je.identifier(e),je.identifier(t)):je.memberExpression(je.identifier(e),je.stringLiteral(t),!0)}function pu(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function Cy(e){return je.isJSXIdentifier(e.name)?e.name.name:je.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as wy,identifier as Er,importDeclaration as Ny,importDefaultSpecifier as Py,importNamespaceSpecifier as Ay,importSpecifier as Ty,isImportDefaultSpecifier as mu,isImportNamespaceSpecifier as gu,isImportSpecifier as hu,stringLiteral as Fy}from"@babel/types";function Vn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(E=>!Vy(E));if(o!==-1){let E=r[o],S=E&&typeof E=="object"&&"kind"in E?E.kind:void 0;return $(t,"unsupported-syntax",`Unsupported import spec kind: ${String(S)}`)}let i=By(r);if(!i.ok)return $(t,"unsupported-syntax",i.message);let s=ke(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(E=>E.type==="ImportDeclaration"&&E.source.value===n),u=new Set(l.flatMap(E=>E.specifiers.flatMap(S=>{let v=Uy(E,S);return v?[v]:[]}))),f=i.imports.filter(E=>!u.has(vu(E)));if(f.length===0)return yr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=jy(c.body),d=f.find(E=>m.has(Fs(E)));if(d)return $(t,"unsupported-syntax",`Import local binding already exists: ${Fs(d)}`);let g=Ly(f);if(g.reduce((E,S)=>E+S.length,0)!==f.length)return $(t,"unsupported-syntax","Unsupported import specifier grouping");for(let E of g){if(!Su(xu(E)))return $(t,"unsupported-syntax","Unsupported import specifier combination");let S=l.find(v=>_y(v,E));if(S)Oy(S,E);else{let v=Ny(yu(E),Fy(n));$y(c.body,v),l.push(v)}}return fe(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function _y(e,t){return e.importKind==="type"?!1:Su(Dy(My(e),xu(t)))}function Oy(e,t){let n=!1,r=new Set(e.specifiers.map(o=>_s(o)));for(let o of yu(t)){let i=_s(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return Eu(e.specifiers),{changed:n}}function yu(e){let t=e.map(n=>{switch(n.kind){case"named":return Ty(n.local?Er(n.local):Er(n.imported),Er(n.imported));case"default":return Py(Er(n.local));case"namespace":return Ay(Er(n.local));default:return n}});return Eu(t),t}function xu(e){let t=bu();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 My(e){let t=bu();for(let n of e.specifiers)mu(n)?t.defaultLocals.add(n.local.name):gu(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function bu(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function Dy(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Su(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function Eu(e){let t=[...e.filter(n=>mu(n)),...e.filter(n=>gu(n)),...e.filter(n=>hu(n))];e.splice(0,e.length,...t)}function Ly(e){let t=e.filter(i=>i.kind==="default"),n=e.filter(i=>i.kind==="namespace"),r=e.filter(i=>i.kind==="named"),o=[];if(n.length>0){let i=Math.max(t.length,n.length);for(let s=0;s<i;s+=1){let a=[],c=t[s],l=n[s];c&&a.push(c),l&&a.push(l),o.push(a)}return r.length>0&&o.push(r),o}if(t.length>0){o.push([t[0],...r]);for(let i of t.slice(1))o.push([i])}else r.length>0&&o.push(r);return o}function By(e){let t=new Map,n=new Map;for(let r of e){let o=vu(r);if(t.has(o))continue;let i=Fs(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 jy(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(wy(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 $y(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 Vy(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 vu(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 Fs(e){return e.kind==="named"?e.local??e.imported:e.local}function Uy(e,t){return e.importKind==="type"||hu(t)&&t.importKind==="type"?null:_s(t)}function _s(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 Un(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!Jy(u));if(o!==-1){let u=r[o],f=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return $(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(f)}`)}let i=ke(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(c===-1)return yr(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),fe(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(f=>Ky(u,f))),l.specifiers.length===0&&a.body.splice(c,1),fe(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function Ky(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 Jy(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 vr(e){let{source:t,locator:n,next:r}=e,o=Vo(t,n);return o.ok?(o.path.replaceWith(Gt(r)),fe(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Bo(e){let{source:t,locator:n,index:r,value:o}=e,i=Vo(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?$(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?$(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,Gt(o)),fe(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):$(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function jo(e){let{source:t,locator:n,index:r}=e,o=Vo(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?$(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?$(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),fe(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):$(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function $o(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=Vo(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return $(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return $(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 $(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),fe(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function Vo(e,t){let n=ke(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=ie(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as Ve from"@babel/types";function Uo(e){let t=ke(e.source,"value");if(!t.ok)return t.result;let n=ie(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return $(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Ve.isSpreadElement(a)||Ve.isObjectProperty(a)&&a.computed))return $(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Ve.isObjectProperty(a)&&Xy(a.key)===e.name);if(o.length>1)return $(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Ve.unaryExpression("void",Ve.numericLiteral(0)):Gt(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Ve.objectProperty(Cs(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return fe(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function Xy(e){return Ve.isIdentifier(e)?e.name:Ve.isStringLiteral(e)?e.value:Ve.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as zy,isSiteEditRuntimeVoidElementTag as Hy}from"@vcp-dev/contracts/site-edit-runtime-capability";function Kn(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function Wy(e,t,n){let r=Kn(n),o=t.nodes.get(e),i=n.elements.get(e);if(!o||!i)return{composition:r,key:e,canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1,constraints:[{kind:"opaque-region",message:"Node not found in graph"}]};let s=o.constraints.map(w=>({kind:w.kind,message:w.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),f=i.tag!==u,m=!f&&Hy(u),d=f||zy(u),g=f&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(w=>w.editable);m&&!s.some(w=>w.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!m&&!d&&!s.some(w=>w.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let E=h&&(!a||i.importedFrom==="next/link"),S=!i.isPublicUiComponent&&!m&&d&&(!a||g);return{composition:r,key:e,canUpdateText:E,canInsertChild:S,canMove:!l,canRemove:!l,constraints:s}}function Iu(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,Wy(r,e,t));return n}function Os(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:be(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Gy(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:be(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(c=>c.type==="JSXAttribute"&&c.name.type==="JSXIdentifier"&&c.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:Cu(r),version:{documentVersion:e.route.graph.version,contentHash:be(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:ku(e.route.source,o),valueRaw:s?ku(e.route.source,s):null,attrRange:Cu(o),diagnostics:[]}}function Ru(e){let{source:t,oldAttrRange:n,openingElementRange:r,newAttrRaw:o}=e;if(n){let a=n.start>0&&/\s/.test(t[n.start-1]??"")?n.start-1:n.start,c=o?`${a<n.start?" ":""}${o}`:"";return t.slice(0,a)+c+t.slice(n.end)}if(!o)return t;let i=r.end,s=t.slice(Math.max(0,i-2),i)==="/>"?i-2:i-1;return t.slice(0,s)+` ${o}`+t.slice(s)}function Gy(e,t){let n=Rt({source:e,profile:pn({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=ie(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Yy(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function wu(e){let t=Rt({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 ku(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Cu(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 Yy(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Nu(){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 Zy}from"node:crypto";import Ko from"node:fs/promises";import Ms from"node:path";import{setTimeout as Qy}from"node:timers/promises";var qy={async mkdir(e,t){await Ko.mkdir(e,t)},async writeFile(e,t,n){await Ko.writeFile(e,t,n)},async rename(e,t){await Ko.rename(e,t)},async rm(e,t){await Ko.rm(e,t)}},ex=new Set(["EACCES","EBUSY","EPERM"]),tx=[10,20,40,80,160];async function nx(e,t,n){for(let r of tx)try{await e.rename(t,n);return}catch(o){if(!rx(o))throw o;await Qy(r)}await e.rename(t,n)}function rx(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&ex.has(e.code)}async function Jo(e,t,n=qy){let r=Ms.dirname(e),o=Ms.basename(e),i=Ms.join(r,`.${o}.${process.pid}.${Zy()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await nx(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import js from"@babel/traverse";import*as b from"@babel/types";import*as ce from"@babel/types";function At(e,t={}){if(ce.isTSAsExpression(e)||ce.isTSSatisfiesExpression(e)||ce.isTSNonNullExpression(e)||ce.isTypeCastExpression(e)||ce.isParenthesizedExpression(e))return At(e.expression,t);if(ce.isStringLiteral(e))return{status:"resolved",value:e.value};if(ce.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(ce.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(ce.isNullLiteral(e))return{status:"resolved",value:null};if(ce.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(ce.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(ce.isUnaryExpression(e)&&e.operator==="void"&&ce.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(ce.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||ce.isSpreadElement(r))return{status:"unresolved"};let o=At(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(ce.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!ce.isObjectProperty(r)||r.computed||!ce.isExpression(r.value))return{status:"unresolved"};let o=ox(r.key);if(o===null)return{status:"unresolved"};let i=At(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 ce.isMemberExpression(e)||ce.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function ox(e){return ce.isIdentifier(e)?e.name:ce.isStringLiteral(e)?e.value:ce.isNumericLiteral(e)?String(e.value):null}import{createHash as ux}from"node:crypto";import*as ix from"@babel/parser";import*as Jn from"@babel/types";import*as Qt from"node:path";var Ds=[".tsx",".ts",".jsx",".js"],sx=Ds.map(e=>`/index${e}`),ax=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 Pu(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&ax.has(n[1].toLowerCase())}function Au(e){let t=[];for(let n of e.program.body)Jn.isImportDeclaration(n)&&typeof n.source.value=="string"&&Tt(n.source.value)&&t.push(n.source.value),Jn.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&Tt(n.source.value)&&t.push(n.source.value),Jn.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&Tt(n.source.value)&&t.push(n.source.value);return Ls(e.program,t),t}function Ls(e,t){if(!e||typeof e!="object")return;let n=e;if(n.type==="CallExpression"&&n.callee?.type==="Import"){let r=n.arguments?.[0];r?.type==="StringLiteral"&&typeof r.value=="string"&&Tt(r.value)&&t.push(r.value)}for(let r of Object.values(n))if(Array.isArray(r))for(let o of r)Ls(o,t);else r&&typeof r=="object"&&Ls(r,t)}function Tt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Ir(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=Qt.dirname(e);return Qt.join(n,t).replace(/\\/g,"/")}async function cx(e,t){if(Ds.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Ds){let r=`${e}${n}`;if(await t(r))return r}for(let n of sx){let r=`${e}${n}`;if(await t(r))return r}return null}async function hn(e,t,n){let r=await Xo(e,t,n);return r.ok?r.path:null}async function Xo(e,t,n){let r=Ir(e,t);try{if(!lx(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 cx(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 lx(e,t,n){if(!Tt(t)||t.includes("\0")||t.includes("\\")||Qt.posix.isAbsolute(n))return!1;let r=Qt.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!Qt.posix.isAbsolute(e)}var kr=(e,t)=>{let n=Rt({source:t,profile:pn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${ux("sha256").update(t).digest("hex")}`,ast:n.ast,imports:Au(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};var zo="components/ui";function yn(e){if(!e)return!1;let t=Bs(e);return t===zo||t.startsWith(`${zo}/`)||t.includes(`/${zo}/`)||t.endsWith(`/${zo}`)}function Cr(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?yn(e.slice(2)):e.startsWith("./")||e.startsWith("../")?yn(Bs(`${dx(t)}/${e}`)):yn(e):!1}function Bs(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 dx(e){let t=Bs(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var fx=typeof js=="function"?js:js.default;function Xe(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 px(e){return/^[A-Z]/.test(e)}function Js(e){let t=e.openingElement;return b.isJSXIdentifier(t.name)?t.name.name==="Fragment":b.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function zn(e){return b.isJSXFragment(e)}function Fu(e){return b.isJSXIdentifier(e.name)?e.name.name:b.isJSXMemberExpression(e.name)?_u(e.name):b.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function _u(e){return b.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:b.isJSXMemberExpression(e.object)?`${_u(e.object)}.${e.property.name}`:e.property.name}function mx(e){return e.split(".")[0]??e}function gx(e){let t=e;for(;t;){let n=t.node;if(b.isFunctionDeclaration(n)&&n.id||b.isVariableDeclarator(n)&&b.isIdentifier(n.id))return n.id.name;if(b.isExportDefaultDeclaration(n)){let r=n.declaration;if(b.isFunctionDeclaration(r)&&r.id)return r.id.name;if(b.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function hx(){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 yx(e){let t=new Map;for(let n of e.program.body){if(!b.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(b.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(b.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(b.isImportSpecifier(o)){let i=b.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Kt(e,t=[]){if(b.isIdentifier(e))return t.push(e.name),t;if(b.isObjectPattern(e)){for(let n of e.properties)b.isObjectProperty(n)?Kt(n.value,t):b.isRestElement(n)&&Kt(n.argument,t);return t}if(b.isArrayPattern(e)){for(let n of e.elements)n&&(b.isRestElement(n)?Kt(n.argument,t):Kt(n,t));return t}return b.isAssignmentPattern(e)?(Kt(e.left,t),t):(b.isRestElement(e)&&Kt(e.argument,t),t)}function bt(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Rr(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 xx(e,t,n){e.set(t,{resolved:!0,value:n})}function Xs(e,t){e.set(t,{resolved:!1})}function Ou(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 Le(e,t,n){if(b.isTSAsExpression(e)||b.isTSSatisfiesExpression(e)||b.isTSNonNullExpression(e)||b.isTypeCastExpression(e)||b.isParenthesizedExpression(e))return Le(e.expression,t,n);if(b.isLogicalExpression(e))return Ho([Le(e.left,t,n),Le(e.right,t,n)]);if(b.isBinaryExpression(e))return Ho([b.isExpression(e.left)?Le(e.left,t,n):null,b.isExpression(e.right)?Le(e.right,t,n):null]);if(b.isConditionalExpression(e))return Ho([Le(e.consequent,t,n),Le(e.alternate,t,n)]);if(b.isTemplateLiteral(e))return Ho(e.expressions.filter(b.isExpression).map(i=>Le(i,t,n)));if(b.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!b.isMemberExpression(e)&&!b.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;b.isMemberExpression(o)||b.isOptionalMemberExpression(o);){if(o.computed)if(b.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(b.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&b.isExpression(o.property)){let i=qt(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(!b.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return b.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:bt(e,t),base:o.name,path:r}:null}function Ho(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 qt(e,t){if(b.isStringLiteral(e)||b.isNumericLiteral(e)||b.isBooleanLiteral(e))return e.value;if(b.isNullLiteral(e))return null;if(b.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(b.isIdentifier(e)){let n=Rr(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(b.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||b.isSpreadElement(r))return;let o=qt(r,t);if(o===void 0)return;n.push(o)}return n}if(b.isObjectExpression(e)){let n={};for(let r of e.properties){if(!b.isObjectProperty(r)||r.computed||!b.isExpression(r.value))return;let o=null;if(b.isIdentifier(r.key)?o=r.key.name:b.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!b.isIdentifier(r.value))return;let s=Rr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=qt(r.value,t);if(i===void 0)return;n[o]=i}return n}if(b.isMemberExpression(e)){let n=Le(e,"",t);if(!n)return;let r=Rr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Ou(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(b.isCallExpression(e))return Du(e,t)??void 0}function Mu(e,t,n){let r=Le(e,n,t);if(!r)return b.isMemberExpression(e)||b.isBinaryExpression(e)||b.isLogicalExpression(e)||b.isConditionalExpression(e)||b.isCallExpression(e)?{value:bt(e,n),source:null}:null;let o=Rr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Ou(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 $s(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:hx(),parentStack:[],valueScopes:i,importMap:o}}function Us(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Kt(o.id))Xs(n,s);if(!b.isIdentifier(o.id)||!o.init||!b.isExpression(o.init))continue;let i=qt(o.init,t);i!==void 0&&xx(n,o.id.name,i)}}function bx(e){let t=[];for(let n of e){if(b.isVariableDeclaration(n)){t.push(n);continue}b.isExportNamedDeclaration(n)&&n.declaration&&b.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function Sx(e,t,n){let r=[],o=0;for(let i of e)if(b.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Xe(i),editable:!0,source:null})}else if(b.isJSXExpressionContainer(i)&&b.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Xe(i),editable:!0,source:null});else if(b.isJSXExpressionContainer(i)&&b.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:Xe(i),editable:!0,source:null}):r.push({index:o++,value:bt(s,n),sourceRange:Xe(i),editable:!0,source:Le(s,n,t)})}else if(b.isJSXExpressionContainer(i)&&b.isExpression(i.expression)){let s=Mu(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Xe(i),editable:!0,source:s.source})}return r}function Ex(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!b.isJSXAttribute(i))continue;let s=Ix(i.name);if(!s)continue;let a=bt(i,n);if(b.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Xe(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:Xe(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(b.isJSXExpressionContainer(i.value)&&b.isExpression(i.value.expression)){let c=qt(i.value.expression,t);if(s==="className"){let d=typeof c=="string"?c:c===void 0?Du(i.value.expression,t):null;if(d){r.push({name:s,value:d,sourceRange:Xe(i),source:null,resolvedValue:d,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:d}});continue}}let l=Mu(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:Ax(c),sourceRange:Xe(i),source:Le(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=kx(i.value.expression,t),f=Le(i.value.expression,n,t),m=l?.value??bt(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":m,sourceRange:Xe(i),source:l?.source??f,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function vx(e,t,n){return e.attributes.flatMap((r,o)=>!b.isJSXSpreadAttribute(r)||!b.isExpression(r.argument)?[]:[{raw:bt(r.argument,n),sourceRange:Xe(r),order:o,source:Le(r.argument,n,t)}])}function Ix(e){return b.isJSXIdentifier(e)?e.name:b.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function kx(e,t){return At(e,{resolveIdentifier(n){let r=Rr(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=qt(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function Du(e,t){let n=Xn(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function Xn(e,t){if(b.isStringLiteral(e))return[e.value];if(b.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(b.isNullLiteral(e))return[];if(b.isBooleanLiteral(e))return e.value?null:[];if(b.isIdentifier(e)||b.isMemberExpression(e)){if(b.isIdentifier(e)&&e.name==="undefined")return[];let n=qt(e,t);return typeof n=="string"?[n]:null}if(b.isConditionalExpression(e)){let n=Xn(e.consequent,t),r=Xn(e.alternate,t);return!n||!r?null:[...n,...r]}if(b.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=qt(e.left,t);return n===!1||n===null?[]:Xn(e.right,t)}if(b.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||b.isSpreadElement(r))return null;let o=Xn(r,t);if(!o)return null;n.push(...o)}return n}if(b.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!b.isObjectProperty(r))return null;let o=Rx(r.key);if(!o)return null;n.push(o)}return n}if(b.isCallExpression(e)){let n=Cx(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!b.isExpression(o))return null;let i=Xn(o,t);if(!i)return null;r.push(...i)}return r}return null}function Cx(e){return b.isIdentifier(e)?e.name:b.isMemberExpression(e)&&b.isIdentifier(e.property)?e.property.name:null}function Rx(e){return b.isIdentifier(e)?e.name:b.isStringLiteral(e)?e.value:null}function wx(e,t){let n=e.attributes.find(r=>b.isJSXAttribute(r)&&b.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!b.isJSXAttribute(n)||!b.isJSXExpressionContainer(n.value)?null:n.value.expression}function Nx(e,t){for(let n of t){let r=wx(e,n);if(r)return r}return null}function Px(e){return b.isJSXIdentifier(e.name)?e.name.name:null}function Ax(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function Tx(e){if(!b.isCallExpression(e)&&!b.isOptionalCallExpression(e))return null;let t=e.callee;return!b.isMemberExpression(t)&&!b.isOptionalMemberExpression(t)||!b.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!b.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Vs(e){return b.isArrowFunctionExpression(e)||b.isFunctionExpression(e)}function Fx(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function _x(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function Tu(e,t,n,r){if(!e||!b.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:bt(e,n),collectionSource:Le(e,n,r)};if(t){let i=t.params[0],s=t.params[1];b.isIdentifier(i)&&(o.itemParamName=i.name),b.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Jt(e,t,n){if(!e)return[];if(b.isJSXElement(e)){if(Js(e))return Qo(e.children,t,n);let r=Yo(e,t,n);return r?[r]:[]}return zn(e)?Zo(e,t,n):b.isParenthesizedExpression(e)?Jt(e.expression,t,n):b.isExpression(e)?qo(e,t,n):[]}function Wo(e,t,n){let r=new Map;for(let o of e.params)for(let i of Kt(o))Xs(r,i);t.valueScopes.push(r);try{if(!b.isBlockStatement(e.body))return Jt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Lu(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Lu(e,t,n){let r=[];for(let o of e){if(b.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){Us([o],t,i);for(let s of o.declarations)b.isIdentifier(s.id)&&(b.isJSXElement(s.init)||b.isJSXFragment(s.init))&&r.push(...Jt(s.init,t,n))}continue}r.push(...Ks(o,t,n))}return r}function Ks(e,t,n){if(b.isReturnStatement(e))return e.argument?Jt(e.argument,t,n):[];if(b.isBlockStatement(e))return xn(e.body,t,n);if(b.isIfStatement(e)){let r=b.isBlockStatement(e.consequent)?xn(e.consequent.body,t,n):Ks(e.consequent,t,n),o=e.alternate?b.isBlockStatement(e.alternate)?xn(e.alternate.body,t,n):Ks(e.alternate,t,n):[];return[...r,...o]}if(b.isSwitchStatement(e))return xn(e.cases.flatMap(r=>r.consequent),t,n);if(b.isTryStatement(e)){let r=xn(e.block.body,t,n);return e.handler&&r.push(...xn(e.handler.body.body,t,n)),e.finalizer&&r.push(...xn(e.finalizer.body,t,n)),r}return[]}function xn(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Lu(e,t,n)}finally{t.valueScopes.pop()}}function Go(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Xe(r),sourceCandidates:i&&i.length>0?i:void 0})}function Ox(e,t,n,r){let o=Nx(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Fu(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!b.isJSXAttribute(s))continue;let a=Px(s);if(!a||!b.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!b.isJSXEmptyExpression(c)){if(Fx(a)&&Vs(c)){let l=Wo(c,n,r),u=Tu(o,c,r,n);Go(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(_x(a)){let l=Vs(c)?Wo(c,n,r):Jt(c,n,r);Go(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!b.isJSXExpressionContainer(s)||!Vs(s.expression))continue;let a=Wo(s.expression,n,r),c=Tu(o,s.expression,r,n);Go(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function Yo(e,t,n){let r=Fu(e.openingElement);if(r==="Fragment"||Js(e))return Qo(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=px(r),a;if(s){let w=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${w}`}else{let w=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${w}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=br(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:u},m=s?"component-boundary":null,d=Sx(e.children,t,n),g=Ex(e.openingElement,t,n),h=vx(e.openingElement,t,n),E,S,v=!1;if(s){let w=t.importMap.get(r)??t.importMap.get(mx(r));w&&(E=w.specifier,S=w.exportName,v=Cr(w.specifier,t.file))}let C={identity:f,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Xe(e),parentKey:i,childKeys:[],textSegments:d,attributes:g.length>0?g:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:m,isOpaque:s,...v?{isPublicUiComponent:!0}:{},importedFrom:E,exportName:S};return t.elements.set(u,C),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),Ox(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),Mx(e.children,t,n),t.parentStack.pop()),u}function Zo(e,t,n){return Qo(e.children,t,n)}function Qo(e,t,n){let r=[];for(let o of e)if(b.isJSXElement(o))if(Js(o))r.push(...Qo(o.children,t,n));else{let i=Yo(o,t,n);i&&r.push(i)}else zn(o)?r.push(...Zo(o,t,n)):b.isJSXExpressionContainer(o)&&r.push(...qo(o.expression,t,n));return r}function Mx(e,t,n){for(let r of e)b.isJSXElement(r)?Yo(r,t,n):zn(r)?Zo(r,t,n):b.isJSXExpressionContainer(r)&&qo(r.expression,t,n)}function Dx(e){return e==="&&"||e==="||"||e==="??"}function qo(e,t,n){if(b.isJSXEmptyExpression(e))return[];let r=Tx(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:bt(r.collection,n),collectionSource:Le(r.collection,n,t)};if(b.isArrowFunctionExpression(a)||b.isFunctionExpression(a)){let u=a.params[0],f=a.params[1];b.isIdentifier(u)&&(c.itemParamName=u.name),b.isIdentifier(f)&&(c.indexParamName=f.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Xe(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(b.isArrowFunctionExpression(a)||b.isFunctionExpression(a))&&l.childKeys.push(...Wo(a,t,n)),l.childKeys}if(b.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:bt(e.test,n),conditionSource:Le(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Xe(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Jt(e.consequent,t,n)),s.childKeys.push(...Jt(e.alternate,t,n)),s.childKeys}if(b.isLogicalExpression(e)&&Dx(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:bt(e.left,n),conditionSource:Le(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Xe(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Jt(e.right,t,n)),s.childKeys}if(b.isParenthesizedExpression(e))return qo(e.expression,t,n);if(b.isJSXElement(e)){let o=Yo(e,t,n);return o?[o]:[]}return zn(e)?Zo(e,t,n):[]}function Lx(e){let t=e.argument;return t&&(b.isExpression(t)||zn(t))?t:null}function wr(e,t){let n=[];for(let r of e){if(b.isReturnStatement(r)){let o=Lx(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(b.isIfStatement(r)){let o=b.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...wr(o,r.test)),r.alternate){let i=b.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...wr(i,r.test))}continue}if(b.isSwitchStatement(r))for(let o of r.cases){let i=o.test?b.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...wr(o.consequent,i))}}return n}function Bu(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier),i=new Map,s=[],a=[],c=new Map,l=yx(r);fx(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let m=gx(f);if(!m)return;let d=f.node,g=[];if(b.isArrowFunctionExpression(d))b.isExpression(d.body)||zn(d.body)?g=[{argument:d.body,statement:b.returnStatement(b.isExpression(d.body)?d.body:null)}]:b.isBlockStatement(d.body)&&(g=wr(d.body.body));else{let w=d.body;b.isBlockStatement(w)&&(g=wr(w.body))}if(g.length===0){f.skip();return}let h=new Map;Us(bx(r.program.body),$s(t,m,i,s,l,[h]),h);let E=new Map;for(let w of d.params)for(let A of Kt(w))Xs(E,A);let S=b.isBlockStatement(d.body)?d.body.body:[],v=g[0]?.statement??null;for(let w of S){if(v&&w===v)break;b.isVariableDeclaration(w)&&Us([w],$s(t,m,i,s,l,[h,E]),E)}let C=$s(t,m,i,s,l,[h,E]);for(let w of g){let A=Jt(w.argument,C,n);for(let P of A)a.includes(P)||a.push(P);if(w.condition){let P={kind:"conditional-branch",conditionExpression:bt(w.condition,n),conditionSource:Le(w.condition,n,C)};Go(C,"conditional-region","",w.statement,A,[P])}}f.skip()}});let u=[...i.keys()];return u.length>0&&c.set(t,u),{graph:{routeId:t,rootKeys:a,elements:i,regions:s,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function zs(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function ei(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function ju(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??kr,c=new Map,l=new Map,u=new Map,f=[],m=new Set,d=S=>{let v=`${S.path}\0${S.code}\0${S.message}\0${JSON.stringify(S.details??{})}`;m.has(v)||(m.add(v),f.push(S))},g=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(S=>({file:S.file,source:S.source,depth:0,diagnosticEntryFile:S.file,importStack:[]}))],h=new Set;for(;g.length>0;){let S=g.shift(),{file:v,source:C,depth:w,diagnosticEntryFile:A,importStack:P}=S;if(h.has(v))continue;h.add(v),c.set(v,C);let k=a(v,C);if(!k.ok){d(ei(k.diagnostic,A,P));continue}u.set(v,k.module);let{graph:T,localImports:_}=Bu(k.module);for(let L of T.elements.values())if(L.importedFrom&&Tt(L.importedFrom)){let G=L.importedFrom,ne=await Xo(v,G,r);ne.ok?(L.importedFrom=ne.path,yn(ne.path)&&(L.isPublicUiComponent=!0)):Cr(G,v)||d(ei(ne.diagnostic,A,zs(P,v,G,ne.diagnostic.path)))}if(l.set(v,T),!(w>=i))for(let L of _){if(Pu(L))continue;let G=await Xo(v,L,r);if(!G.ok){Cr(L,v)||d(ei(G.diagnostic,A,zs(P,v,L,G.diagnostic.path)));continue}let ne=G.path;if(h.has(ne)||yn(ne))continue;let ve=zs(P,v,L,ne);try{let Y=await n(ne);g.push({file:ne,source:Y,depth:w+1,diagnosticEntryFile:A,importStack:ve})}catch(Y){d(ei({path:ne,code:"import-read-failed",message:`Failed to read imported file: ${ne}`,details:{fromFile:v,specifier:L,reason:Y instanceof Error?Y.message:String(Y)}},A,ve))}}}let E=Bx(e,l,s,(o.additionalEntries??[]).map(S=>S.file));return E.diagnostics=f,{graph:E,allSources:c,diagnostics:f,parsedModules:u,entryModule:u.get(e)??null}}function Bx(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,f]of l.elements)o.set(u,f);for(let u of l.regions)i.push(u);for(let[u,f]of l.fileIndex){let m=s.get(u)??[];s.set(u,[...m,...f])}if(c===e){a=l.rootKeys;continue}r.includes(c)&&(a=[...a,...l.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}import{SiteEditHistoryProvenanceSchema as jx}from"@vcp-dev/contracts";var $x={affectedCompositions:[]};function Xu(e){let t=null,n=new WeakMap;async function r(){return t??=Vx(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(Ku(o),{durableManifest:!1}),a;try{a=await e.previewStagedAppend(s.entryId,i.digest)}catch(l){throw await e.discardStage(s.stageId),l}let c={kind:"append",entry:o,historyTransition:a};return n.set(c,{expectedDigest:i.digest,stageId:s.stageId,entryId:s.entryId}),c},async prepareUndo(){let i=(await r()).undo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("undo entry is missing from index");let c=a-1,l=await e.previewCursor(c,s.digest),u={kind:"undo",entry:i,historyTransition:l};return n.set(u,{expectedDigest:s.digest,cursor:c}),u},async prepareRedo(){let i=(await r()).redo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("redo entry is missing from index");let c=a,l=await e.previewCursor(c,s.digest),u={kind:"redo",entry:i,historyTransition:l};return n.set(u,{expectedDigest:s.digest,cursor:c}),u},async publishPrepared(o){let i=n.get(o);if(!i)throw new Error("history mutation was not prepared");let s=await r();if(o.kind==="append"){if(!i.entryId)throw new Error("staged entry id is missing");let a=await e.publishStagedAppend(i.entryId,i.expectedDigest,i.stageId);$u(a,o.historyTransition),o.entry.historyId=i.entryId,s.entryIds=[...a.entryIds],s.cursor=a.cursor,s.undo.push(o.entry),s.redo.length=0}else{if(i.cursor===void 0)throw new Error("prepared cursor is missing");let a=await e.setCursor(i.cursor,i.expectedDigest);if($u(a,o.historyTransition),o.kind==="undo"){if(s.undo.at(-1)!==o.entry)throw new Error("undo state changed before publish");s.undo.pop(),s.redo.push(o.entry)}else{if(s.redo.at(-1)!==o.entry)throw new Error("redo state changed before publish");s.redo.pop(),s.undo.push(o.entry)}s.cursor=i.cursor}n.delete(o)},async discardPrepared(o){let i=n.get(o);if(!i)return;let s=o.historyTransition;if(s){let a=await e.readIndex();if(a.digest===s.publishedIndexDigest&&a.cursor===s.publishedCursor&&a.currentId===s.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}i.stageId&&await e.discardStage(i.stageId),n.delete(o)},async peekUndo(){return(await r()).undo.at(-1)??null},async pushUndo(o){let i=await r(),s=o;if(s.historyId){let l=i.entryIds.indexOf(s.historyId);if(l>=0)try{await e.setCursor(l),i.undo.push(o),i.cursor=l;return}catch(u){throw i.redo.push(o),u}}let a=await e.append(Ku(o)),c=a.currentId;if(!c)throw new Error("history store did not publish an entry");o.historyId=c,i.entryIds=[...a.entryIds],i.cursor=a.cursor,i.undo.push(o),i.redo.length=0},async popUndo(){return(await r()).undo.pop()??null},async peekRedo(){return(await r()).redo.at(-1)??null},async pushRedo(o){let i=await r(),s=o;if(!s.historyId)throw i.undo.push(o),new Error("cannot move an unpersisted history entry to redo");let a=i.entryIds.indexOf(s.historyId);if(a<0)throw i.undo.push(o),new Error("history entry is missing from the durable index");try{await e.setCursor(a-1),i.cursor=a-1,i.redo.push(o)}catch(c){throw i.undo.push(o),c}},async popRedo(){return(await r()).redo.pop()??null},async clearRedo(){(await r()).redo.length=0},async getStatus(){let o=await e.readStatus();return{canUndo:o.canUndo,canRedo:o.canRedo,undoDepth:o.undoDepth,redoDepth:o.redoDepth,recoveryRequired:o.recoveryRequired}},async markRecoveryRequired(o){await e.markRecoveryRequired(o)}}}function $u(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")}async function Vx(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>Vu(e,o))),r=await Promise.all(t.redoIds.map(async o=>Vu(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function Vu(e,t){let n=await e.readEntry(t),r=Ux(n),o=r.provenance??$x;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 Uu(e,n,r.preSnapshots),postSnapshots:await Uu(e,n,r.postSnapshots)}}async function Uu(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(Xx(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Ku(e){let t=[],n=(i,s)=>i.map((a,c)=>{let l={file:a.file,exists:a.exists!==!1,version:a.version,...a.sha256?{sha256:a.sha256}:{}};if(l.exists){let u=`${s}-${c}`;l.blobName=u,t.push({name:u,data:a.content})}return l}),r=Kx(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 Ux(e){if(!Hu(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:zu(t.provenance)}:{},preSnapshots:Ju(t.preSnapshots,"preSnapshots"),postSnapshots:Ju(t.postSnapshots,"postSnapshots")}}function Kx(e){if(e.provenance!==void 0)return zu(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function zu(e){let t=jx.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 Ju(e,t){return e.map((n,r)=>{if(!Hu(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&&!Jx(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 Jx(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function Xx(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Hu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{COMPONENT_I18N_FILE_SUFFIX as zx,parseComponentI18nResourcesJson as Hx,resolveSiteTextDirection as Wx,SiteLocaleSchema as Gx}from"@vcp-dev/contracts";var Yx=["i18next","react-i18next"],Zx="components/ui/site-locale-provider.tsx",Qx="components/ui/component-i18n-provider.tsx",Wu="app/layout.tsx";async function Ws(e){let t=e.files.filter(m=>m.path.endsWith(zx));if(t.length===0)return{ok:!0};for(let m of["package.json",Wu,Zx,Qx])if(!await e.exists(m))return bn(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return bn("Target snapshot package.json is invalid.")}let r=Gu(n)&&Gu(n.dependencies)?n.dependencies:{},o=Yx.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return bn(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(Wu),s=Hs(i,"html","lang"),a=Hs(i,"html","dir"),c=Hs(i,"SiteLocaleProvider","locale"),l=Gx.safeParse(s);if(!l.success||!a||!c||s!==c||a!==Wx(l.data))return bn("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 bn("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data,f=u.split("-")[0];for(let m of t){let d=Hx(m.content);if(!d.success)return bn(`Component i18n resource is invalid: ${m.path}.`);if(!Object.hasOwn(d.data,u)&&!Object.hasOwn(d.data,f))return bn(`Component i18n resource ${m.path} has no locale for ${u} or ${f}.`)}return{ok:!0}}function Hs(e,t,n){let r=e.match(new RegExp(`<${t}\\b[^>]*>`))?.[0];if(!r)return null;let o=[...r.matchAll(new RegExp(`\\b${n}=(?:"([^"]+)"|\\{"([^"]+)"\\})`,"g"))];return o.length!==1?null:o[0]?.[1]??o[0]?.[2]??null}function Gu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bn(e){return{ok:!1,message:e}}import{randomBytes as pb}from"node:crypto";import ni from"node:path";import{parse as qs}from"@babel/parser";import mb from"@babel/traverse";import*as od from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Ys,PageResourceArtifactSchema as gb,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as hb,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as yb,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as xb,parseComponentI18nResourcesJson as bb}from"@vcp-dev/contracts";var Zu=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,Qu=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,qx=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,eb=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,tb=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,nb=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,rb=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,ob=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,ib=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,sb=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,ab=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,cb=/\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,lb=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,ub=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Nr(e,t){let n=ti([...pt(e,qx),...pt(e,eb),...pt(e,tb),...pt(e,t.includeRgbBackgroundImage?nb:rb),...t.includeExtendedColorFunctions?[...pt(e,ob),...pt(e,ib)]:[]]),r=ti([...pt(e,sb),...pt(e,ab)]).filter(o=>t.colorMixPolicy==="always"||Zu.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...pt(e,cb).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...pt(e,ub).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:ti(pt(e,Qu)),hardCodedSurfaceOccurrences:fb(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?ti(pt(e,lb)):[]}}function pt(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var Yu=160,db=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function fb(e){let t=new RegExp(Qu.source,"g"),n=[0];for(let s=0;s<e.length;s+=1)e[s]===`
5
- `&&n.push(s+1);let r=s=>{let a=0,c=n.length-1;for(;a<c;){let l=Math.ceil((a+c)/2);(n[l]??0)<=s?a=l:c=l-1}return a},o=[],i;for(;(i=t.exec(e))!==null;){let s=i[0],a=s.endsWith("/")?s.slice(0,-1):s,c=/^\/(\d+)/.exec(e.slice(i.index+a.length)),l=e.slice(Math.max(0,i.index-64),i.index),u=db.exec(l),f=r(i.index),m=e.indexOf(`
6
- `,i.index),d=e.slice(n[f]??0,m===-1?void 0:m).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:f+1,snippet:d.length>Yu?`${d.slice(0,Yu-1)}\u2026`:d})}return o}function ti(e){return[...new Set(e)]}var Zs="{{$INSTANCE}}",Sb=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Eb=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Qs="components/site/generated",vb=/\.(?:tsx?|json)$/,Ib=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,kb=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Cb=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Gs=mb,Rb=typeof Gs=="function"?Gs:Gs.default;async function ea(e){let t=gb.safeParse(e.artifact);if(!t.success)return me("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>pb(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=Lb(r());if(!i)return me("Random instance suffix must be 8 lowercase hex chars.");let s=`${Bb(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let C of n.pages){let w=C.final_route.slice(1);a.set(C.template_page_id,C.final_route),c.set(C.template_page_id,C.title),l.push({template_page_id:C.template_page_id,title:C.title,final_route:C.final_route,route_file_path:`app/${w}/page.tsx`})}let u=[],f=new Set,m=new Set,d=new Map,g=new Map,h=[],E=new Set(n.pages.flatMap(C=>C.components.map(w=>w.component_id)));for(let C of n.components){if(!E.has(C.component_id))continue;let w=qu({materialization:C.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!w.ok)return w;for(let A of w.files){let P=td(A,f,u);if(P)return P}m.add(w.entry),g.set(w.entry,w.entryExport),d.set(C.component_id,w.entry)}for(let[C,w]of n.pages.entries()){let A=l[C],P=qu({materialization:w.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:A.route_file_path,pageTitle:A.title});if(!P.ok)return P;for(let _ of P.files){let L=td(_,f,u);if(L)return L}m.add(P.entry),g.set(P.entry,P.entryExport),h.push({entry:P.entry,declaredComponentIds:new Set(w.components.map(_=>_.component_id))});let k=u.find(_=>_.file===A.route_file_path);if(!k)return me("Page materialization entry did not resolve to its final route file.",A.route_file_path);if(Tb(k.content,A.route_file_path)!==A.final_route)return me(`Page ${w.template_page_id} requires a static PAGE_SEO.path equal to ${A.final_route}.`,A.route_file_path)}let S=Nb(u,m,s,d,h,g);if(!S.ok)return S;for(let C of u)if(await e.exists(C.file))return!C.file.startsWith("app/")&&o>1?ea({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${C.file}`,path:C.file};let v=Pb(u);return v||(u.sort((C,w)=>C.file.localeCompare(w.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function qu(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:ed(o.pathTemplate,e.packageInstanceId);if(!s)return me("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=wb(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?Fb(a.data,e.pageTitle,s):a;if(!c.ok)return c;n.push({operation:"create-only",file:s,content:c.data})}let r=e.pageEntryTarget??ed(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?me("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function wb(e,t,n,r){let o,i=e.replace(Sb,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return me(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(Eb,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return me(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(Zs,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?me("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function ed(e,t){let n=`${Qs}/${t}`;if(e.split(Zs).length>2)return null;let o=e.replace(Zs,t),i=`${Qs}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=ni.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!vb.test(a)||Ib.test(a)?null:a}function td(e,t,n){return t.has(e.file)?me(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function Nb(e,t,n,r,o,i){let s=new Set(e.map(d=>d.file)),a=`${Qs}/${n}`,c=new Map(e.map(d=>[d.file,new Set])),l=new Map;for(let d of e){if(d.file.endsWith(".json")){try{JSON.parse(d.content)}catch{return me("Materialization JSON file must contain valid JSON.",d.file)}if(d.file.endsWith(Ys)&&!bb(d.content).success)return me("Materialization component i18n resources are invalid.",d.file);continue}try{let h=qs(d.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(d.file,h);for(let S of h.program.body)if((S.type==="ImportDeclaration"||S.type==="ExportAllDeclaration"||S.type==="ExportNamedDeclaration"&&S.source)&&S.source){let v=S.source.value,C=Mb(d.file,v,s,a);if(!C.allowed)return me(`Materialization import is outside the controlled package: ${v}`,d.file);C.internalPath&&c.get(d.file).add(C.internalPath)}let E;if(Rb(h,{Identifier(S){S.isReferencedIdentifier()&&Cb.has(S.node.name)&&(E??=S.node.name,S.stop())},JSXAttribute(S){S.node.name.type==="JSXIdentifier"&&S.node.name.name==="style"&&(E??="inline style",S.stop())},JSXOpeningElement(S){S.node.name.type==="JSXIdentifier"&&S.node.name.name.toLowerCase()==="style"&&(E??="style element",S.stop())}}),E)return me(`Materialization source uses forbidden capability: ${E}`,d.file)}catch{return me("Materialization source must parse as TS/TSX.",d.file)}let g=Nr(d.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(g.hardCodedSurfaceHits.length>0||g.rawColorHits.length>0||g.privateTokenHits.length>0)return me("Materialization source violates the public theme token policy.",d.file)}if([...t].some(d=>!s.has(d)))return me("Materialization entry is outside the controlled package.");for(let d of t)if(d.endsWith(".json"))return me("Materialization JSON files cannot be package entries.");for(let[d,g]of i){let h=l.get(d);if(!h||!Ab(h,g))return me("Materialization entry does not declare its contracted export.",d)}let u=new Map([...r].map(([d,g])=>[g,d]));for(let d of o){let g=rd(d.entry,c);for(let h of d.declaredComponentIds){let E=r.get(h);if(!E||!g.has(E))return me(`Page entry does not reach declared component: ${h}`,d.entry)}for(let h of g){let E=u.get(h);if(E&&!d.declaredComponentIds.has(E))return me(`Page entry imports undeclared component: ${E}`,d.entry)}}let f=new Set;for(let d of t)for(let g of rd(d,c))f.add(g);if(f.size!==e.length)return me("Every materialization file must be reachable from a package entry.");let m=Db(e,l,c);return m||{ok:!0}}function Pb(e){if(e.length>hb)return me("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>yb)return me("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>xb?me("Page resource exceeds the aggregate content byte limit."):null}function Ab(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 Tb(e,t){let n;try{n=qs(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}for(let r of n.program.body){let o=r.type==="VariableDeclaration"?r:r.type==="ExportNamedDeclaration"&&r.declaration?.type==="VariableDeclaration"?r.declaration:null;if(o)for(let i of o.declarations){if(i.id.type!=="Identifier"||i.id.name!=="PAGE_SEO")continue;let s=ri(i.init);if(s?.type!=="ObjectExpression")return null;for(let a of s.properties){if(a.type!=="ObjectProperty"||a.computed||!_b(a.key))continue;let c=ri(a.value);return c?.type==="StringLiteral"?c.value:c?.type==="TemplateLiteral"&&c.expressions.length===0?c.quasis[0]?.value.cooked??null:null}return null}}return null}function Fb(e,t,n){let r;try{r=qs(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return me("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=ri(s.init);if(a?.type!=="ObjectExpression")return me("Page materialization PAGE_SEO must be a static object.",n);let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&Ob(u.key));if(!c||c.type!=="ObjectProperty")return me("Page materialization PAGE_SEO must declare a static title.",n);let l=ri(c.value);return!l||l.type!=="StringLiteral"&&l.type!=="TemplateLiteral"||l.type==="TemplateLiteral"&&l.expressions.length>0||typeof l.start!="number"||typeof l.end!="number"?me("Page materialization PAGE_SEO.title must be a static string.",n):{ok:!0,data:e.slice(0,l.start)+JSON.stringify(t)+e.slice(l.end)}}}return me("Page materialization must declare a top-level PAGE_SEO object.",n)}function ri(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&od.isExpression(t)?t:null}function _b(e){return e.type==="Identifier"&&e.name==="path"||e.type==="StringLiteral"&&e.value==="path"}function Ob(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function Mb(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=nd(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:kb.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=ni.posix.normalize(ni.posix.join(ni.posix.dirname(e),t)),i=nd(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function nd(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 Db(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Ys))continue;let i=o.file.slice(0,-Ys.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return me("Component i18n resources require a same-name TS/TSX companion.",o.file);let c=t.get(s)?.program.directives.some(u=>u.value.value==="use client"),l=[...n].filter(([,u])=>u.has(o.file));if(!c||l.length!==1||l[0]?.[0]!==s)return me("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function rd(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 Lb(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function Bb(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function me(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as jb}from"node:crypto";import Xt from"node:path";import{parse as $b}from"@babel/parser";import Vb from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as oi,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as id,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as Ub,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as Kb,SiteEditMaterializationSchema as Jb,parseComponentI18nResourcesJson as Xb}from"@vcp-dev/contracts";var ra="components/site/generated",sd="{{$INSTANCE}}",ii=5,zb=/^[a-z][a-z0-9-]{0,48}$/,Hb=/^[a-f0-9]{8}$/,ad=/\.tsx?$/,Wb=/\.json$/,Gb=/\.(?:tsx?|json)$/,Yb=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Zb=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],ta=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),na=Vb,Qb=typeof na=="function"?na:na.default;function qb(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>id)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=uS(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=Jb.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=aS(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${ra}.`,path:e.generatedRoot}};if(!pd(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=ud(r.data.files),s=ud(e.controlledFiles);if(!dS(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>id)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[c,l]of r.data.files.entries()){let u=Buffer.byteLength(l.content,"utf8");if(u>Ub)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file exceeds the per-file content limit.",file:l.pathTemplate,path:`files[${c}]`}};a+=u}return a>Kb?{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 eS(e){let t=qb(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=pd(e.manifest.instanceBaseName),o=Math.max(1,Math.min(ii,e.maxAttempts??ii));for(let i=0;i<o;i+=1){let s=cS(e.instanceNameGenerator?.()??jb(4).toString("hex"));if(!s)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let a=`${r}-${s}`,c=gd(n,a),l=tS({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,allowedExternalImports:e.allowedExternalImports??Zb});if(!l.ok)return l;if(!await nS(e.exists,c,l.data.files))return{ok:!0,data:l.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function fd(e){let t=Math.max(1,Math.min(ii,e.maxAttempts??ii));for(let n=0;n<t;n+=1){let r=await eS({...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 tS(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=cd({pathTemplate:i.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!s.ok)return s;if(n.has(s.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${s.data}`,path:s.data}};n.add(s.data),t.push({kind:"create-only",path:s.data,content:i.content,...i.role?{role:i.role}:{},sourcePathTemplate:i.pathTemplate})}t.sort((i,s)=>i.path.localeCompare(s.path));let r=cd({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!r.ok)return r;if(!t.some(i=>i.path===r.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:r.data}};let o=rS(t,e.instanceRoot,r.data,e.manifest.entry.export,e.allowedExternalImports);return o.ok?{ok:!0,data:{kind:"static-prefab-materialization",instanceName:e.instanceName,generatedRoot:e.generatedRoot,instanceRoot:e.instanceRoot,entry:{path:r.data,export:e.manifest.entry.export},files:t}}:o}async function nS(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function cd(e){if(e.pathTemplate.split(sd).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(sd,e.instanceName),n=lS(t);return n?gd(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||!Gb.test(n)||Yb.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 rS(e,t,n,r,o){let i=new Set(e.map(f=>f.path)),s=new Map,a=new Map(e.map(f=>[f.path,new Set])),c=new Map;for(let f of e){if(Wb.test(f.path)){if(f.path.endsWith(oi)){let g=Xb(f.content);if(!g.success)return Sn("MATERIALIZATION_DATA_UNSUPPORTED",g.error.message,f.path);c.set(f.path,new Set)}else try{JSON.parse(f.content)}catch{return Sn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",f.path)}continue}let m;try{m=$b(f.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:f.path}}}let d=Nr(f.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(d.hardCodedSurfaceHits.length>0||d.rawColorHits.length>0||d.privateTokenHits.length>0)return{ok:!1,error:{code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source must use public semantic design tokens instead of raw colors or private tokens.",file:f.path}};s.set(f.path,m)}for(let f of e){if(!ad.test(f.path))continue;let m=s.get(f.path),d=null;if(Qb(m,{ImportDeclaration(g){let h=ld({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!h.allowed)d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:f.path},g.stop();else if(h.internalPath&&(a.get(f.path).add(h.internalPath),h.internalPath.endsWith(oi))){let E=oS({importer:f.path,imported:h.internalPath,source:g.node.source.value,ast:m});E.ok?c.get(h.internalPath).add(f.path):(d??=E.error,g.stop())}},ExportAllDeclaration(g){d??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:f.path},g.stop()},ExportNamedDeclaration(g){if(g.node.source){let h=ld({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!h.allowed||!h.internalPath?(d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:f.path},g.stop()):a.get(f.path).add(h.internalPath)}},CallExpression(g){if(g.node.callee.type==="Import"){d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:f.path},g.stop();return}g.node.callee.type==="Identifier"&&g.node.callee.name==="require"&&(d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:f.path},g.stop())},NewExpression(g){g.node.callee.type==="Identifier"&&g.node.callee.name==="Function"&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:f.path},g.stop())},MetaProperty(g){g.node.meta.type==="Identifier"&&g.node.meta.name==="import"&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:f.path},g.stop())},MemberExpression(g){let h=dd(g.node);h&&ta.has(h)&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},OptionalMemberExpression(g){let h=dd(g.node);h&&ta.has(h)&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&ta.has(g.node.name)&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${g.node.name}.`,file:f.path},g.stop())},JSXAttribute(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name==="style"&&(d??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:f.path},g.stop())},JSXOpeningElement(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name.toLowerCase()==="style"&&(d??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:f.path},g.stop())}}),d)return{ok:!1,error:d}}if(!ad.test(n))return Sn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return Sn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!iS(l,r))return Sn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[f,m]of c)if(m.size!==1)return Sn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",f);return sS(n,a).size!==e.length?Sn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:ra,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function ld(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return e.source.startsWith("@/components/site/generated/")?{allowed:!1}:{allowed:e.allowedExternalImports.some(o=>o.endsWith("/")?e.source.startsWith(o):e.source===o)};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Xt.posix.normalize(Xt.posix.join(Xt.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 oS(e){let t=Xt.posix.dirname(e.importer),n=Xt.posix.dirname(e.imported),r=Xt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Xt.posix.basename(e.imported).slice(0,-oi.length),i=`./${r}${oi}`;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 iS(e,t){for(let n of e.program.body){if(t.kind==="default"&&n.type==="ExportDefaultDeclaration")return!0;if(t.kind!=="named"||n.type!=="ExportNamedDeclaration")continue;if(n.specifiers.some(o=>o.exported.type==="Identifier"&&o.exported.name===t.name))return!0;let r=n.declaration;if((r?.type==="FunctionDeclaration"||r?.type==="ClassDeclaration")&&r.id?.name===t.name||r?.type==="VariableDeclaration"&&r.declarations.some(o=>o.id.type==="Identifier"&&o.id.name===t.name))return!0}return!1}function sS(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 Sn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function aS(e){let t=md(e);return t===ra?t:null}function cS(e){let t=e.trim().toLowerCase();return Hb.test(t)?t:null}function pd(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 zb.test(t)?t:null}function md(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Xt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function lS(e){let t=md(e);return!t||t!==e?null:t}function gd(...e){return Xt.posix.join(...e)}function ud(e){return new Set(e.map(t=>t.pathTemplate))}function uS(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 dS(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function dd(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 xa}from"node:crypto";import da from"@babel/traverse";function oa(e){let t=new Map,n=new Map;for(let s of e){if(t.has(s.placementKey))throw new Error(`Duplicate placement key in page composition projection: ${s.placementKey}`);t.set(s.placementKey,s);let a=n.get(s.placementUnitKey)??[];a.push(s),n.set(s.placementUnitKey,a)}let r=new Map,o=new Map,i=new Map;for(let[s,a]of n){let c=Object.freeze([...a]),l=c.find(u=>u.anchorSourceRange!==null&&u.members.length>0)??c.find(u=>u.members.length>0)??c[0];l&&(o.set(s,c),i.set(s,l),r.set(s,Object.freeze({placementUnitKey:s,placementKeys:Object.freeze(c.map(u=>u.placementKey)),sourcePlacementKey:l.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}import{createHash as fS}from"node:crypto";import hd from"node:path";import*as Sd from"@babel/parser";import ia from"@babel/generator";import*as $e from"@babel/types";var yd=typeof ia=="function"?ia:ia.default;function aa(e){let t=Id(e);if(t)return{ok:!1,error:t};let n=e.projection,r=ua(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=gS(n,o),s={jsx:`<${e.component.localName} />`},a=pS(e);if(i){let d=Ed(e);return d.ok?{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:a,rewriteStep:{kind:"insert-root-expression",locator:d.locator,sourceHash:d.sourceHash,node:s,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:d.result}let c=o.containerSourceRange??n.container.sourceRange,l=o.containerSourceHash??(la(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return sa("Route page composition does not expose a verifiable container boundary.");let u=Ar(c),f=xd(e.source,u,l,"Route page composition container");if(!f.ok)return f.result;let m=o.anchorSourceRange?Ar(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return sa("Route page composition placement does not expose a verifiable anchor boundary.");let d=xd(e.source,m,o.anchorSourceHash,"Route page composition anchor");if(!d.ok)return d.result}return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:a,rewriteStep:{kind:"insert-child",parentLocator:u,node:s,placement:o.relation,...m?{anchorLocator:m}:{}}}}}function pS(e){let t=bS(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 si(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return En(e.source,"Root expression rewrite requires an exact expression locator.");let t=mr(e.source,"value");if(!t.ok)return En(e.source,t.diagnostic.message);let n=ie(t.ast,e.locator);if(!n.ok)return En(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return En(e.source,"Resolved value locator does not point to an expression.");let o=Hn(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return En(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith($e.nullLiteral()),{ok:!0,source:yd(t.ast,{}).code};let i;try{i=Sd.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return En(e.source,s instanceof Error?s.message:String(s))}return!$e.isJSXElement(i)&&!$e.isJSXFragment(i)?En(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(mS(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:yd(t.ast,{}).code})}function mS(e,t,n,r){if($e.isNullLiteral(e)||r)return t;let o=$e.isJSXFragment(e)?[...e.children]:[$e.isJSXElement(e)?e:$e.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return $e.jsxFragment($e.jsxOpeningFragment(),$e.jsxClosingFragment(),s)}function En(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function ca(e){let t=Id(e);if(t)return{ok:!1,error:t};let n=e.projection,r=kd(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(hS(n,o)){let h=Ed(e);return h.ok?e.operation==="move-node"?sa("A singleton root expression cannot be moved without a safe parent boundary."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:h.sourceHash,rewriteStep:{kind:e.operation==="remove-node"?"remove-root-expression":"replace-root-expression",locator:h.locator,sourceHash:h.sourceHash}}}:h.result}let s=Ar(o.sourceRange),a=Nt(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?[]:[Pr(a.diagnostic)]}};if(Hn(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")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:"remove-node",locator:s}}};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||!xS(e.targetPlacement.composition,e.composition))return{ok:!1,error:{code:"CROSS_PAGE_MOVE_UNSUPPORTED",message:"Page-unit move across routes or composition templates is not supported.",diagnostics:[]}};if(e.targetPlacement.documentVersion!==e.expectedDocumentVersion)return{ok:!1,error:{code:"VERSION_STALE",message:"Page-unit target placement belongs to a different document version.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Page-unit target placement belongs to a different document version."}]}};let l=ua(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!l.ok)return{ok:!1,error:{code:l.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:l.diagnostic.message,diagnostics:[l.diagnostic]}};let u=l.placement;if(u.placementUnitKey!==e.targetPlacement.placementUnitKey||u.relation!==e.targetPlacement.relation)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit target placement metadata does not match the cached projection.",diagnostics:[]}};let f=u.containerSourceRange;if(!f||!u.containerSourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable container boundary.",diagnostics:[]}};let m=Ar(f),d=Nt(e.source,m);if(!d.ok||!d.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:d.ok===!1?d.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:d.ok?[]:[Pr(d.diagnostic)]}};if(Hn(e.source,d.match.node.start??null,d.match.node.end??null)!==u.containerSourceHash)return bd("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let h=u.anchorSourceRange,E=u.anchorSourceHash;if(!h||!E)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let S=Ar(h),v=Nt(e.source,S);return!v.ok||!v.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:v.ok===!1?v.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:v.ok?[]:[Pr(v.diagnostic)]}}:Hn(e.source,v.match.node.start??null,v.match.node.end??null)!==E?bd("Route page composition target anchor hash no longer matches the current source."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:m,anchorLocator:S,placement:u.relation}}}}return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:m,placement:u.relation}}}}function gS(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&la(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 hS(e,t){return e.container.kind!=="jsx-container"&&la(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function Ed(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Nt(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?[]:[Pr(r.diagnostic)]}}}:Hn(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:vd("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function xd(e,t,n,r){let o=Nt(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?[]:[Pr(o.diagnostic)]}}}:Hn(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:vd(`${r} hash no longer matches the current source.`)}:{ok:!0}}function vd(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function sa(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function bd(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Pr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Id(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&&!yS(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 yS(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function xS(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function bS(e,t){let n=hd.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=hd.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Ar(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Hn(e,t,n){return t==null||n==null?null:`sha256:${fS("sha256").update(e.slice(t,n)).digest("hex")}`}function la(e,t){return e===null||t===null?e===t:e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}var SS=typeof da=="function"?da:da.default;function Nd(e){if(!e.ast)return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=NS(e.ast);if(!t)return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=AS(t);if(!n.ok)return St(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=FS(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(OS(r,t))return St(e,[Be("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return pa(e,t,"virtual-route-root",r);if(_S(r)){let o=BS({input:e,source:e.source,expression:r});return fa(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Oe(r)&&!en(r)){let o=ha(r),i=wd({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return fa(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=DS(r);if(!o.ok)return St(e,[o.diagnostic]);let i=Wn(o.path);if(i.unsupported)return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(MS(e.source,r,i.members))return pa(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Oe(r);if(i.members.length===0&&s)return pa(e,t,"virtual-route-root",r);let a=o.path===r&&s?"virtual-route-root":"jsx-container",c=o.path.isJSXFragment()?"jsx-fragment":"jsx-element",l=wd({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return fa(e,t,l,{kind:a,sourceKind:c},r)}return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function ua(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Be("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:Be("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function kd(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Be("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:Be("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Pd(e){return e.ok?ES(e.projection):vS(e.projection)}function ES(e){let t=new Map,n=[];for(let l of e.placements)l.members.length===0&&e.placements.length>1||l.members.length>0&&!l.anchorSourceRange||t.has(l.placementUnitKey)||t.set(l.placementUnitKey,l);let r=new Map,o=new Map;for(let[l,u]of t){let f=u.members.flatMap((h,E)=>Ad(e,u,h,E,e.container.placementKey)),m=f.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>kS(l,h,u.independent)),d=f.length>0?f:[{sourceMember:{key:`source:${l}:empty`,kind:e.container.kind==="starter-placeholder"?"starter-placeholder":"null-return",containerKey:e.container.placementKey,label:"empty-page",sourceFile:e.entryFile,isAtomic:!0},member:null}];r.set(l,d.map(({sourceMember:h})=>h)),o.set(l,m);let g=d[0]?.sourceMember.key??l;n.push({key:l,containerKey:g,businessMemberKeys:m.map(h=>h.key),isMultiMember:u.memberCount>1})}let i=[...r.values()].flat(),s=[...o.values()].flat(),a=i[0]?.key??null,c=e.placements.map(l=>({kind:"page-composition",placementKey:l.placementKey,documentVersion:e.documentVersion,composition:e.composition,placementUnitKey:l.placementUnitKey,relation:l.relation}));return{status:"supported",version:e.version,composition:e.composition,container:IS(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function vS(e){let t=e.diagnostics.map(CS);return{status:"unsupported",version:e.version,composition:e.composition,reason:RS(e.diagnostics),diagnostics:t}}function IS(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 Ad(e,t,n,r,o){let i=`source:${t.placementUnitKey}:${r}:${n.memberKey}`;return[{sourceMember:{key:i,kind:n.kind==="jsx-element"?"jsx-element":"jsx-expression",containerKey:o,label:n.label,sourceFile:e.entryFile,isAtomic:n.kind!=="jsx-element"},member:n},...n.children.flatMap((a,c)=>Ad(e,t,a,c,i))]}function kS(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function CS(e){return{code:wS(e),message:e.message}}function RS(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 wS(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 NS(e){let t=null;return SS(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=PS(o.path);i&&(t=i,n.stop())}}),t}function PS(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 AS(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Fr(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Be("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:Be("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Be("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(!TS(s))return{ok:!1,diagnostic:Be("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Td(s)||Fd(s))return{ok:!1,diagnostic:Be("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=Fr(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Be("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function TS(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(Td(o)||Fd(o))return null;return r}function Td(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function Fd(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function FS(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=Fr(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 _S(e){return e.isConditionalExpression()?Cd(Fr(e.get("consequent")))&&Cd(Fr(e.get("alternate"))):!1}function Cd(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Fr(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 OS(e,t){if(e.isIdentifier())return Rd(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Rd(n.node.name,t)}return!1}function Rd(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 MS(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&ga(t)}function ga(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(!ga(t))return!1;continue}if(t.isJSXElement()&&!ga(t))return!1}return!0}function DS(e){let t=e;if(e.isJSXFragment()||Oe(e)){let r=Tr(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&en(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&en(t);){let r=Tr(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!en(o))return{ok:!0,path:t};if(Tr(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function Tr(e){let t=[];for(let n of e.get("children"))if(!Array.isArray(n)){if(n.isJSXText()){n.node.value.trim()&&t.push(n);continue}if(n.isJSXExpressionContainer()){let r=n.get("expression");!r.isJSXEmptyExpression()&&!r.isNullLiteral()&&t.push(n);continue}if(n.isJSXFragment()){t.push(...Tr(n));continue}n.isJSXElement()&&(Oe(n)?t.push(...Tr(n)):t.push(n))}return t}function Wn(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:ya(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:mt(r.node.loc),businessMemberCount:0,parentSourceRange:mt(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=Wn(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=en(o)?Wn(o):null;n||=i?.unsupported??!1,t.push({...ha(o,i?.members),sourceRange:mt(r.node.loc),parentSourceRange:mt(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:ya(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:mt(r.node.loc),businessMemberCount:1,parentSourceRange:mt(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Oe(r)){let o=Wn(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=en(r)?Wn(r):null;n||=o?.unsupported??!1,t.push({...ha(r,o?.members),parentSourceRange:mt(e.node.loc)})}}return{members:t,unsupported:n}}function ha(e,t){let n=e.isJSXElement()&&en(e)?t??Wn(e).members:[],r=e.isJSXElement()&&!en(e)&&!Oe(e);return{memberKey:ya(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:mt(e.node.loc),businessMemberCount:r?1:_d(n),parentSourceRange:mt(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:LS(e)}}function en(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function LS(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 _d(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function ai(e){return e.length===0?0:Math.max(1,_d(e))}function wd(e){let t=mt(e.containerPath.node.loc),n=ba(e.source,e.containerPath.node.start,e.containerPath.node.end),r=gt(e.input,e.containerKind,e.sourceKind,t),o=gt(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:ai(e.members)<=1,memberCount:ai(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function BS(e){let t=mt(e.expression.node.loc),n=ba(e.source,e.expression.node.start,e.expression.node.end),r=gt(e.input,"virtual-route-root","atomic-expression",t),o=gt(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:gt(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 Od(e,t){let n=mt(t.node.loc),r=ba(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function fa(e,t,n,r,o){let i=Od(e,o);if(!i)return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=jS(e,n,s),c=oa(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Dd(t),container:{kind:r.kind,placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,version:e.version,isEmptyPage:n.memberCount===0,sourceKind:r.sourceKind,sourceRange:s,sourceHash:n.sourceHash},placements:a,diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:i};return Object.defineProperties(l,{placementByKey:{value:c.placementByKey,enumerable:!1},unitByKey:{value:c.unitByKey,enumerable:!1},placementsByUnitKey:{value:c.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:c.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:l}}function jS(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,f,m,d,g,h=n)=>({...t,placementKey:u,placementUnitKey:f,containerKey:t.placementKey,independent:ai(g)<=1,memberCount:ai(g),sourceRange:m,sourceHash:m?ma(e.source,m):null,relation:l,containerSourceRange:h,containerSourceHash:h?ma(e.source,h):null,anchorSourceRange:d,anchorSourceHash:d?ma(e.source,d):null,members:g}),i=t.placementKey,s=t.members.map(l=>gt(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",gt(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,f=gt(e,i,"placement-unit",l.sourceRange);r.push(o("before",gt(e,f,"before",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",gt(e,f,"after",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function pa(e,t,n,r){let o=Od(e,r);if(!o)return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=gt(e,n,"empty-container",void 0),s=gt(e,n,"empty-unit",void 0),a={placementKey:i,placementUnitKey:s,version:e.version,containerKey:i,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},c=oa([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Dd(t),container:{kind:n,placementKey:i,placementUnitKey:s,version:e.version,isEmptyPage:!0,sourceKind:n==="starter-placeholder"?"starter-placeholder":"jsx-fragment",sourceRange:null,sourceHash:null},placements:[a],diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:o};return Object.defineProperties(l,{placementByKey:{value:c.placementByKey,enumerable:!1},unitByKey:{value:c.unitByKey,enumerable:!1},placementsByUnitKey:{value:c.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:c.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:l}}function St(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 Be(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function gt(e,t,n,r){return Md([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function ya(e,t,n){return Md(["member",e,String(t??-1),String(n??-1)])}function Md(e){return`pc_${xa("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function ba(e,t,n){return t==null||n==null?null:`sha256:${xa("sha256").update(e.slice(t,n)).digest("hex")}`}function ma(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:${xa("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function mt(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Dd(e){if(e.isFunctionDeclaration())return e.node.id?.name??null;let t=e.parentPath;return t?.isVariableDeclarator()&&t.node.id.type==="Identifier"?t.node.id.name:null}import{PageTemplateIdSchema as tE}from"@vcp-dev/contracts";import BA from"node:fs";import $A from"node:path";var VS=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/,US=/^\[[^\]]+\]$/,KS=/^\[\.\.\.[^\]]+\]$/,JS=/^\[\[\.\.\.[^\]]+\]\]$/;function _r(e){let t=e.map(r=>eE(r.path)),n=zS(t);return n?t.filter(r=>WS(n,r)).map(r=>({routeId:GS(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function XS(e){return e.split("/").filter(Boolean).some(t=>US.test(t)||KS.test(t)||JS.test(t))}function Ld(e){return XS(ci(e))}function ci(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=qS(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function zS(e){return e.some(r=>r.startsWith("app/")&&!HS(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function HS(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function WS(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return VS.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function GS(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(ZS).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function YS(e){return e.startsWith("(")&&e.endsWith(")")}function ZS(e){return!e||e.startsWith("@")||e.startsWith("_")||YS(e)?null:QS(e)}function QS(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function qS(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function eE(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Or=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function Ze(e,t={}){throw new Or("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Sa(e){return tE.safeParse(e).success||Ze("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function Bd(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||Ze("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return Ze("invalid-template-key",{path:e})}return Sa(t)!==e&&Ze("noncanonical-template-key",{path:e}),t}function nE(e){let t=ci(e),n=t.slice(1).split("/");return(!e.startsWith("/")||/[?#\\%\u0000-\u001f]/.test(e)||t.startsWith("/.vcp")||Ld(t)||t!=="/"&&n.some(r=>!r||r==="."||r===".."||r.startsWith("@")||r.startsWith("_")||r.startsWith("(")))&&Ze("invalid-public-route",{routeId:e}),t}function jd(e,t,n="app"){n!=="app"&&n!=="src/app"&&Ze("invalid-app-root");let r=nE(e),o=Sa(t),i=`${n}/.vcp/page-templates${r==="/"?"":r}`,s=`${i}/${o}/page.tsx`;return(Buffer.byteLength(s,"utf8")>4095||s.split("/").some(a=>Buffer.byteLength(a,"utf8")>255))&&Ze("path-too-long",{path:s}),{appRoot:n,routeRoot:i,templateKey:o,templateEntryFile:s}}function $d(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function Vd(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===".")&&Ze("invalid-file-path",{path:i}),n.has(i)&&Ze("duplicate-file-path",{path:i}),n.set(i,o)}return n}function ui(e){let t=Vd(e.files),n=_r([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Or("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(!$d(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||Ze("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=Bd(c.pop()),u=c.length?`/${c.join("/")}`:"/";jd(u,l,a).templateEntryFile!==i&&Ze("candidate-path-mismatch",{path:i,routeId:u});let m=r.get(u);(!m||!m.startsWith(`${a}/`))&&Ze("canonical-entry-missing",{path:i,routeId:u}),o.push({routeId:u,templateId:l,entryFile:i,canonicalEntryFile:m,appRoot:a})}return o.sort((i,s)=>li(i.routeId,s.routeId)||li(i.templateId,s.templateId))}function Ud(e){let t=Vd(e.files),n=ui({files:t}),r=_r([...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)=>li(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:li(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function rE(e){let t=ci(e.selector.routeId),n=Ud({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&Ze("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||Ze("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function li(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as yE}from"@vcp-dev/contracts";import{parse as VT}from"@babel/parser";import{parse as GA}from"@babel/parser";import{FormBlockIdSchema as ZA,FormSpecV1Schema as QA}from"@vcp-dev/contracts";var Mr="components/site/generated/forms",qA=`${Mr}/vcp-form-runtime.tsx`,di="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",eT=new RegExp(`^${Mr}/form-(${di})\\.spec\\.ts$`),tT=new RegExp(`^${Mr}/form-(${di})\\.tsx$`),nT=new RegExp(`^@/${Mr}/form-(${di})$`),rT=new RegExp(`(?:^|/)${Mr}/form-(${di})(?:\\.tsx?)?$`);var oT=Symbol("invalid-literal");import{createHash as aT}from"node:crypto";import{posix as lT}from"node:path";import{parse as dT}from"@babel/parser";import{FormSpecV1Schema as pT}from"@vcp-dev/contracts";var mT=Symbol("dynamic");import{parse as oE}from"@babel/parser";function fi(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var iE=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function sE(e){let t=iE.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 aE(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Kd(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function cE(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Ea(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(Ea);if(t?.type==="ObjectExpression"){let n={};for(let r of fi(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=Kd(r.key);if(!o)throw new Error("unsupported object key");n[o]=Ea(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function va(e,t){let n=[],r=sE(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=oE(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(l){return n.push({code:"page-seo.parse-failed",message:l instanceof Error?l.message:String(l)}),{found:!1,seo:null,diagnostics:n}}let i;for(let l of fi(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let f of fi(u.declarations)){let m=f.id;m?.type==="Identifier"&&m.name==="PAGE_SEO"&&(i=f.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=cE(i);if(!s)return{found:!1,seo:null,diagnostics:n};if(s.type!=="ObjectExpression")return n.push({code:"page-seo.dynamic-declaration",message:"PAGE_SEO is not a static object literal"}),{found:!1,seo:null,diagnostics:n};let a={};for(let l of fi(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Kd(l.key);if(!(u!=="path"&&u!=="title"&&u!=="description"&&u!=="keywords"&&u!=="meta_tags_json"&&u!=="schema_json"&&u!=="breadcrumbs_json")){if(u==="path"||u==="title"||u==="description"||u==="keywords"){let f=aE(l.value);if(f===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static string; skipped`});continue}a[u]=f;continue}try{let f=Ea(l.value);u==="meta_tags_json"&&f!==null&&typeof f=="object"&&!Array.isArray(f)?a.meta_tags_json=f:u==="schema_json"&&f!==null&&typeof f=="object"?a.schema_json=f:u==="breadcrumbs_json"&&Array.isArray(f)?a.breadcrumbs_json=f:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} has unsupported static shape; skipped`})}catch(f){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static JSON-like value; skipped: ${f instanceof Error?f.message:String(f)}`})}}}let c=r;return a.path!==void 0&&(a.path!==r&&n.push({code:"page-seo.path-mismatch",message:`PAGE_SEO.path "${a.path}" != derived "${r}"; using PAGE_SEO.path`}),c=a.path),{found:!0,seo:{path:c,...a.title!==void 0?{title:a.title}:{},...a.description!==void 0?{description:a.description}:{},...a.keywords!==void 0?{keywords:a.keywords}:{},...a.meta_tags_json!==void 0?{meta_tags_json:a.meta_tags_json}:{},...a.schema_json!==void 0?{schema_json:a.schema_json}:{},...a.breadcrumbs_json!==void 0?{breadcrumbs_json:a.breadcrumbs_json}:{}},diagnostics:n}}import{parse as lE}from"@babel/parser";var Jd=["page","anchor","external","email","phone","group","file"],uE=["link","cta"],zd=["description","badge","iconKey"],Ia=["label","targetType","href","role","openInNewTab","nofollow","children",...zd],dE=new Set(Ia);function Lr(e){return Array.isArray(e)?e:[]}function Dr(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function fE(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Xd(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function ka(e){let t=[],n;try{n=lE(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 Lr(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of Lr(s.declarations)){let c=a.id;c?.type==="Identifier"&&c.name==="NAV_ITEMS"&&(r=a.init)}}for(;r&&(r.type==="TSAsExpression"||r.type==="TSSatisfiesExpression"||r.type==="TSInstantiationExpression");)r=r.expression;if(!r||r.type!=="ArrayExpression")return{items:[],diagnostics:[{severity:"fatal",path:"NAV_ITEMS",message:"missing top-level NAV_ITEMS array literal"}]};let o=[];return Lr(r.elements).forEach((i,s)=>{let a=Hd(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function Hd(e,t,n){if(e?.type!=="ObjectExpression")return n.push({severity:"fatal",path:t,message:"nav item must be an object literal"}),null;let r={};for(let l of Lr(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=fE(l.key);u&&(r[u]=l.value)}let o=Dr(r.label),i=Dr(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!Jd.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${Jd.join("/")}`}),null;r.group!==void 0&&n.push({severity:"warning",code:"leaf-group-field",path:`${t}.group`,message:'unsupported leaf group field ignored; use a canonical targetType: "group" node with children'});let s={label:o,targetType:i};for(let l of zd){if(r[l]===void 0)continue;let u=Dr(r[l]);u!==void 0?s[l]=u:n.push({severity:"warning",path:`${t}.${l}`,message:`${l} ignored: not a static string`})}r.icon!==void 0&&n.push({severity:"warning",path:`${t}.icon`,message:"icon component ref ignored; use static iconKey"});for(let l of Object.keys(r))dE.has(l)||l==="group"||l==="icon"||n.push({severity:"warning",code:"unknown-field",path:`${t}.${l}`,message:`unsupported field \`${l}\` ignored; NAV_ITEMS only carries ${Ia.join("/")}`});if(r.children!==void 0){if(r.children.type!=="ArrayExpression")return n.push({severity:"fatal",path:`${t}.children`,message:"children must be a static array"}),null;let l=[];Lr(r.children.elements).forEach((u,f)=>{let m=Hd(u,`${t}.children[${f}]`,n);m&&l.push(m)}),s.children=l}if(i==="group")return s.children?s:(n.push({severity:"fatal",path:`${t}.children`,message:"group item requires children"}),null);let a=Dr(r.href);if(!a)return n.push({severity:"fatal",path:`${t}.href`,message:"href must be a static string for non-group item"}),null;s.href=a;let c=Dr(r.role);if(c!==void 0&&(uE.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Xd(r.openInNewTab);l!==void 0?s.openInNewTab=l:n.push({severity:"warning",path:`${t}.openInNewTab`,message:"openInNewTab ignored: not a static boolean"})}if(r.nofollow!==void 0){let l=Xd(r.nofollow);l!==void 0?s.nofollow=l:n.push({severity:"warning",path:`${t}.nofollow`,message:"nofollow ignored: not a static boolean"})}return s}import{parse as pE}from"@babel/parser";function Br(e){return Array.isArray(e)?e:[]}function Wd(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function mE(e){let t;try{t=pE(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of Br(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of Br(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=Wd(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 Ca(e,t){let n=Gd(t);if(!n)return{status:"unsupported",source:e};let r=mE(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(ka(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=Br(l.elements);for(let[f,m]of u.entries()){if(hE(m,n)){let g=u[f+1],h=u[f-1],E=m.start,S=m.end;if(typeof E!="number"||typeof S!="number")continue;if(g&&typeof g.start=="number")s.push({start:E,end:g.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:S});else{let v=/^\s*,/.exec(e.slice(S));s.push({start:E,end:v?S+v[0].length:S})}continue}let d=gE(m);d&&a(d)}};if(a(o),s.length===0)return{status:"not_found",source:e};let c=e;for(let l of s.sort((u,f)=>f.start-u.start))c=c.slice(0,l.start)+c.slice(l.end);return{status:"removed",source:c,removedCount:s.length}}function gE(e){if(e.type==="ObjectExpression")for(let t of Br(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return Wd(t.value)}}function Gd(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function hE(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Br(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"&&Gd(n??"")===t}import{estimateNavLabelWidth as kT}from"@vcp-dev/contracts";import{parse as wT}from"@babel/parser";var xE="components/site/generated/",jr=[".tsx",".ts",".jsx",".js"];function Yd(e){if(e.expectedUrlPath===yE)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(_r(Object.keys(e.files).map(m=>({path:m}))).map(m=>m.entryFile)),n=Object.entries(e.files).filter(([m,d])=>{let g=m.replace(/\\/g,"/");if(!t.has(g))return!1;let h=va(d,g);return h.found&&h.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];try{if(ui({files:new Map(Object.entries(e.files))}).some(d=>d.canonicalEntryFile===r))return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:"Clean up page template candidates before deleting their canonical page."}}catch(m){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:m instanceof Error?m.message:"Invalid page template source."}}let o=bE(e.files);if(!o.ok)return o.error;let i=o.graph,s=IE(r,i),a=kE(r,s,i),c=[...s].filter(m=>!a.has(m)).sort((m,d)=>m.localeCompare(d)),l=[{operation:"delete",file:r},...[...a].sort((m,d)=>m.localeCompare(d)).map(m=>({operation:"delete",file:m}))],u=[],f=[];for(let[m,d]of Object.entries(e.files))if(m!==r){if(d.includes("NAV_ITEMS")){let g=Ca(d,e.expectedUrlPath);g.status==="removed"?(l.push({operation:"upsert",file:m,content:g.source}),u.push(m)):g.status==="unsupported"&&f.push(`unsupported_navigation:${m}`)}d.includes(e.expectedUrlPath)&&!d.includes("NAV_ITEMS")&&f.push(`preserved_link:${m}`)}return{ok:!0,edits:l,deletedFiles:[r,...[...a].sort((m,d)=>m.localeCompare(d))],updatedFiles:u,preservedSharedFiles:c,warnings:f}}function bE(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")||!SE(r))continue;let s=kr(r,o);if(!s.ok)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} (parse-failed).`}};let a=new Set;for(let{specifier:c}of s.module.imports){if(EE(c))continue;let l=Ir(r,c),u=vE(l,t);if(!u)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${c} (import-not-found).`}};a.add(u)}n.set(r,a)}return{ok:!0,graph:n}}function SE(e){let t=e.toLowerCase();return jr.some(n=>t.endsWith(n))}function EE(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!jr.some(n=>e.endsWith(n)))}function vE(e,t){let n=e.replace(/\\/g,"/");return(jr.some(o=>n.endsWith(o))?[n]:[...jr.map(o=>`${n}${o}`),...jr.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function IE(e,t){let n=new Set,r=[...t.get(e)??[]];for(;r.length>0;){let o=r.pop();!o.startsWith(xE)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function kE(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,c])=>a!==e&&!r.has(a)&&c.has(i))&&(r.delete(i),o=!0)}return r}import*as Gf from"@babel/parser";import*as le from"@babel/types";import*as Ai from"node:path";import*as ge from"@babel/types";function Zd(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 Ft(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return vn(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(ge.isObjectPattern(n)||ge.isArrayPattern(n))return vn(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(RE(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function vn(e,t,n=!1){return ge.isIdentifier(e)?e.name===t&&n:ge.isObjectPattern(e)?e.properties.some(r=>ge.isObjectProperty(r)?vn(r.value,t,n):vn(r.argument,t,n)):ge.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=ge.isRestElement(r)?r.argument:r;return vn(o,t,n)}):ge.isAssignmentPattern(e)?vn(e.left,t,!0):ge.isRestElement(e)?vn(e.argument,t,n):!1}function Gn(e,t){if(e.path.isObjectPattern()){if(t){let r=Et(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Ft(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Ft(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Qd(r),i=!1,s=o?o.initBinding&&Ra(o.initBinding)?(i=Ft(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=Gn(o.initBinding,{kind:"identifier",expression:o.initBinding.identifier.name,base:o.initBinding.identifier.name,path:[]});return i=c?.hasDefault??!1,c?[{kind:"property",name:c.propName},...c.remainingPath,...o.initPathPrefix]:null})():null:null,a=Et(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...u]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||Ft(e)}}}}let n=PE(e);if(n){let r=CE(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||Ft(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=wE(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Ft(e)}}let i=$r(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Ft(e)}:null}if(Ra(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Ft(e)}}return null}function CE(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=Qd(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Ra(i)?(a=Ft(i),[...s]):(()=>{let u=Gn(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=u?.hasDefault??!1,u?[{kind:"property",name:u.propName},...u.remainingPath,...s]:null})();if(!c)return null;let l=Et(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Ft(t)}:null}function Qd(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=AE(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Ra(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function RE(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function wE(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=Et(i.node,t);if(a)return a}return null}function qd(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=pi(a,e.identifier.name);if(c&&(!n||c.propName===n))return{propName:c.propName,componentName:t,expressionPath:c.expressionPath,displayPath:`${t}.${c.propName}.default`}}}if(e.path.isObjectPattern())for(let a of e.path.get("properties")){if(!a.isObjectProperty())continue;let c=$r(a.node);if(!c||n&&c!==n)continue;let l=a.get("value");if(!l.isAssignmentPattern())continue;let u=l.get("right");if(u.isExpression())return{propName:c,componentName:t,expressionPath:u,displayPath:`${t}.${c}.default`}}let r=NE(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=$r(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 pi(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=$r(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&Et(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=pi(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=pi(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=pi(r,t);if(o)return o}}return null}function Et(e,t,n=[]){if(ge.isIdentifier(e))return e.name===t?n:null;if(ge.isObjectPattern(e)){for(let r of e.properties)if(ge.isObjectProperty(r)){let o=$r(r);if(!o)continue;let i=Et(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(ge.isRestElement(r)){let o=Et(r.argument,t,n);if(o)return o}}if(ge.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=ge.isRestElement(o)?o.argument:o,s=Et(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return ge.isAssignmentPattern(e)?Et(e.left,t,n):null}function NE(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function PE(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 $r(e){return e.computed?null:ge.isIdentifier(e.key)?e.key.name:ge.isStringLiteral(e.key)?e.key.value:null}function AE(e){let t=[],n=e;for(;ge.isMemberExpression(n);){if(n.computed)if(ge.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ge.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ge.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ge.isIdentifier(n)?{base:n.name,path:t}:null}import*as of from"@babel/parser";import Pa from"@babel/traverse";import*as Yn from"@babel/types";import*as oe from"@babel/types";function hi(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?mi(n,t):null}if(e.isMemberExpression()){let n=DE(e.node),r=TE(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?mi(o,[...r,...t]):null}return e.isAwaitExpression()||Na(e.node)?tn(BE(e.node),t,"awaited or fetched expression"):null}function TE(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 mi(e,t=[]){let n=FE(e,t);if(n)return n;let r=_E(e,t);if(r)return r;let o=OE(e,t);return o||null}function Ur(e){return e?.kind==="api-source"}function FE(e,t){if(e.path.isVariableDeclarator()&&oe.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&wa(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return tn(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(c=>oe.isObjectProperty(c)&&nf(c)==="data"&&Vr(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&wa(a.node))return tn(e.identifier.name,t,"query hook data binding")}let n=ME(e);if(!n||nf(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()||!wa(i.node)?null:tn(e.identifier.name,t,"query hook data binding")}function _E(e,t){if(e.path.isVariableDeclarator()&&oe.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!tf(a.node))return null;let[c,l]=e.path.node.id.elements;return!oe.isIdentifier(c)||c.name!==e.identifier.name||!oe.isIdentifier(l)?null:ef(e,l.name)?tn(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let n=e.path.parentPath;if(!n?.isArrayPattern())return null;let r=n.parentPath;if(!r?.isVariableDeclarator())return null;let o=r.get("init");if(!o?.isCallExpression()||!tf(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return oe.isIdentifier(s)&&ef(e,s.name)?tn(e.identifier.name,t,"state setter is updated by API data"):null}function OE(e,t){let n=e.path.isVariableDeclarator()?e.path:e.path.findParent(o=>o.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");return r?.isExpression()?r.isAwaitExpression()?tn(e.identifier.name,t,"awaited binding result"):Na(r.node)?tn(e.identifier.name,t,"fetch-backed binding result"):null:null}function ME(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 Vr(e,t){return oe.isIdentifier(e)?e.name===t:oe.isAssignmentPattern(e)?Vr(e.left,t):oe.isObjectPattern(e)?e.properties.some(n=>oe.isObjectProperty(n)?Vr(n.value,t):Vr(n.argument,t)):oe.isArrayPattern(e)?e.elements.some(n=>!!n&&Vr(oe.isRestElement(n)?n.argument:n,t)):!1}function ef(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Na(i.node)&&(n=!0),(LE(i.node.callee,t)||i.node.arguments.some(s=>oe.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function wa(e){let t=yi(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function tf(e){return yi(e.callee)==="useState"}function Na(e){return gi(e,t=>oe.isCallExpression(t)&&yi(t.callee)==="fetch")}function DE(e){let t=e;for(;oe.isMemberExpression(t);)t=t.object;return oe.isIdentifier(t)?t.name:null}function nf(e){return e.computed?null:oe.isIdentifier(e.key)?e.key.name:oe.isStringLiteral(e.key)?e.key.value:null}function yi(e){return oe.isIdentifier(e)?e.name:oe.isMemberExpression(e)&&oe.isIdentifier(e.property)?e.property.name:null}function LE(e,t){return gi(e,n=>oe.isIdentifier(n)&&n.name===t)}function gi(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)&&gi(i,t))return!0;continue}if(oe.isNode(o)&&gi(o,t))return!0}return!1}function BE(e){return oe.isIdentifier(e)?e.name:oe.isCallExpression(e)?yi(e.callee)??"api":oe.isAwaitExpression(e)?"awaited-api":"api"}function tn(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:jE(e,t),reason:n}}function jE(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var sf=typeof Pa=="function"?Pa:Pa.default;function af(e,t){let n=lf(e);if(!n)return{allowed:!0};let r=!1;return sf(n,{CallExpression(o){if(!uf(o.node,t.sourceRange)||!$E(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||Ur(hi(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function cf(e,t){let n=lf(e);if(!n)return{allowed:!0};let r=!1;return sf(n,{JSXExpressionContainer(o){uf(o.node,t.sourceRange)&&(Yn.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 lf(e){try{return of.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function $E(e){let t=e.callee;return Yn.isMemberExpression(t)&&Yn.isIdentifier(t.property)&&t.property.name==="map"}function uf(e,t){let n=e.loc;return n?rf({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&rf({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function rf(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 V from"@babel/types";import*as df from"@babel/parser";import Aa from"@babel/traverse";import*as Re from"@babel/types";import*as Zn from"node:path";var vt=typeof Aa=="function"?Aa:Aa.default;function Ue(e){try{return df.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Ta(e){return e.computed?Re.isStringLiteral(e.key)||Re.isNumericLiteral(e.key)?String(e.key.value):null:VE(e.key)}function VE(e){return Re.isIdentifier(e)?e.name:Re.isStringLiteral(e)||Re.isNumericLiteral(e)?String(e.value):null}function In(e){return Re.isParenthesizedExpression(e)||Re.isTSAsExpression(e)||Re.isTSSatisfiesExpression(e)||Re.isTSNonNullExpression(e)||Re.isTSTypeAssertion(e)?In(e.expression):Re.isExpression(e)?e:null}function Fa(e){if(Re.isIdentifier(e))return[e.name];if((Re.isMemberExpression(e)||Re.isOptionalMemberExpression(e))&&!e.computed&&Re.isIdentifier(e.property)){let t=In(e.object),n=t?Fa(t):null;return n?[...n,e.property.name]:null}return null}function kn(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?Zn.normalize(Zn.join(Zn.dirname(e),t)).replace(/\\/g,"/"):t}function tt(e,t){return xi(e)===xi(t)}function xi(e){let t=Qn(e);return t.endsWith("/index")?t.slice(0,-6):t}function Qn(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function mf(e,t,n){let r=xf(e,t);if(bf(e,r),Sf(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 vt(e,{JSXElement(s){kf(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:bi(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 gf(e,t){let n=new Map,r=i=>{let s=qn(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 UE(i,n))o=r(s)||o}return[...n.values()]}function UE(e,t){let n=[],r=KE(e,t);for(let o of e.ast.program.body){if(V.isExportDefaultDeclaration(o)&&V.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=Kr(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(V.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=kn(e.file,o.source.value);for(let s of o.specifiers){if(V.isExportNamespaceSpecifier(s)){let l=nn(s.exported);for(let u of t.values())tt(u.file,i)&&n.push({file:e.file,namespace:_a(l,u.namespace),exportName:u.exportName});continue}if(!V.isExportSpecifier(s))continue;let a=nn(s.local),c=[...t.values()].filter(l=>tt(l.file,i)&&Cn(l.namespace,a));if(c.length>0){let l=nn(s.exported);for(let u of c){let f=Kr(u.namespace,a,l);f&&n.push({file:e.file,namespace:f,exportName:u.exportName})}continue}t.has(qn({file:i,exportName:a}))&&n.push({file:e.file,exportName:nn(s.exported)})}continue}if(V.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!V.isExportSpecifier(i))continue;let s=nn(i.local),a=r.get(s)??[];if(a.length>0){let c=nn(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=Kr(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(V.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=kn(e.file,o.source.value),s=o.exported;if(s){let a=nn(s);for(let c of t.values())tt(c.file,i)&&n.push({file:e.file,namespace:_a(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())tt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function _a(e,t){return t?`${e}.${t}`:e}function Cn(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Kr(e,t,n){return!Cn(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function KE(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(!V.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=kn(e.file,i.source.value);for(let a of i.specifiers){if(V.isImportDefaultSpecifier(a)){let c=t.get(qn({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>tt(u.file,s)&&Cn(u.namespace,"default"));for(let u of l){let f=Kr(u.namespace,"default",a.local.name);f&&r(a.local.name,{...u,namespace:f})}continue}if(V.isImportSpecifier(a)){let c=nn(a.imported),l=[...t.values()].filter(f=>tt(f.file,s)&&Cn(f.namespace,c));for(let f of l)r(a.local.name,f);let u=t.get(qn({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(V.isImportNamespaceSpecifier(a))for(let c of t.values())tt(c.file,s)&&r(a.local.name,{...c,namespace:_a(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(V.isVariableDeclaration(i))for(let s of i.declarations){if(!V.isIdentifier(s.id)||!s.init)continue;let a=In(s.init);if(!a||!V.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],u=new Set(l.map(qn));for(let f of c){let m=Kr(f.namespace,a.name,s.id.name),d=m?{...f,namespace:m}:f,g=qn(d);u.has(g)||(r(s.id.name,d),u.add(g),o=!0)}}}return n}function qn(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${xi(e.file)}#${t}`}function nn(e){return V.isIdentifier(e)?e.name:e.value}function hf(e,t){for(let n of e.program.body){if(V.isExportDefaultDeclaration(n)){let o=n.declaration;if((V.isFunctionDeclaration(o)||V.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(V.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!V.isExportNamedDeclaration(n))continue;let r=n.declaration;if((V.isFunctionDeclaration(r)||V.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(V.isVariableDeclaration(r)){for(let o of r.declarations)if(V.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!V.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:V.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Ma(e){let t=JE(e),n=[],r=Sf(e.ast,t);return vt(e.ast,{JSXElement(o){tt(e.file,e.sourceFile)&&bi(o)===e.sourceComponent||kf(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function yf(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function xf(e,t){let n=yf();return vt(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function JE(e){let t=yf();return tt(e.file,e.sourceFile)&&XE(t,xf(e.ast,e.sourceComponent)),vt(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=kn(e.file,o),s=e.componentIdentities.filter(a=>tt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(V.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),V.isImportDefaultSpecifier(a)){let l=s.filter(u=>Cn(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let f of l){let m=pf(f,"default");m&&u.add(m)}t.namespaceMembers.set(c,u)}continue}if(V.isImportSpecifier(a)){let l=V.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(f=>Cn(f.namespace,l));if(u.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let m of u){let d=pf(m,l);d&&f.add(d)}t.namespaceMembers.set(c,f);continue}s.some(f=>!f.namespace&&f.exportName===l)&&t.localBindings.add(c);continue}if(V.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,f=t.namespaceMembers.get(c)??new Set;f.add(u),t.namespaceMembers.set(c,f)}}}}}),bf(e.ast,t),t}function XE(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 bf(e,t){vt(e,{VariableDeclarator(n){if(!n.node.init)return;let r=In(n.node.init);if(r){if(V.isIdentifier(n.node.id)){let o=Rn(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Oa(t,i,o);return}if(V.isObjectPattern(n.node.id)){let o=Rn(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&If(n.node.id,o.namespaceMembers,t,n)}}}})}function Sf(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return vt(e,{ReferencedIdentifier(r){if(n){r.stop();return}zE(r)||!r.isIdentifier()||!Ef(r,t)||HE(r,t)||WE(r)||(n=!0,r.stop())}}),n}function zE(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 Ef(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)&&Rn(r.node,t,r)?r:null}function HE(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!ff(e,r))return!1;let o=Ef(e,t);if(!o)return!1;if(In(r.node)===o.node)return!!Rn(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&ff(e,a)&&!!Rn(a.node,t,a)}function WE(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function ff(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Rn(e,t,n){let r=In(e);if(!r)return null;if(V.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let c=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:c?{local:!1,namespaceMembers:new Set(c),unsupported:!1}:null}if(V.isObjectExpression(r))return GE(r,t,n);let o=Fa(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?vf(s,o.slice(1).join(".")):null}function GE(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!V.isObjectProperty(i))continue;let s=Ta(i);if(!s||!V.isExpression(i.value)){V.isExpression(i.value)&&(o||=Rn(i.value,t,n)!==null);continue}let a=Rn(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let c of a.namespaceMembers)r.add(`${s}.${c}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function vf(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 Oa(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 If(e,t,n,r){for(let o of e.properties){if(V.isRestElement(o)){if(V.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Oa(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!V.isObjectProperty(o))continue;let i=Ta(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=vf(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=V.isAssignmentPattern(o.value)?o.value.left:o.value;if(V.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Oa(n,c,s);continue}if(V.isObjectPattern(a)&&s.namespaceMembers.size>0){If(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function pf(e,t){if(!Cn(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 kf(e,t){let n=e.node.openingElement.name;if(V.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=Cf(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 Cf(e){if(V.isJSXIdentifier(e))return[e.name];if(V.isJSXMemberExpression(e)){let t=Cf(e.object);return t?[...t,e.property.name]:null}return null}function bi(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()&&V.isIdentifier(n.node.id))return n.node.id.name}return null}function Rf(e,t){let n=Ue(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Ma({ast:n,file:t.file,sourceFile:t.file,sourceComponent:t.tag,componentIdentities:[{file:t.importedFrom,exportName:t.exportName}]});return r.hasUnsafeReference?Number.POSITIVE_INFINITY:r.callSites.length}function Se(e){return e.structuralPath.includes("#repeat:")||e.isRepeatItemRoot||e.isRepeatRegion?{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange}:{kind:"jsx-node",strategy:"structural-path",file:e.file,component:e.component,structuralPath:e.structuralPath,expectedRange:e.sourceRange}}function de(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function _t(e,t){let n=de(e);return!!(n&&nt(t,n))}function nt(e,t){return t.start>=e.start&&t.end<=e.end}function Ot(e,t){let n=ie(e,Se(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Si(e,t)}function er(e,t){let n=de(t);return n?e.slice(n.start,n.end):""}function wf(e,t){return e.start===t.start&&e.end===t.end}function Si(e,t){let n=null;return vt(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 Ei(e,t){return Da(e,t).length>0}function vi(e,t){let n=de(e.node),r=de(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()&&!YE(o,n,r)))return!0;o=o.parentPath}return!1}function YE(e,t,n){let r=de(e.node.consequent);if(r&&nt(r,t)&&!nt(r,n))return!1;let o=e.node.alternate?de(e.node.alternate):null;return!(o&&nt(o,t)&&!nt(o,n))}function Da(e,t){let n=de(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=de(o.node.consequent),a=de(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()&&La(o.node.operator)){let s=de(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 La(e){return e==="&&"||e==="||"||e==="??"}function Nf(e,t){let n=de(e.consequent);if(n&&nt(n,t))return n;let r=de(e.alternate);return r&&nt(r,t)?r:null}function Pf(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=>Qn(a.file)));if(!t.has(Qn(e.sourceFile))||!t.has(Qn(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(Qn(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=hf(e.sourceAst,e.sourceComponent);if(!n)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without an exported source component identity"};let r=[];for(let a of e.knownSourceFiles){let c=Ue(a.content);if(!c)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because a loaded source file cannot be parsed"};r.push({file:a.file,ast:c})}let o=gf(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Ma({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(c.hasUnsafeReference)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the component has unsupported value usages"};i.push(...c.callSites)}if(i.length!==1)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without a single project-wide component call site"};let[s]=i;return!tt(s.file,e.targetFile)||bi(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 nv}from"@vcp-dev/contracts";function Ii(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 Jr();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return Jr();let u=ZE(a,l,o?.instanceCount);if(!u)return Jr();c=u}return{ok:!0,target:{kind:"value-binding",file:a.file,locator:c}}}return o?.instanceIndex!==void 0?n!=="selection"||!i?.ok?{ok:!1,code:"repeat-target-failed",reason:i&&!i.ok?i.reason:"No safe selected repeat property target is available"}:{ok:!0,target:{kind:"repeat-property",target:i}}:e.isRepeat&&n!=="template"||t.status==="direct"&&t.target?.kind!=="jsx-attribute"?Jr():{ok:!0,target:{kind:"jsx-attribute"}}}function Jr(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function ZE(e,t,n){if(!e.locator||!Number.isInteger(t)||t<0)return null;let r=e.collectionPathMap?.length??e.collectionIndexMap?.length;if(r!==void 0&&(t>=r||n!==void 0&&n!==r))return null;let o=e.collectionPathMap?.[t];if(o)return{...e.locator,path:o};let i=e.locator.path??[],s=i.findLastIndex(c=>c.kind==="index");if(s<0)return null;let a=i.map((c,l)=>l===s&&c.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:c);return{...e.locator,path:a}}import*as Mt from"@babel/types";import{SiteEditSetPropsParamsSchema as QE}from"@vcp-dev/contracts";function Af(e){let t=e.changes??(e.change?[e.change]:[]);if(!QE.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return Xr("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return Xr("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=ke(e.source,"value");if(!o.ok)return Xr("invalid-target","Repeat property source could not be parsed");let i=[{type:"set-property-binding",order:0,file:e.target.templateFile,locator:e.target.targetElementLocator,name:r.name,object:e.target.callbackItemName,property:r.name}];for(let[s,a]of e.target.parentObjectLocators.entries()){let c=ie(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return Xr("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?qE(r):ev(c.match.path.node,r.name);if(!l)return Xr("unsupported-property-value",`Repeat item ${s} has an unsupported value for '${r.name}'`);i.push({type:"upsert-object-property",order:i.length,file:e.target.sourceFile,locator:a,name:r.name,value:l})}return{ok:!0,steps:i}}function qE(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function ev(e,t){let n=e.properties.filter(i=>Mt.isObjectProperty(i)&&tv(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Mt.isExpression(r.value))return null;let o=At(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function tv(e){return Mt.isIdentifier(e)?e.name:Mt.isStringLiteral(e)?e.value:Mt.isNumericLiteral(e)?String(e.value):null}function Xr(e,t){return{ok:!1,errorCode:e,reason:t}}function Tf(e){if(e.change.name!=="className"&&e.change.name!=="class")return zr("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return zr("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return zr("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return zr("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 zr("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 zr(e,t){return{ok:!1,errorCode:e,reason:t}}async function _f(e){let t=nv.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return wn("invalid-change","Typed property changes are invalid");let n=[];for(let r of t.data.changes){let o=await rv(e,r);if(o){if(!o.ok)return wn("owner-plan-failed",o.reason);Ff(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return wn("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return wn("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(sv(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=Ii({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return wn(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){Ba(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=Af({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return wn("repeat-target-failed",l.reason);Ff(n,l.steps);continue}Ba(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:ov(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),iv(n)?wn("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function rv(e,t){return t.name!=="className"&&t.name!=="class"?null:Tf({node:e.node,change:t,classNameSource:e.classNameSource})}function ov(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 iv(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 Ff(e,t){for(let n of t)Ba(e,{...n,order:e.length})}function Ba(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 sv(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?ja(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function ja(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)=>ja(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=>ja(n[i],r[i]))}return!1}function wn(e,t){return{ok:!1,errorCode:e,reason:t}}import*as nr from"@babel/types";import*as X from"@babel/types";function $a(e,t,n){let r=Ot(t,n);return r?Dt(e,r):null}function Dt(e,t){let n=t.findParent(h=>h.isArrowFunctionExpression()||h.isFunctionExpression());if(!n||!n.isArrowFunctionExpression()&&!n.isFunctionExpression())return null;let r=n,o=r.parentPath;if(!o||!o.isCallExpression()&&!o.isOptionalCallExpression())return null;let i=o;if(i.node.arguments.findIndex(h=>h===r.node)!==0)return null;let a=i.get("callee");if(!a.isMemberExpression()&&!a.isOptionalMemberExpression())return null;let c=a.node,l=c.property;if(!X.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),f=er(e,u.node),m=r.node.params.map(h=>er(e,h)),d=de(i.node),g=de(r.node);return!f||m.some(h=>h.length===0)||!d||!g?null:{callStart:d.start,callEnd:d.end,callbackStart:g.start,callbackEnd:g.end,collectionExpression:f,callbackParams:m,mapOperator:X.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:ki(u.node),callbackPath:r,collectionPath:u}}function Hr(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function av(e,t){let n=de(e.node);return n?cv(t).some(r=>{let o=de(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function cv(e){let t=e.callbackPath.node.body;return X.isBlockStatement(t)?rn(t.body):on(t)}function rn(e){let t=[];for(let n of e){if(X.isReturnStatement(n)){n.argument&&t.push(...on(n.argument));continue}if(X.isBlockStatement(n)){t.push(...rn(n.body));continue}if(X.isIfStatement(n)){let r=X.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...rn(r)),n.alternate){let o=X.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...rn(o))}continue}if(X.isSwitchStatement(n)){for(let r of n.cases)t.push(...rn(r.consequent));continue}X.isTryStatement(n)&&(t.push(...rn(n.block.body)),n.handler&&t.push(...rn(n.handler.body.body)),n.finalizer&&t.push(...rn(n.finalizer.body)))}return t}function on(e){return X.isJSXElement(e)?lv(e)?Of(e.children):[e]:X.isJSXFragment(e)?Of(e.children):X.isParenthesizedExpression(e)||X.isTSAsExpression(e)||X.isTSSatisfiesExpression(e)||X.isTSNonNullExpression(e)||X.isTSTypeAssertion(e)?on(e.expression):X.isConditionalExpression(e)?[...on(e.consequent),...on(e.alternate)]:X.isLogicalExpression(e)&&La(e.operator)?on(e.right):[]}function Of(e){return e.flatMap(t=>X.isJSXElement(t)||X.isJSXFragment(t)?on(t):X.isJSXExpressionContainer(t)&&(X.isJSXElement(t.expression)||X.isJSXFragment(t.expression)||X.isConditionalExpression(t.expression)||X.isLogicalExpression(t.expression))?on(t.expression):[])}function lv(e){let t=e.openingElement.name;return X.isJSXIdentifier(t)?t.name==="Fragment":X.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Mf(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function ki(e){return!(X.isIdentifier(e)||X.isThisExpression(e)||X.isMemberExpression(e)||X.isOptionalMemberExpression(e)||X.isCallExpression(e)||X.isOptionalCallExpression(e))}function Df(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(X.isMemberExpression(n)||X.isOptionalMemberExpression(n))&&X.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function tr(e,t){let n=Ue(e);if(!n)return t.isRepeatItemRoot===!0;let r=ie(n,Se(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Si(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Dt(e,o);return i?av(o,i):t.isRepeatItemRoot===!0}function Lf(e,t){let n=Ue(e);if(!n)return!1;let r=ie(n,Se(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Si(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(X.isMemberExpression(s)||X.isOptionalMemberExpression(s))&&X.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as Ee from"@babel/types";function Va(e){if(Ee.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(Ee.isJSXMemberExpression(e)){let t=e;for(;Ee.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function uv(e,t){let n=de(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||_t(a.path.node,n)||sn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Va(i.node.name);s&&o(s,i)}}),[...r].sort()}function Ua(e,t,n){let r=Ue(e);if(!r)return{ok:!0};let o=ie(r,Se(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=ie(r,Se(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};if(Ei(o.match.path,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let s=uv(o.match.path,i.match.path);return s.length>0?{ok:!1,bindingNames:s}:{ok:!0}}function jf(e){let t=e;for(;Ee.isTSQualifiedName(t);)t=t.left;return Ee.isIdentifier(t)?t.name:null}function Wr(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Ci(e){let t=[],n=r=>{if(r){if(Ee.isIdentifier(r)){t.push(r.name);return}if(Ee.isObjectPattern(r)){for(let o of r.properties){if(Ee.isRestElement(o)){n(o.argument);continue}Ee.isObjectProperty(o)&&n(o.value)}return}if(Ee.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(Ee.isAssignmentPattern(r)){n(r.left);return}if(Ee.isRestElement(r)){n(r.argument);return}Ee.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Ka(e,t){let n=de(e.node),r=de(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=Bf(e),i=Bf(t);if(!o||!i||!wf(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=Nf(s.node,n);if(a&&!nt(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=de(s.node.right);if(a&&nt(a,n)&&!nt(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())&&Df(s)){let a=de(s.node.body)??de(s.node);if(a&&!nt(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 Bf(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?de(t.node.argument):null;if(t.isArrowFunctionExpression()&&(Ee.isJSXElement(t.node.body)||Ee.isJSXFragment(t.node.body)||Ee.isConditionalExpression(t.node.body)||Ee.isLogicalExpression(t.node.body)))return de(t.node.body);t=t.parentPath}return null}function sn(e,t,n){return n.scope.getBinding(t)===e}function Ja(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Ei(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=de(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>Ci(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);!u||_t(u.path.node,o)||i.has(u.path.node)||sn(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Va(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Xa(e,t,n){let r=de(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Ci(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return Wr(e,s=>{let a=s.scope.getBinding(s.node.name);!a||_t(a.path.node,r)||o.has(a.path.node)||sn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function $f(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Ci(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);!l||n.has(l.path.node)||sn(l,a,t)||r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(c){o(c.node.name,c)},TSTypeReference(c){let l=c.node.typeName;if(nr.isIdentifier(l))o(l.name,c);else{let u=jf(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function za(e,t){let n=de(e.node),r=new Set;return Wr(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&_t(i.path.node,n)||sn(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 Vf(e){let t=[];for(let n of e.callbackPath.node.params){if(nr.isIdentifier(n)){t.push(n.name);continue}if(nr.isRestElement(n)&&nr.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 Uf(e,t){return{...e,callbackParams:t}}function Ha(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function rr(e){return{file:e.file,component:e.component}}function dv(e){return e.target.kind==="node"?e.target.key:null}function fv(e){return"kind"in e}function Ri(e){return!fv(e)}function Qa(e,t){let n=Ai.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Ai.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Wa(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Nt(n,Se(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function ec(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 pv(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function mv(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 Ga(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function gv(e){let t=mf(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Ka(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=hv({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Yf(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?ki(o):!0}}}function hv(e){let t=de(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||_t(a.path.node,t))return;let c=bv(s,a,t);if(c){if(c.hasDefault){o="Cannot move prop-backed repeat child because the collection prop has a default value that cannot be preserved safely";return}let l=Ev(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=yv(l.expression,c.remainingPath);if(!u){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let f=za(l.expressionPath,e.targetParentPath);if(!f.ok){o=f.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${f.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:u});return}sn(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:vv(e.source,t,[...n.values()])}}function yv(e,t){if(t.length===0)return e;let n=Yf(e);if(!n)return null;let r=ki(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=xv(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function xv(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function bv(e,t,n){let r=Sv(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=Gn(t,o);if(!i)return null;let s=r?.range??de(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function Sv(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!_t(n.node,t)||n.node.computed||!le.isIdentifier(n.node.property))return null;let r=de(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Ev(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(c=>c.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let o=r.find(c=>c.isJSXAttribute()&&le.isJSXIdentifier(c.node.name)&&c.node.name.name===t);if(!o?.isJSXAttribute())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not passed explicitly`};let i=o.get("value");if(!i.isJSXExpressionContainer())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not an expression`};let s=i.get("expression");if(!s.isExpression())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not a usable expression`};let a=er(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 vv(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 Yf(e){try{let n=Gf.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=le.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&le.isExpression(r)?r:null}catch{return null}}function Iv(e){let t=de(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||_t(s.path.node,t))return;let a=Kf(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=Kf(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!kv(u.importSpec,a.importSpec))&&r.add(a.localName);return}let l=n.get(a.moduleSpecifier)??[];l.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||l.push(a.importSpec),n.set(a.moduleSpecifier,l);return}r.add(i.node.name)};return Wr(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 kv(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 Kf(e,t,n){let r=Cv(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=kn(t,i),a=i.startsWith(".")?Qa(n,s):i;if(r.isImportDefaultSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:c}}}if(r.isImportNamespaceSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:c}}}if(r.isImportSpecifier()){let c=le.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:c,local:l===c?void 0:l}}}return null}function Cv(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Jf(e,t,n,r){let o=Da(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=er(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=Rv(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${Nv(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function Rv(e,t){return wv(e.node)?t:`(${t})`}function wv(e){return le.isIdentifier(e)||le.isThisExpression(e)||le.isSuper(e)||le.isMemberExpression(e)||le.isOptionalMemberExpression(e)||le.isCallExpression(e)||le.isOptionalCallExpression(e)||le.isBooleanLiteral(e)||le.isNumericLiteral(e)||le.isStringLiteral(e)||le.isNullLiteral(e)||le.isUnaryExpression(e)}function Nv(e){return e.trim().startsWith("<")?e:`(${e})`}var Pv={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 wi(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=Pv[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 Av(e,t){for(let n of e.program.body){if(!le.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>le.isImportDefaultSpecifier(o));if(r&&le.isImportDefaultSpecifier(r))return r.local.name}return null}function Tv(e,t,n){for(let r of e.program.body){if(!le.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>le.isImportSpecifier(i)&&(le.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&le.isImportSpecifier(o))return o.local.name}return null}function Xf(e){let t=new Set;return vt(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function zf(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function Fv(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=ec(e),o=Ue(t);if(n.exportName!=="default"){let a=o?Tv(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?zf(r,Xf(o)):r;return{localName:c,importStep:Ya(e,c)}}if(!o)return{localName:r,importStep:Ya(e,r)};let i=Av(o,n.source);if(i)return{localName:i};let s=zf(r,Xf(o));return{localName:s,importStep:Ya(e,s)}}function _v(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??ec(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 Ov(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?Mv(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function Mv(e){return Object.fromEntries(Object.entries(e).filter(t=>qa(t[1])))}function qa(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(qa):typeof e=="object"?Object.values(e).every(qa):!1}function Ya(e,t=ec(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 Hf(e,t){if("kind"in e)return{parentNode:null,anchorNode:null,placement:e.relation};if("parentKey"in e)return{parentNode:t.getNode(e.parentKey),anchorNode:null,placement:e.relation};let n=t.getNode(e.anchorKey);return{parentNode:n?.parentKey?t.getNode(n.parentKey)??n:n,anchorNode:n,placement:e.relation}}function Dv(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Gr(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function tc(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Yr(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:tc(e,t.slice(0,n)),index:r.index}}return null}function Za(e,t){return e.locator?e.collectionPathMap?.[t]?tc(e.locator,e.collectionPathMap[t]):Yr(e.locator)?Bv(e.locator,jv(t,e.collectionIndexMap)):null:null}function Lv(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:Zf(o,t)}function Zf(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Zf(r,t);return o===void 0?void 0:{[n.name]:o}}function Ni(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 Bv(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},tc(e,i)}return null}function jv(e,t){return t?.[e]??e}function Wf(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 $v(e,t){return Vv(e.root,t.root)&&Kv(e.path??[],t.path??[])}function Vv(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&&Uv(e.sourceRange,t.sourceRange)}}function Uv(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function Kv(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 Pi=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:Gr(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:Gr(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:Gr(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:Gr(t.kind,t.params.kind)};let r=t;if(!Ri(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Hf(r.params.position,this.graph);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:Gr(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"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=dv(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):Jv(i)}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?_f({node:t.node,scope:t.scope,changes:t.changes,selectionRef:t.selectionRef,getPropertyState:n,getRepeatPropertyTarget:this.graph.getRepeatPropertyTarget,getFileContent:r=>this.graph.getFileContent(r),getFileVersion:r=>this.graph.getFileVersion(r),classNameSource:this.graph.getClassNameSource?.(t.node.key)??void 0}):{ok:!1,errorCode:"missing-property-state",reason:"Typed property planning requires authoritative property provenance"}}async buildStyleDraftPropertySteps(t){let{initialOrder:n,node:r,props:o,selectionRef:i}=t,s=[],a=[];for(let[c,l]of Object.entries(o)){if(l===void 0)continue;let u=await this.graph.getElementPropertyWriteTarget?.(r.key,c),f=r.attributes?.find(d=>d.name===c);if((await this.graph.getPropertyState?.(r.key,c,i))?.status==="blocked"||!u&&f?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${c}'`};if(!(typeof f?.resolvedValue=="string"&&f.resolvedValue===l||f?.source===null&&f.value===l)){if(u?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${c}'`};if(u?.kind==="value-binding"&&u.locator){let d=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let g=Za(u,i.instanceIndex);if(!g)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};d=g}s.push({order:n+s.length,file:u.file,type:"update-value",locator:d,value:l});continue}a.push({operation:"set",name:c,value:l})}}return a.length>0&&s.push({order:n+s.length,file:r.file,type:"set-property-changes",locator:Se(r),scope:"selection",changes:a}),{ok:!0,steps:s}}buildTextRewriteSteps(t,n,r,o,i){if(o?.kind==="value-binding"&&o.locator){if(o.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let a=Za(o,i.instanceIndex);if(!a)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the selected repeat item"};let c=this.coerceTextValueForValueTarget(o.file,a,r);return c.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-array-item",locator:a,value:c.value}]}:c}let s=this.coerceTextValueForValueTarget(o.file,o.locator,r);return s.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-value",locator:o.locator,value:s.value}]}:s}return{ok:!0,steps:o?.kind==="external-entry"?[{order:0,file:`external:${o.sourceId}`,type:"invoke-external-adapter",sourceType:o.sourceType,sourceId:o.sourceId,adapterId:o.adapterId,capability:"write-text",value:r}]:[{order:0,file:t.file,type:"update-text",locator:Se(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Ue(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=ie(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!pv(a.match.path))return{ok:!0,value:r};let c=mv(r);return c===null?{ok:!1,errorCode:"invalid-params",reason:`${o} value must be a valid number for numeric source`}:{ok:!0,value:c}}planUpdateArrayItem(t,n,r,o){if(!r.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update repeated text on this node"};if(o?.kind!=="value-binding"||o.sourceKind!=="repeat-template"||!o.locator)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item requires a writable repeat-template source"};let{index:i,value:s}=n.params,a=o.collectionPathMap?.length??o.collectionIndexMap?.length;if(a!==void 0&&i>=a)return{ok:!1,errorCode:"invalid-params",reason:`update-array-item index ${i} is outside the repeated source`};let c=Za(o,i);if(!c)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(o.file,c,s,"update-array-item");return l.ok?this.isValueTargetUnchanged(o.file,c,l.value)?{ok:!1,errorCode:"invalid-params",reason:"update-array-item value is unchanged"}:this.buildPlan(t,n,[{order:0,file:o.file,type:"update-array-item",locator:c,value:l.value}],r):l}isValueTargetUnchanged(t,n,r){let o=Ue(this.graph.getFileContent(t));if(!o)return!1;let i=ie(o,n);if(!i.ok)return!1;let s=i.match.path;if(s.isStringLiteral())return typeof r=="string"&&s.node.value===r;if(s.isNumericLiteral())return typeof r=="number"&&Object.is(s.node.value,r);if(s.isBooleanLiteral())return typeof r=="boolean"&&s.node.value===r;if(s.isNullLiteral())return r===null;if(s.isUnaryExpression({operator:"-"})){let a=s.get("argument");return typeof r=="number"&&!Array.isArray(a)&&a.isNumericLiteral()&&Object.is(-a.node.value,r)}return!1}planUpdateText(t,n,r,o,i){let s=this.graph.getTextProvenance?.(r.key,n.params.segmentIndex);if(s&&(s.editMode==="readonly"||s.editMode==="unsupported"))return{ok:!1,errorCode:"unsupported-operation",reason:"Text has no identity-preserving write target"};if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let a=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return a.ok?this.buildPlan(t,n,a.steps,o):a}async planRemoveNode(t,n,r,o){if(!o.canRemove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot remove this node"};let i=await this.graph.getTextWriteTarget(r.key,0);if(i?.kind==="external-entry")return this.buildPlan(t,n,[{order:0,file:`external:${i.sourceId}`,type:"invoke-external-adapter",sourceType:i.sourceType,sourceId:i.sourceId,adapterId:i.adapterId,capability:"remove-node",value:{operation:"remove-node"}}],o);if(r.isRepeatItemRoot){let f=i;if(f?.kind==="value-binding"&&f.locator){let m=Yr(f.locator);if(m)return this.buildPlan(t,n,[{order:0,file:f.file,type:"remove-bound-array-item",locator:m.locator,index:m.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=Ni(r,i,this.graph.getTextProvenance?.(r.key,0)??null);if(s)return{ok:!1,errorCode:"unsupported-operation",reason:s};let a=this.getRepeatBackedTemplateStructureReason(r);if(a)return{ok:!1,errorCode:"unsupported-operation",reason:a};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=[{order:0,file:r.file,type:"remove-node",locator:Se(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&l.push({...u,order:l.length}),this.buildPlan(t,n,l,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||Rf(n,t)>1)return null;let r=Qa(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(!Ri(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.node.kind==="component-call"&&!n.params.node.component)return{ok:!1,errorCode:"unsupported-operation",reason:"Materialized component insertion requires the materialization transaction planner"};if(!o.canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot insert child into this node"};let s=this.graph.getEditableTextSegmentIndex(r.key),a=s!==null?await this.graph.getTextWriteTarget(r.key,s):null,c=Ni(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let f=await this.planRepeatBackedInsertChild(t,n,r,o);if(f)return f;let m=this.getRepeatBackedTemplateStructureReason(r);if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let d=af(this.graph.getFileContent(r.file),r);if(!d.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:d.reason??"Cannot insert child into this node"};let g=wi(r,n.params.node);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let h=[],E=0,S=n.params.node.kind==="component-call"?Fv(n.params.node,this.graph.getFileContent(r.file)):void 0,v=S?.importStep;return v&&h.push({order:E++,file:r.file,type:"add-import",moduleSpecifier:v.moduleSpecifier,imports:v.imports}),h.push({order:E++,file:r.file,type:"insert-child",parentLocator:Se(r),node:{jsx:_v(n.params.node,S?.localName)},placement:n.params.position.relation,anchorLocator:i?Se(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Ri(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let a=s?.kind==="external-entry"?s:await this.findExternalInsertContext(r,i);if(!a)return null;let c=i?await this.graph.getTextWriteTarget(i.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${a.sourceId}`,type:"invoke-external-adapter",sourceType:a.sourceType,sourceId:a.sourceId,adapterId:a.adapterId,capability:"insert-child",value:{operation:"insert-child",relation:n.params.position.relation,parentKey:r.key,anchorSourceId:c?.kind==="external-entry"?c.sourceId:null,node:Ov(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(!Ri(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(f=>f.isRepeatItemRoot&&f.tag?.toLowerCase()===i.tag.toLowerCase());if(!s)return null;let a=await this.graph.getTextWriteTarget(s.key,0);if(!a||a.kind!=="value-binding"||!a.locator)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires a writable value target"};let c=Yr(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=Lv(a.locator,i.text);if(l===void 0)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child could not infer an item shape from the template"};let u=n.params.position.relation==="prepend"?Wf(0,a.collectionIndexMap):Wf(a.collectionIndexMap?.length??c.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:c.locator,index:u,value:l}],o)}async getUpstreamBackedDescendantReason(t){if(!this.graph.getChildNodes)return null;let n=[...this.graph.getChildNodes(t.key)];for(;n.length>0;){let r=n.shift();if(!r)continue;let o=this.graph.getEditableTextSegmentIndex(r.key),i=o!==null?await this.graph.getTextWriteTarget(r.key,o):null,s=Ni(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 tr(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:")||Lf(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&&tr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Ue(c);if(!l)return null;let u=Ot(l,r),f=Ot(l,o);if(!u||!f)return null;let m=Dt(c,u),d=Dt(c,f);if(!Hr(m,d))return null;if(a&&(s==="before"||s==="after")){let h=Ot(l,a),E=h?Dt(c,h):null;if(!Hr(m,E))return null}if(vi(u,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=Ua(c,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Se(r),targetParentLocator:Se(o),placement:s,anchorLocator:a?Se(a):void 0,selectionContext:rr(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&&tr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Ue(c);if(!l)return null;let u=Ot(l,r),f=Ot(l,o);if(!u||!f)return null;let m=Dt(c,u);if(!m)return null;let d=Dt(c,f);if(Hr(m,d))return null;if(d&&!Mf(d,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let C=$a(c,l,a);if(d&&!Hr(d,C)||!d&&C)return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"}}if(r.tag&&r.tag.toLowerCase()===r.tag){let C=wi(o,{kind:"native-tag",tag:r.tag});if(C)return{ok:!1,errorCode:"unsupported-operation",reason:C}}let g=Wa(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(vi(u,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=Jf(c,u,f,g);for(let C of h.conditionPaths){let w=Xa(C,f,m);if(!w.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${w.bindingNames.join(", ")}`}}let E=Ja(u,f,m,{preserveConditionalBoundary:h.conditionPaths.length>0});if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${E.bindingNames.join(", ")}`};let S=$f(m,f);if(!S.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${S.bindingNames.join(", ")}`};let v=m;if(r.component!==o.component){let C=gv({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:f});if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:C.reason};v=C.context}else{let C=za(m.collectionPath,f);if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:C.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${C.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:Se(r),targetParentLocator:Se(o),placement:s,anchorLocator:a?Se(a):void 0,repeatExpression:Ha(v,h.sourceJsx),selectionContext:rr(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&tr(this.graph.getFileContent(r.file),r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),u=Ue(c),f=Ue(l);if(!u||!f)return null;let m=Pf({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!m.ok)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason};let d=Ot(u,r),g=Ot(f,o);if(!d||!g)return null;let h=Ka(m.callSitePath,g);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let E=Dt(c,d);if(!E)return null;if(Dt(l,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&$a(l,f,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 _=wi(o,{kind:"native-tag",tag:r.tag});if(_)return{ok:!1,errorCode:"unsupported-operation",reason:_}}let v=Wa(this.graph,r);if(!v)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(vi(d,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let C=Jf(c,d,g,v);for(let _ of C.conditionPaths){let L=Xa(_,g,E);if(!L.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${L.bindingNames.join(", ")}`}}let w=Ja(d,g,E,{preserveConditionalBoundary:C.conditionPaths.length>0});if(!w.ok)return{ok:!1,errorCode:"unsupported-operation",reason:w.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${w.bindingNames.join(", ")}`};let A=Iv({sourceFile:r.file,targetFile:o.file,sourceContext:E,targetParentPath:g});if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason};let P=Vf(E);if(!P.ok)return{ok:!1,errorCode:"unsupported-operation",reason:P.reason};let k=Uf(E,P.callbackParams),T=[{order:0,file:r.file,type:"remove-node",locator:Se(r),removeWhitespace:!0}];for(let _ of A.imports)T.push({order:T.length,file:o.file,type:"add-import",moduleSpecifier:_.moduleSpecifier,imports:_.imports});return T.push({order:T.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:Se(o),expression:Ha(k,C.sourceJsx),placement:s,anchorLocator:a?Se(a):void 0,selectionContext:rr(o)}),this.buildPlan(t,n,T,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};let i=Hf(n.params.target,this.graph),s=i.parentNode;if(!s)return{ok:!1,errorCode:"locator-miss",reason:`Target parent for request '${n.id}' not found in graph`};if(Dv(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 a=await this.graph.getTextWriteTarget(r.key,0);if(a?.kind==="external-entry"){let S=n.params.target.relation,v=i.anchorNode&&(S==="before"||S==="after")?await this.graph.getTextWriteTarget(i.anchorNode.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:"move-node",value:{operation:"move-node",relation:S,anchorSourceId:v?.kind==="external-entry"?v.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let c=r.file!==s.file,l=n.params.target.relation,u=i.anchorNode,f=Ni(r,a,this.graph.getTextProvenance?.(r.key,0)??null);if(f&&!Ga(f))return{ok:!1,errorCode:"unsupported-operation",reason:f};if(r.isRepeatItemRoot&&u?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===u.repeatOwnerKey&&(l==="before"||l==="after")){let S=a,v=await this.graph.getTextWriteTarget(u.key,0);if(S?.kind==="value-binding"&&v?.kind==="value-binding"&&S.locator&&v.locator){let C=Yr(S.locator),w=Yr(v.locator);if(C&&w&&S.file===v.file&&$v(C.locator,w.locator)){let A=C.index,P=w.index,k=l==="before"?P-(A<P?1:0):P+(A<P?0:1);return this.buildPlan(t,n,[{order:0,file:S.file,type:"move-array-item",locator:C.locator,fromIndex:A,toIndex:k}],o)}}}if(r.isRepeatItemRoot&&tr(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),d=Ga(f)?f:m;if(d&&Ga(d)){let S=this.planRepeatTemplateInternalMove(t,n,r,s,o,l,u);if(S)return S;let v=this.planRepeatTemplateHoistMove(t,n,r,s,o,l,u);if(v)return v;let C=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,l,u);return C||{ok:!1,errorCode:"unsupported-operation",reason:d}}if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let g=await this.getUpstreamBackedDescendantReason(r);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};if(r.tag&&r.tag.toLowerCase()===r.tag){let S=wi(s,{kind:"native-tag",tag:r.tag});if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S}}if(c)return this.planCrossFileMove(t,n,r,s,o,l,u);let h=Ua(this.graph.getFileContent(r.file),r,s);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason??`Cannot move node because it depends on bindings outside the target scope: ${h.bindingNames.join(", ")}`};let E=[{order:0,file:r.file,type:"move-node",locator:Se(r),targetParentLocator:Se(s),placement:l,anchorLocator:u?Se(u):void 0,selectionContext:rr(s)}];return this.buildPlan(t,n,E,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),f=Wa(this.graph,r)??`<${r.component} />`,m=cf(u,r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:Se(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,E={moduleSpecifier:Qa(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:g}]:[{kind:"named",imported:r.exportName,local:g===r.exportName?void 0:g}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:E.moduleSpecifier,imports:E.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Se(o),node:{jsx:f},placement:s,anchorLocator:a?Se(a):void 0,selectionContext:rr(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Se(o),node:{jsx:f},placement:s,anchorLocator:a?Se(a):void 0,selectionContext:rr(o)});let d=this.buildRemoveComponentImportStep(r,u);return d&&c.push({...d,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:be(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 Jv(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 sc from"@babel/generator";import{parse as iI}from"@babel/parser";import ac from"@babel/traverse";import*as R from"@babel/types";import*as Bt from"@babel/types";import nc from"@babel/generator";import*as he from"@babel/types";var Xv=typeof nc=="function"?nc:nc.default,zv=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,Hv=/^((?:https?:)?\/\/)[^/@\s]+@/i,Wv=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function qf(e,t){let n=Lt(e.callee);if(!n)return null;if(n==="fetch")return rc(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Qf(r))return rc(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Qf(r))return rc(e.arguments[0],r,t,["ky client contract"])}return null}function rc(e,t,n,r){if(!e||he.isSpreadElement(e)||he.isJSXNamespacedName(e))return Qv(t,n,r,"missing url argument");let o=Zr(e);return{sourceKind:Zv(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 Zr(e){if(he.isStringLiteral(e))return Ti(e.value);if(he.isTemplateLiteral(e))return Ti(Gv(e));if(he.isBinaryExpression(e)&&e.operator==="+"){let t=Zr(e.left),n=Zr(e.right);return!t&&!n?void 0:Ti(`${t??oc(e.left)}${n??oc(e.right)}`)}if(he.isMemberExpression(e)){let t=ep(e);if(t)return`env:${t}`}if(!(he.isCallExpression(e)&&Lt(e.callee)==="new URL")){if(he.isNewExpression(e)&&he.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!he.isSpreadElement(t)?Zr(t):void 0,o=n&&!he.isSpreadElement(n)?Zr(n):void 0;return o&&r?Ti(`${o} + ${r}`):r??o}if(he.isIdentifier(e))return`:${e.name}`}}function Gv(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+=oc(r))}return t}function oc(e){if(he.isIdentifier(e))return`:${e.name}`;if(he.isMemberExpression(e)){let t=ep(e);if(t)return`env:${t}`}return`:${Yv(e)}`}function Yv(e){return Xv(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Ti(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(Hv,"$1<redacted>@").replace(Wv,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?zv.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function Zv(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 Qv(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function Qf(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function ep(e){return!he.isMemberExpression(e.object)||!he.isIdentifier(e.object.object,{name:"process"})||!qv(e.object.property,"env")?null:he.isIdentifier(e.property)?e.property.name:he.isStringLiteral(e.property)?e.property.value:null}function qv(e,t){return he.isIdentifier(e)&&e.name===t}function Lt(e){if(he.isIdentifier(e))return e.name;if(he.isMemberExpression(e)){let t=Lt(e.object),n=he.isIdentifier(e.property)?e.property.name:he.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var eI=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),tI=new Set(["getConfig","submit"]);function tp(e,t){let n=nI(Lt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!eI.has(i))return null;let s=ic(e,0),a=i==="getByUrl"||i==="getByUrlStrict",c=a?void 0:s,l=a?s??"/:record-url":c?`/collections/${c}`:"/collections/:collection";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:i,...c?{collection:c}:{},endpointPattern:l,confidence:s?"exact":"partial",evidence:[{file:t.file,symbol:n,reason:"VCP CMS collection facade"}]}}let o="cms.forms.";if(n.startsWith(o)){let i=n.slice(o.length);if(!tI.has(i))return null;let s=ic(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=ic(e,0)??rI(e,0,"path")??"/cms/:path",s=oI(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 nI(e,t){let n=e?.indexOf(".")??-1;if(!e||n<1)return e;let r=t.imports?.get(e.slice(0,n));return r?.importedName==="collections"&&/(?:^|\/)lib\/cms\/collections(?:\.js)?$/.test(r.source)?`cms.collections${e.slice(n)}`:e}function np(e,t){let n=Lt(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 rp(e){let t=Lt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function ic(e,t){let n=e.arguments[t];return Bt.isStringLiteral(n)?n.value:null}function rI(e,t,n){let r=e.arguments[t];if(!Bt.isObjectExpression(r))return null;for(let o of r.properties)if(Bt.isObjectProperty(o)&&!o.computed&&(Bt.isIdentifier(o.key)&&o.key.name===n||Bt.isStringLiteral(o.key)&&o.key.value===n)&&Bt.isStringLiteral(o.value))return o.value.value;return null}function oI(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}var lc=typeof ac=="function"?ac:ac.default,E_=typeof sc=="function"?sc:sc.default,sI={maxFunctionDepth:8,maxImportDepth:6},aI=new Set(["src","href","alt","poster","content","title","aria-label"]);async function lp(e){let t=e.fileCache??new Map,n=fc(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...sI,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:Ip(n,e.element.componentName)};await up(e.element.componentName,e.graph,r);let o=[];o.push(...await fI(e.element,e.graph,r),...await pI(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await mI(s,e.element,e.graph,r);a&&o.push(Oi(a,"text","children"))}for(let s of e.element.attributes??[]){let a=dI(s,e.element);if(!a)continue;let c=await pp(s.source,e.element,e.graph,r);c&&o.push(Oi(c,a,s.name))}let i=PI(o).sort(Ep);return{hasDynamicData:i.length>0,bindings:i}}async function up(e,t,n){if(n.importDepth>=n.options.maxImportDepth)return;let r=n.analysis.functions.get(e)??n.analysis.functions.get("default"),o=r?.params[0];if(!r||!o)return;let i=n.analysis.functions.get("default")===r?"default":e,s=[];for(let l of t.elements.values()){if(l.sourceFile===n.file&&l.tag===e){s.push(l);continue}!l.importedFrom||!l.exportName||l.importedFrom===n.file&&l.exportName!==i||(l.importedFrom===n.file||await dp(l.importedFrom,l.exportName,n.file,n))&&s.push(l)}if(s.length===0)return;let a=new Map;for(let l of s){let u=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let f=await fp(l.sourceFile,n);if(!f)continue;let m=Di(f,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=Ip(f,l.componentName),await up(l.componentName,t,m);let d=await cI(l,m);for(let[g,h]of d){if(!h)continue;let E=a.get(g)??[];E.push(h),a.set(g,E)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let f=bp(u);f.length===1&&c.set(l,f[0])}uI(o,c,n)}async function dp(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 fp(e,r))?.imports.get(t);if(!s||!Tt(s.source))return!1;let a=await Rp(e,s.source,r.exists);return a?a===n?!0:dp(a,s.importedName,n,r,o):!1}async function cI(e,t){let n=new Map;lc(t.analysis.ast,{JSXElement(o){if(lI(o.node,e.sourceRange)){for(let i of o.node.openingElement.attributes)!R.isJSXAttribute(i)||!R.isJSXIdentifier(i.name)||!R.isJSXExpressionContainer(i.value)||!R.isExpression(i.value.expression)||n.set(i.name.name,i.value.expression);o.stop()}}});let r=new Map;for(let[o,i]of n){let s=await De(i,t);s&&r.set(o,s)}return r}function lI(e,t){return e.loc?.start.line===t.startLine&&e.loc.start.column===t.startColumn&&e.loc.end.line===t.endLine&&e.loc.end.column===t.endColumn}async function fp(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 fc(e,r,t.fileCache)}function uI(e,t,n){if(R.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,dc(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,Ke(o))}}function dI(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":aI.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function fI(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 Mi(i.collectionSource,n);s&&r.push(Oi(Nn(s),"repeat-region",i.collectionExpression))}return r}async function pI(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 Mi(i.conditionSource,n);s&&r.push(Oi(Nn(s),"conditional-region",i.conditionExpression))}return r}async function mI(e,t,n,r){return pp(e.source,t,n,r)}async function pp(e,t,n,r){let o=await gI(e,t,n,r);return o||Mi(e,r)}async function gI(e,t,n,r){if(!e)return null;let o=hI(e.base,t,n);if(!o)return null;let i=await Mi(o.collectionSource,r);return i?to(i,e.path,!0):null}function hI(e,t,n){let r=t.identity.key;for(;r;){for(let o of n.regions){if(o.kind!=="repeat-region"||!o.childKeys.includes(r))continue;let i=o.sourceCandidates?.find(s=>s.kind==="repeat-template"&&s.itemParamName===e);if(i)return i}r=n.elements.get(r)?.parentKey??null}return null}async function Mi(e,t){if(!e)return null;let n=await mp(e.base,t);return n?to(n,e.path,!1):null}async function mp(e,t){let n=t.paramSources.get(e);if(n)return Ke(n);if(t.variableCache.has(e))return AI(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await yI(e,t);if(r)return t.variableCache.set(e,Ke(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=await De(o,t);return t.variableCache.set(e,s?Ke(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await kp(i,t);if(s){let a=Di(s,t,{importDepth:t.importDepth+1}),c=Cp(i,s);if(c){let f=(await Pn(c,[],a)).returnSource;return t.variableCache.set(e,f?Ke(f):null),t.resolvingVariables.delete(e),f}let l=s.variables.get(i.importedName);if(l){let u=await De(l,a);return t.variableCache.set(e,u?Ke(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function yI(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];lc(t.analysis.ast,{CallExpression(o){if(R.isIdentifier(o.node.callee,{name:n})){let i=o.node.arguments[0];R.isExpression(i)&&r.push(i);return}o.node.arguments.some(i=>R.isIdentifier(i)&&i.name===n)&&r.push(o.node)}});for(let o of r){let i=await De(o,t);if(i)return i}return null}async function De(e,t){if(R.isIdentifier(e))return mp(e.name,t);if(R.isMemberExpression(e)||R.isOptionalMemberExpression(e)){let n=R.isMemberExpression(e)?np(e,{file:t.file}):null;if(n)return xp(n);let r=await xI(e,t);if(!r)return null;let o=wI(e);return to(r,o,!1)}if(R.isAwaitExpression(e))return R.isExpression(e.argument)?De(e.argument,t):null;if(R.isCallExpression(e))return gp(e,t);if(R.isObjectExpression(e)){let n=await hp(e,t);return Object.keys(n).length>0?dc(n,t.file):null}if(R.isConditionalExpression(e)){let n=await De(e.consequent,t),r=await De(e.alternate,t);return eo(ip(n,r))}if(R.isLogicalExpression(e)){let n=await De(e.left,t),r=await De(e.right,t);return eo(ip(n,r))}return R.isTSAsExpression(e)||R.isTSSatisfiesExpression(e)||R.isTSNonNullExpression(e)||R.isTypeCastExpression(e)||R.isParenthesizedExpression(e)?De(e.expression,t):null}async function xI(e,t){let n=e;for(;R.isMemberExpression(n)||R.isOptionalMemberExpression(n);)n=n.object;return R.isExpression(n)?De(n,t):null}async function gp(e,t){let n=tp(e,{file:t.file,imports:t.analysis.imports});if(n)return xp(n);if(rp(e)){let f=e.arguments[0];if(f&&R.isExpression(f))return eo(await De(f,t))}let r=await bI(e,t);if(r)return r;let o=qf(e,{file:t.file});if(o)return{sourceKind:o.sourceKind,sourceType:"api-field",endpointPattern:o.endpointPattern,valuePath:o.valuePath,confidence:o.confidence,readonly:!0,evidence:o.evidence};let i=await vI(e,t);if(i)return i;let s=await II(e,t);if(s)return s;let a=await kI(e,t);if(a)return a;let c=await CI(e,t);if(c)return c;let l=[];for(let f of e.arguments)if(R.isExpression(f)){let m=await De(f,t);m&&l.push(m)}let u=bp(l);return u.length===1?eo(u[0]):null}async function bI(e,t){let n=Lt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=EI(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(R.isIdentifier(s)){let a=await qr(s.name,t);if(a)return(await Pn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!R.isObjectExpression(r))return Fi(t.file,`${n} without static options`);let o=SI(r,"queryFn");if(!o)return Fi(t.file,`${n} without queryFn`);if(R.isIdentifier(o)){let i=await qr(o.name,t);return i?(await Pn(i.node,[],i.context)).returnSource:Fi(t.file,`${n} queryFn unresolved`)}return R.isArrowFunctionExpression(o)||R.isFunctionExpression(o)?(await Pn(o,[],t)).returnSource:R.isCallExpression(o)?gp(o,t):null}function SI(e,t){for(let n of e.properties){if(!R.isObjectProperty(n)||!R.isExpression(n.value))continue;if(yp(n)===t)return n.value}return null}function EI(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 vI(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"].includes(n))return null;let r=R.isExpression(e.callee.object)?await De(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Nn(r);let o=e.arguments[0];if(R.isIdentifier(o)){let i=await qr(o.name,t);if(!i)return Nn(r);let s=await Pn(i.node,[r],i.context);return{...Nn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(R.isArrowFunctionExpression(o)||R.isFunctionExpression(o)){let i=await Pn(o,[r],t);return{...Nn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Nn(r)}async function II(e,t){return!R.isMemberExpression(e.callee)||!R.isIdentifier(e.callee.property,{name:"json"})||!R.isExpression(e.callee.object)?null:De(e.callee.object,t)}async function kI(e,t){return!R.isMemberExpression(e.callee)||!R.isIdentifier(e.callee.property,{name:"then"})||!R.isExpression(e.callee.object)?null:eo(await De(e.callee.object,t))}async function CI(e,t){if(!R.isIdentifier(e.callee))return null;let n=await qr(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!R.isExpression(i)){r.push(Fi(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await De(i,t);r.push(s)}return(await Pn(n.node,r,n.context)).returnSource}async function qr(e,t){let n=t.analysis.functions.get(e);if(n)return{node:n,context:t};let r=t.analysis.imports.get(e);if(!r||t.importDepth>=t.options.maxImportDepth)return null;let o=await kp(r,t);if(!o)return null;let i=Di(o,t,{importDepth:t.importDepth+1}),s=Cp(r,o);return s?{node:s,context:i}:qr(r.importedName,i)}async function Pn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=Di(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let u=t[l];u&&cc(c,NI(u),r)});let o=RI(e),i=null,s,a=!1;for(let c of o){if(R.isObjectExpression(c)){s={...s??{},...await hp(c,r)},i=i??dc(s,n.file);continue}let l=await De(c,r);if(l){if(!i){i=l;continue}let u=uc(i,l);if(!u){a=!0,i=null;continue}i=u}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function cc(e,t,n){if(R.isIdentifier(e)){n.paramSources.set(e.name,Ke(t));return}if(R.isAssignmentPattern(e)){cc(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=to(t,[{kind:"property",name:r.key.name}],!0),i=R.isAssignmentPattern(r.value)?r.value.left:r.value;cc(i,o,n)}}function RI(e){if(R.isArrowFunctionExpression(e)&&R.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!R.isBlockStatement(n))return t;let r=o=>{if(R.isFunction(o)&&o!==e)return;if(R.isReturnStatement(o)){o.argument&&R.isExpression(o.argument)&&t.push(o.argument);return}let i=R.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)R.isNode(c)&&r(c);else R.isNode(a)&&r(a)}};return r(n),t}async function hp(e,t){let n={};for(let r of e.properties){if(!R.isObjectProperty(r))continue;let o=yp(r);if(!o||!R.isExpression(r.value))continue;let i=await De(r.value,t);i&&(n[o]=i)}return n}function yp(e){return R.isIdentifier(e.key)&&!e.computed?e.key.name:R.isStringLiteral(e.key)?e.key.value:null}function wI(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 to(e,t,n){if(t.length===0)return Ke(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return to(e.fieldMap[r.name],t.slice(1),n);let o=Ke(e);if(o.sourceType==="cms-field"){let i=t.filter(s=>s.kind==="property").map(s=>s.name);return i[0]==="data"&&i[1]==="items"?(o.valuePath=Qr(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=Qr(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=Qr(o.fieldPath,i.join(".")),o):(o.valuePath=Qr(o.valuePath,op(t)),o)}return o.valuePath=Qr(o.valuePath,op(t)),o}function op(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Qr(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function xp(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 Nn(e){let t=Ke(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function NI(e){let t=Ke(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function eo(e){return e?{...Ke(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function ip(e,t){return e?t?uc(e,t):Ke(e):t?Ke(t):null}function uc(e,t){if(_i(e)!==_i(t))return null;let n=vp(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function bp(e){let t=new Map;for(let n of e){let r=_i(n),o=t.get(r);t.set(r,o?uc(o,n):Ke(n))}return[...t.values()]}function _i(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,_i(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 dc(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 Fi(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Oi(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 Sp(e){let t=[...e].sort(Ep),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 PI(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 Ep(e,t){return sp(e.targetKind)-sp(t.targetKind)||vp(e.confidence,t.confidence)||ap(e.sourceKind)-ap(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function sp(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function ap(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function vp(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function fc(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=iI(t,{sourceType:"module",plugins:["jsx","typescript"]}),i={file:e,source:t,ast:o,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,functionVariables:new WeakMap};return lc(o,{ImportDeclaration(s){let a=s.node.source.value;for(let c of s.node.specifiers)R.isImportSpecifier(c)&&R.isIdentifier(c.local)?i.imports.set(c.local.name,{source:a,importedName:R.isIdentifier(c.imported)?c.imported.name:c.imported.value,localName:c.local.name,isDefault:!1}):R.isImportDefaultSpecifier(c)&&i.imports.set(c.local.name,{source:a,importedName:"default",localName:c.local.name,isDefault:!0})},FunctionDeclaration(s){s.node.id?.name&&i.functions.set(s.node.id.name,s.node)},VariableDeclarator(s){let a=s.getFunctionParent(),c=a&&(R.isFunctionDeclaration(a.node)||R.isFunctionExpression(a.node)||R.isArrowFunctionExpression(a.node))?a.node:null,l=c?i.functionVariables.get(c)??new Map:i.variables;c&&!i.functionVariables.has(c)&&i.functionVariables.set(c,l);for(let u of or(s.node.id))l.set(u,R.isExpression(s.node.init)?s.node.init:null);if(R.isArrayPattern(s.node.id)&&R.isCallExpression(s.node.init)&&Lt(s.node.init.callee)==="useState"){let[u,f]=s.node.id.elements;R.isIdentifier(u)&&R.isIdentifier(f)&&i.stateSetters.set(u.name,f.name)}R.isIdentifier(s.node.id)&&cp(s.node.init)&&i.functions.set(s.node.id.name,s.node.init)},ExportNamedDeclaration(s){let a=s.node.declaration,c=s.node.source?.value;if(c)for(let l of s.node.specifiers){if(!R.isExportSpecifier(l))continue;let u=R.isIdentifier(l.exported)?l.exported.name:l.exported.value,f=l.local.name;i.imports.set(u,{source:c,importedName:f,localName:u,isDefault:f==="default"})}if(R.isFunctionDeclaration(a)&&a.id?.name&&i.functions.set(a.id.name,a),R.isVariableDeclaration(a))for(let l of a.declarations)R.isIdentifier(l.id)&&cp(l.init)&&i.functions.set(l.id.name,l.init)},ExportDefaultDeclaration(s){let a=s.node.declaration;if((R.isFunctionDeclaration(a)||R.isFunctionExpression(a)||R.isArrowFunctionExpression(a))&&i.functions.set("default",a),R.isIdentifier(a)){let c=i.functions.get(a.name);c&&i.functions.set("default",c)}}}),n.set(e,i),i}function or(e){return!e||R.isVoidPattern(e)?[]:R.isIdentifier(e)?[e.name]:R.isObjectPattern(e)?e.properties.flatMap(t=>R.isObjectProperty(t)?or(t.value):or(t.argument)):R.isArrayPattern(e)?e.elements.flatMap(t=>t?or(R.isRestElement(t)?t.argument:t):[]):R.isAssignmentPattern(e)?or(e.left):R.isRestElement(e)?or(e.argument):[]}function cp(e){return R.isFunctionExpression(e)||R.isArrowFunctionExpression(e)}function Ip(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function kp(e,t){let n=await Rp(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return fc(n,r,t.fileCache)}function Cp(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Rp(e,t,n){return Tt(t)?hn(e,t,n):null}function Di(e,t,n={}){return{file:e.file,analysis:e,readFile:t.readFile,exists:t.exists,fileCache:t.fileCache,options:t.options,variableCache:new Map,functionDepth:n.functionDepth??t.functionDepth,importDepth:n.importDepth??t.importDepth,paramSources:new Map(t.paramSources),resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0}}function AI(e){return e?Ke(e):null}function Ke(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,Ke(n)]))}:{}}}import*as mc from"@babel/parser";import pc from"@babel/traverse";import*as z from"@babel/types";import{classifySiteEditPropertyName as TI}from"@vcp-dev/contracts";var gc=typeof pc=="function"?pc:pc.default;function hc(e){let t=TI(e.propertyName);if(t.owner!=="generic")return rt("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return rt("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return rt("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return rt("missing-instance-index","A repeat property target requires an instance index");let r;try{r=mc.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(E){return rt("repeat-not-found",`Unable to parse repeat source: ${E instanceof Error?E.message:String(E)}`)}let o=FI(r,e.element.sourceRange);if(!o)return rt("repeat-not-found","The selected element is not inside a supported map repeat");if(!z.isIdentifier(o.callback.params[0]))return rt("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=_I(r,o.collection,e.file,e.sources);if(!i)return rt("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],u=[];for(let[E,S]of s.elements.entries()){if(!S||!z.isObjectExpression(S)||!Fp(S))return rt("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let v=[{kind:"index",index:E}];l.push(v),u.push({kind:"value",root:a.root,path:v})}let f=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==f)return rt("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${f}`);let m=n.instanceIndex;if(m>=f)return rt("index-out-of-range",`Selected repeat instance ${m} is outside the source collection`);let d=s.elements[m];if(!d||!z.isObjectExpression(d))return rt("unsafe-collection","Selected repeat item is not an object");let g=jI(e.element,e.propertyName),h=LI(d,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[m],sourceItemIndex:m,sourceItemPath:l[m],collectionIndexMap:Array.from({length:f},(E,S)=>S),callbackItemName:o.callback.params[0].name,targetElementLocator:{kind:"jsx-node",strategy:"structural-path",file:e.element.identity.file,component:e.element.identity.component,structuralPath:e.element.identity.structuralPath,expectedRange:e.element.sourceRange},propertyName:e.propertyName,propertyState:h,selectedResolution:BI(d,e.propertyName),...g?{property:g}:{},selectionRef:n}:rt("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function FI(e,t){let n=[];return gc(e,{CallExpression(r){let o=wp(r.node);o&&Pp(o.callback,t)&&n.push({...o,span:Np(r.node)})},OptionalCallExpression(r){let o=wp(r.node);o&&Pp(o.callback,t)&&n.push({...o,span:Np(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function wp(e){let t=e.callee;if(!z.isMemberExpression(t)&&!z.isOptionalMemberExpression(t)||t.computed||!z.isIdentifier(t.property)||t.property.name!=="map"||!z.isExpression(t.object))return null;let n=e.arguments[0];return!n||!z.isExpression(n)||!z.isArrowFunctionExpression(n)&&!z.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function _I(e,t,n,r){let o=no(t);if(o&&z.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:Op(o)}},sourceFile:n};if(!z.isIdentifier(t))return null;let i=[];if(gc(e,{VariableDeclarator(s){z.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=no(i[0].init);return!s||!z.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return OI(e,t.name,n,r)}function OI(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!z.isImportDeclaration(o))continue;let i=o.specifiers.find(m=>m.local.name===t);if(!i||!z.isStringLiteral(o.source)||!z.isImportSpecifier(i))continue;let s=DI(n,o.source.value,r);if(!s)return null;let a=z.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=mc.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=MI(l,a),f=u?no(u):null;return!f||!z.isArrayExpression(f)?null:{array:f,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function MI(e,t){let n=null;return gc(e,{VariableDeclarator(r){n||!z.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!z.isExpression(r.node.init)||(n=r.node.init)}}),n}function DI(e,t,n){let r=Ir(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 no(e){return z.isParenthesizedExpression(e)?no(e.expression):z.isTSAsExpression(e)?Tp(e.typeAnnotation)?no(e.expression):null:z.isTSSatisfiesExpression(e)?null:e}function Tp(e){return z.isTSTypeReference(e)&&z.isIdentifier(e.typeName)&&e.typeName.name==="const"}function Fp(e){return e.properties.every(t=>!z.isObjectProperty(t)||t.computed||!z.isExpression(t.value)?!1:Li(t.value))}function Li(e){if(z.isTSAsExpression(e)&&Tp(e.typeAnnotation))return Li(e.expression);if(z.isTSSatisfiesExpression(e))return!1;if(z.isArrayExpression(e))return e.elements.every(n=>!n||z.isSpreadElement(n)||!z.isExpression(n)?!1:Li(n));if(z.isObjectExpression(e))return Fp(e);let t=At(e);return t.status==="resolved"||t.status==="undefined"}function LI(e,t){let n=e.properties.filter(o=>z.isObjectProperty(o)&&_p(o.key)===t);if(n.length>1)return null;let r=n[0];return r?z.isExpression(r.value)?Li(r.value)?"static":z.isIdentifier(r.value)||z.isMemberExpression(r.value)?"binding":null:null:"missing"}function BI(e,t){let n=e.properties.filter(o=>z.isObjectProperty(o)&&_p(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!z.isExpression(r.value)?{status:"undefined"}:At(r.value)}function jI(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function _p(e){return z.isIdentifier(e)?e.name:z.isStringLiteral(e)?e.value:z.isNumericLiteral(e)?String(e.value):null}function Op(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 Np(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function Pp(e,t){let n=Op(e);return Ap(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&Ap(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function Ap(e,t,n,r){return e===n?t-r:e-n}function rt(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as Ck}from"@vcp-dev/contracts";import*as H from"@babel/types";import so from"node:path";import*as pe from"@babel/types";import*as jp from"@babel/parser";import yc from"@babel/traverse";import*as q from"@babel/types";function Bi(e,t){let n=[],r=e;for(;q.isMemberExpression(r);){if(r.computed)if(q.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(q.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!q.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!q.isIdentifier(r)||r.name!==t?null:n}function Mp(e){if(q.isIdentifier(e))return{base:e.name,path:[]};if(!q.isMemberExpression(e))return null;let t=[],n=e;for(;q.isMemberExpression(n);){if(n.computed)if(q.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(q.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!q.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return q.isIdentifier(n)?{base:n.name,path:t}:null}function Qe(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}function Dp(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,f){if(q.isStringLiteral(i)||q.isNumericLiteral(i)||q.isBooleanLiteral(i))return i.value;if(q.isNullLiteral(i))return null;if(q.isTemplateLiteral(i))return i.expressions.length===0&&i.quasis.length===1?i.quasis[0].value.cooked??i.quasis[0].value.raw:void 0;if(q.isTSAsExpression(i)||q.isTSSatisfiesExpression(i)||q.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,f);if(q.isIdentifier(i)){let m=s.getBinding(i.name);if(!m)return;let d=await t({currentFile:a,binding:m,readFile:c,exists:l,fileCache:u,visited:f});return d?.kind==="static"?d.value:void 0}if(q.isArrayExpression(i)){let m=[];for(let d of i.elements){if(!d||q.isSpreadElement(d))return;let g=await r(d,s,a,c,l,u,f);if(g===void 0)return;m.push(g)}return m}if(q.isObjectExpression(i)){let m={};for(let d of i.properties){if(!q.isObjectProperty(d)||d.computed)return;let g=null;if(q.isIdentifier(d.key)?g=d.key.name:q.isStringLiteral(d.key)&&(g=d.key.value),!g)return;if(d.shorthand){if(!q.isIdentifier(d.value))return;let E=await r(d.value,s,a,c,l,u,f);if(E===void 0)return;m[g]=E;continue}if(!q.isExpression(d.value))return;let h=await r(d.value,s,a,c,l,u,f);h!==void 0&&(m[g]=h)}return m}if(q.isMemberExpression(i)){let m=await o(i,s,a,c,l,u,f);if(!m)return;let d=s.getBinding(m.base);if(!d)return;let g=await t({currentFile:a,binding:d,readFile:c,exists:l,fileCache:u,visited:f});return!g||g.kind!=="static"?void 0:Qe(g.value,m.path)}}async function r(i,s,a,c,l,u,f){if(!q.isSpreadElement(i))return await n(i,s,a,c,l,u,f)}async function o(i,s,a,c,l,u,f){if(q.isIdentifier(i))return{base:i.name,path:[]};if(!q.isMemberExpression(i))return null;let m=[],d=i;for(;q.isMemberExpression(d);){if(d.computed){let g=d.property;if(q.isNumericLiteral(g))m.unshift({kind:"index",index:g.value});else if(q.isStringLiteral(g))m.unshift({kind:"property",name:g.value});else{let h=q.isExpression(g)?await n(g,s,a,c,l,u,f):void 0;if(typeof h=="string")m.unshift({kind:"property",name:h});else if(Number.isInteger(h))m.unshift({kind:"index",index:h});else return null}}else{if(!q.isIdentifier(d.property))return null;m.unshift({kind:"property",name:d.property.name})}d=d.object}return q.isIdentifier(d)?{base:d.name,path:m}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var $p=typeof yc=="function"?yc:yc.default,Lp=new WeakMap;function Vp(e){try{return jp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ji(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Vp(n);return e.set(t,{source:n,ast:o}),o}function $i(e,t){let n=null,r=-1;for(let o of ro(e).expressions){let i=o.node.loc;if(!i||!bc(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function Up(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of ro(e).expressions){if(!$I(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function xc(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of ro(e).jsxElements){let i=o.node.loc;if(!i||!bc(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function ro(e){let t=Lp.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return $p(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),Lp.set(e,n),n}function $I(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 bc(e,t){let n=Bp({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=Bp({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function Vi(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 Bp(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}function ir(e,t){if(t)return Sc(e,t);let n=Mp(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Sc(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function oo(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of ro(e).expressions){if(Sc(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function Kp(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of ro(e).expressions){if(Sc(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!bc(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}function sr(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function io(e){let t=null;if($p(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function jt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Vp(o),s={source:o,ast:i};return n.set(e,s),s}function VI(e){return pe.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:pe.isMemberExpression(e.callee)&&pe.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function UI(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()||!pe.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 KI(e,t){let n=UI(e.path);if(!n)return null;let r=Gn(e,t);return r?{...n,...r}:null}function JI(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function Ec(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 vc(e,t){for(let n of e.program.body){if(t==="default"&&pe.isExportDefaultDeclaration(n))return pe.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(pe.isFunctionDeclaration(n.declaration)||pe.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(pe.isExportNamedDeclaration(n)){if(n.declaration){if(pe.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(pe.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((pe.isFunctionDeclaration(n.declaration)||pe.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((pe.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&pe.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 Jp(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(d){let{currentFile:g,binding:h,readFile:E,exists:S,fileCache:v,visited:C}=d,w=`${g}::${h.kind}::${h.identifier.name}`;if(C.has(w))return null;C.add(w);try{let A=await a({currentFile:g,binding:h,readFile:E,exists:S,fileCache:v,visited:C});if(A)return A;if(h.path.isImportSpecifier()||h.path.isImportDefaultSpecifier())return await f({currentFile:g,binding:h,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,fileCache:v,visited:C});if(h.kind==="param")return null;if(h.path.isVariableDeclarator()){let P=h.path.node.init;if(!P||!pe.isExpression(P))return null;let k=h.path.get("init");if(k&&!Array.isArray(k)&&k.isExpression()){let _=await t({currentFile:g,expressionPath:k,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});if(_)return _;if(k.isCallExpression()){let L=await n({currentFile:g,callPath:k,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});if(L)return L}}let T=await r(P,h.path.scope,g,E,S,v,C);return T===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:T,sourceKind:"binding"}}if(h.path.isIdentifier()&&h.path.parentPath?.isExportDefaultDeclaration()){let P=h.path.parentPath.node.declaration;if(!pe.isExpression(P))return null;let k=await r(P,h.path.scope,g,E,S,v,C);return k===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:k,sourceKind:"binding"}}return null}finally{C.delete(w)}}async function a(d){let{currentFile:g,binding:h,readFile:E,exists:S,fileCache:v,visited:C}=d;if(!h.path.isVariableDeclarator()||!h.path.get("id").isArrayPattern())return null;let w=h.path,A=w.node.init;if(!A||!pe.isCallExpression(A))return null;let P=VI(A);if(!P||!pe.isArrayPattern(w.node.id)||w.node.id.elements.findIndex(G=>pe.isIdentifier(G)&&G.name===h.identifier.name)!==0)return null;let T=P==="useReducer"?1:0,_=A.arguments[T];if(!_||!pe.isExpression(_))return null;let L=await r(_,w.scope,g,E,S,v,C);return L===void 0?null:{kind:"static",file:g,root:{kind:"hook-state",name:h.identifier.name,hook:P},value:L,sourceKind:"binding"}}async function c(d){let g=KI(d.binding,d.sourceInfo);if(!g||!d.graph)return null;let h=[...d.graph.elements.values()].filter(P=>JI(P,d.currentFile,g.componentName,g.exportName));if(h.length!==1)return null;let E=h[0],S=E.attributes?.find(P=>P.name===g.propName);if(S&&!S.source){let P=await l({caller:E,propName:g.propName,remainingPath:g.remainingPath,readFile:d.readFile,fileCache:d.fileCache});if(P)return Ec(P,{componentName:g.componentName,propName:g.propName,file:E.sourceFile})}if(!S?.source){let P=await u({caller:E,propName:g.propName,remainingPath:g.remainingPath,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(P)return Ec(P,{componentName:g.componentName,propName:g.propName,file:E.sourceFile});let k=qd(d.binding,g.componentName,g.propName);if(!k||k.propName!==g.propName)return null;let T=await r(k.expressionPath.node,k.expressionPath.scope,d.currentFile,d.readFile,d.exists,d.fileCache,d.visited);if(T===void 0)return null;let _=g.remainingPath;return _.length>0&&Qe(T,_)===void 0?null:{kind:"value",file:d.currentFile,root:{kind:"binding",name:g.propName},path:_,sourceKind:"binding",semanticKind:"component-prop",displayExpression:k.displayPath,chainPrefix:[{kind:"component-prop",file:d.currentFile,displayName:k.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let v=await jt(E.sourceFile,d.readFile,d.fileCache);if(!v.ast)return null;let C=Kp(v.ast,v.source,S.source.expression,S.sourceRange)??oo(v.ast,v.source,S.source.expression);if(!C)return null;let w={...S.source,expression:sr(S.source.expression,g.remainingPath),path:[...S.source.path,...g.remainingPath]},A=await o({currentFile:E.sourceFile,expressionPath:C,sourceInfo:w,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});return A?Ec(A.kind==="external"?A:{...A,displayExpression:w.expression},{componentName:g.componentName,propName:g.propName,file:E.sourceFile}):null}async function l(d){let g=await jt(d.caller.sourceFile,d.readFile,d.fileCache);if(!g.ast)return null;let h=xc(g.ast,d.caller.sourceRange);if(!h)return null;let E=h.get("openingElement").get("attributes").find(w=>w.isJSXAttribute()&&w.node.name.type==="JSXIdentifier"&&w.node.name.name===d.propName);if(!E?.isJSXAttribute())return null;let S=E.get("value"),v=S.isStringLiteral()?S:S.isJSXExpressionContainer()?S.get("expression"):null;if(!v?.isExpression())return null;let C=Vi(v.node);return C?{kind:"value",file:d.caller.sourceFile,root:{kind:"expression",sourceRange:C},path:d.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:d.propName,editMode:"upstream",diagnostics:[]}:null}async function u(d){let g=await jt(d.caller.sourceFile,d.readFile,d.fileCache);if(!g.ast)return null;let h=xc(g.ast,d.caller.sourceRange);if(!h)return null;let E=h.get("openingElement");for(let S of E.get("attributes")){if(!S.isJSXSpreadAttribute())continue;let v=S.get("argument");if(!v.isExpression())continue;let C=await i({expression:v.node,scope:v.scope,source:g.source,currentFile:d.caller.sourceFile,readFile:d.readFile,exists:d.exists,fileCache:d.fileCache,visited:d.visited});if(!C)continue;let w=[{kind:"property",name:d.propName},...d.remainingPath],A={...C,expression:sr(C.expression,w),path:[...C.path,...w]},P=await o({currentFile:d.caller.sourceFile,expressionPath:v,sourceInfo:A,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(P)return P.kind==="external"?P:{...P,displayExpression:A.expression}}return null}async function f(d){let{currentFile:g,binding:h,readFile:E,exists:S,fileCache:v,visited:C}=d,w=h.path.parentPath;if(!w||!w.isImportDeclaration())return null;let A=w.node.source.value;if(typeof A!="string")return null;let P=await hn(g,A,S);if(!P)return null;if(h.path.isImportDefaultSpecifier()){let ne=await jt(P,E,v),ve=ne.ast?vc(ne.ast,"default"):null,Y=await m({file:P,exportName:"default",readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});return!Y||Y.kind!=="static"?null:{kind:"static",file:ve?.kind==="default-expression"?Y.file:P,root:ve?.kind==="default-expression"?Y.root:{kind:"default-export"},value:Y.value,sourceKind:"imported-binding"}}if(!h.path.isImportSpecifier())return null;let k=h.path.node.imported,T=pe.isIdentifier(k)?k.name:k.value,_=await jt(P,E,v),L=_.ast?vc(_.ast,T):null,G=await m({file:P,exportName:T,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});return G?G.kind==="external"?G:{kind:"static",file:L?.kind==="re-export"?G.file:P,root:L?.kind==="re-export"?G.root:{kind:"named-export",name:T},value:G.value,sourceKind:"imported-binding"}:null}async function m(d){let{file:g,exportName:h,readFile:E,exists:S,fileCache:v,visited:C}=d,w=`export::${g}::${h}`;if(!C.has(w)){C.add(w);try{let A=await jt(g,E,v);if(!A.ast)return;let P=vc(A.ast,h);if(!P)return;if(P.kind==="default-expression"){let L=P.expression;if(!L||!pe.isIdentifier(L))return;let G=io(A.ast).getBinding(L.name);return G?await s({currentFile:g,binding:G,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C})??void 0:void 0}if(P.kind==="re-export"){if(!P.source||!P.name)return;let L=await hn(g,P.source,S);return L?m({...d,file:L,exportName:P.name}):void 0}let k=P.name;if(!k)return;let T=io(A.ast).getBinding(k);return T?await s({currentFile:g,binding:T,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C})??void 0:void 0}finally{C.delete(w)}}}return{resolveExportValue:m,resolveComponentPropBinding:c,resolveBindingTarget:s}}import*as J from"@babel/types";function kc(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=Et(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!XI(s,r)?null:{callPath:s,basePath:i}}function XI(e,t){let n=e.node.callee;return!J.isMemberExpression(n)||!J.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function Hp(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:hi(r,t)}function Xp(e,t){return e?J.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function zp(e,t,n,r,o){let i=J.isExpression(e.body)?e.body:e.body.body.find(a=>J.isReturnStatement(a))?.argument;if(!i||!J.isExpression(i))return;let s=Ic(i,t,n,r,o);return typeof s=="number"?s:void 0}function Ic(e,t,n,r,o){if(J.isNumericLiteral(e)||J.isStringLiteral(e)||J.isBooleanLiteral(e))return e.value;if(J.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(J.isMemberExpression(e)){let i=Bi(e,t);if(i)return Qe(r,i);let s=Bi(e,n);return s?Qe(o,s):void 0}if(J.isBinaryExpression(e)&&e.operator==="-"){let i=J.isExpression(e.left)?Ic(e.left,t,n,r,o):void 0,s=J.isExpression(e.right)?Ic(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function zI(e){if(J.isExpression(e.body))return e.body;for(let t of e.body.body)if(J.isReturnStatement(t)&&t.argument&&J.isExpression(t.argument))return t.argument;return null}function HI(e,t,n){let r=An(e,t,n);return typeof r=="boolean"?r:void 0}function An(e,t,n){if(J.isStringLiteral(e)||J.isNumericLiteral(e)||J.isBooleanLiteral(e))return e.value;if(J.isNullLiteral(e))return null;if(J.isIdentifier(e))return e.name===t?n:void 0;if(J.isMemberExpression(e)){let r=Bi(e,t);return r?Qe(n,r):void 0}if(J.isUnaryExpression(e)&&e.operator==="!"){let r=An(e.argument,t,n);return r===void 0?void 0:!r}if(J.isLogicalExpression(e)){let r=An(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&An(e.right,t,n);if(e.operator==="||")return r||An(e.right,t,n)}if(J.isBinaryExpression(e)){let r=J.isExpression(e.left)?An(e.left,t,n):void 0,o=J.isExpression(e.right)?An(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 Wp(e){let t=[],n=e;for(;J.isMemberExpression(n)||J.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(J.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(J.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(J.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(J.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return J.isIdentifier(n)?{base:n.name,segments:t}:null}function Gp(e){return e.some(t=>t.kind==="dynamic")}function WI(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function Yp(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 GI(e,t){let n=[],r=[];for(let o of t){let i=Qe(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 Zp(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o}=e;async function i(d){let{currentFile:g,callPath:h,readFile:E,exists:S,fileCache:v,visited:C}=d,w=h.node.callee;if(!J.isMemberExpression(w)||!J.isIdentifier(w.property)||w.property.name!=="map")return null;let A=h.get("callee");if(!A.isMemberExpression())return null;let P=A.get("object");if(Array.isArray(P)||!P.isExpression())return null;let k=await s({currentFile:g,expressionPath:P,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});return!k||!Array.isArray(k.value)||k.value.length===0?null:k}async function s(d){let{currentFile:g,expressionPath:h,readFile:E,exists:S,fileCache:v,visited:C}=d;if(h.isIdentifier()){let w=h.scope.getBinding(h.node.name);if(!w)return null;let A=await t({currentFile:g,binding:w,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});return A?.kind==="static"?A:null}if(h.isCallExpression())return c({currentFile:g,callPath:h,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let w=h.get("expression");if(!Array.isArray(w)&&w.isExpression())return s({...d,expressionPath:w})}if(h.isArrayExpression()){let w=Vi(h.node);if(!w)return null;let A=await n(h.node,h.scope,g,E,S,v,C);return Array.isArray(A)?{kind:"static",file:g,root:{kind:"expression",sourceRange:w},value:A,sourceKind:"binding"}:null}if(h.isMemberExpression()){let w=await r({expression:h.node,scope:h.scope,currentFile:g,readFile:E,exists:S,fileCache:v,visited:C});if(!w)return null;let A=await o({currentFile:g,expressionPath:h,sourceInfo:w,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});if(!A||A.kind==="external")return null;let P=await a({currentFile:g,expressionPath:h,provenance:A,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});if(!P||P.kind!=="static")return null;if(A.collectionPathMap?.length){let T=GI(P.value,A.collectionPathMap);if(T)return{kind:"static",file:A.file,root:A.root,value:T.value,sourceKind:A.sourceKind,collectionPathMap:T.collectionPathMap}}let k=Qe(P.value,A.path);return Array.isArray(k)?{kind:"static",file:A.file,root:A.root,value:k,sourceKind:A.sourceKind,pathPrefix:A.path,collectionIndexMap:A.collectionIndexMap,collectionPathMap:A.collectionPathMap}:null}return null}async function a(d){let{provenance:g}=d;if(g.root.kind==="binding"){let v=d.expressionPath.scope.getBinding(g.root.name);if(!v&&g.file!==d.currentFile){let C=await jt(g.file,d.readFile,d.fileCache);v=C.ast?io(C.ast).getBinding(g.root.name):void 0}return v?await t({currentFile:g.file,binding:v,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited}):null}if(g.root.kind!=="expression")return null;let h=await jt(g.file,d.readFile,d.fileCache);if(!h.ast)return null;let E=Up(h.ast,g.root.sourceRange);if(!E)return null;let S=await n(E.node,E.scope,g.file,d.readFile,d.exists,d.fileCache,d.visited);return S===void 0?null:{kind:"static",file:g.file,root:g.root,value:S,sourceKind:g.sourceKind}}async function c(d){return await l(d)??await u(d)??await f(d)}async function l(d){let{callPath:g}=d,h=g.node.callee;if(!J.isMemberExpression(h)||!J.isIdentifier(h.property)||h.property.name!=="filter")return null;let E=g.get("callee");if(!E.isMemberExpression())return null;let S=E.get("object");if(Array.isArray(S)||!S.isExpression())return null;let v=await s({currentFile:d.currentFile,expressionPath:S,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!v||!Array.isArray(v.value))return null;let[C]=g.node.arguments;if(!J.isArrowFunctionExpression(C)&&!J.isFunctionExpression(C))return null;let w=C.params[0];if(!J.isIdentifier(w))return null;let A=zI(C);if(!A)return null;let P=[],k=[],T=[];for(let[_,L]of v.value.entries()){let G=HI(A,w.name,L);if(typeof G!="boolean")return null;if(G){P.push(L),k.push(v.collectionIndexMap?.[_]??_);let ne=v.collectionPathMap?.[_];ne&&T.push(ne)}}return{...v,value:P,pathPrefix:v.pathPrefix,collectionIndexMap:k,...T.length>0?{collectionPathMap:T}:{}}}async function u(d){let{callPath:g}=d,h=g.node.callee;if(!J.isMemberExpression(h)||!J.isIdentifier(h.property)||h.property.name!=="slice")return null;let E=g.get("callee");if(!E.isMemberExpression())return null;let S=E.get("object");if(Array.isArray(S)||!S.isExpression())return null;let v=await s({currentFile:d.currentFile,expressionPath:S,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!v||!Array.isArray(v.value))return null;let[C,w]=g.node.arguments,A=Xp(C,0),P=Xp(w,v.value.length);if(A===null||P===null)return null;let k=Math.max(0,A<0?v.value.length+A:A),T=Math.max(0,P<0?v.value.length+P:P),_=v.value.map((G,ne)=>v.collectionIndexMap?.[ne]??ne).slice(k,T),L=v.collectionPathMap?.slice(k,T);return{...v,value:v.value.slice(k,T),pathPrefix:v.pathPrefix,collectionIndexMap:_,...L?{collectionPathMap:L}:{}}}async function f(d){let{callPath:g}=d,h=g.node.callee;if(!J.isMemberExpression(h)||!J.isIdentifier(h.property)||h.property.name!=="sort"&&h.property.name!=="toSorted")return null;let E=g.get("callee");if(!E.isMemberExpression())return null;let S=E.get("object");if(Array.isArray(S)||!S.isExpression())return null;let v=await s({currentFile:d.currentFile,expressionPath:S,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!v||!Array.isArray(v.value))return null;let[C]=g.node.arguments;if(!J.isArrowFunctionExpression(C)&&!J.isFunctionExpression(C))return null;let[w,A]=C.params;if(!J.isIdentifier(w)||!J.isIdentifier(A))return null;let P=v.value.map((T,_)=>({value:T,sourceIndex:v.collectionIndexMap?.[_]??_,originalIndex:_})),k=[...P];for(let T of P)for(let _ of P)if(zp(C,w.name,A.name,T.value,_.value)===void 0)return null;return k.sort((T,_)=>{let L=zp(C,w.name,A.name,T.value,_.value)??0;return L===0?T.originalIndex-_.originalIndex:L}),{...v,value:k.map(T=>T.value),pathPrefix:v.pathPrefix,collectionIndexMap:k.map(T=>T.sourceIndex),...v.collectionPathMap?{collectionPathMap:k.map(T=>v.collectionPathMap?.[T.originalIndex]).filter(T=>!!T)}:{}}}async function m(d){let g=null,h,E=[];for(let v of d.segments){if(v.kind!=="dynamic")continue;let C=await r({expression:v.expression,scope:d.expressionPath.scope,source:d.fileCache.get(d.currentFile)?.source,currentFile:d.currentFile,readFile:d.readFile,exists:d.exists,fileCache:d.fileCache,visited:d.visited});if(!C)return null;let w=kc(d.expressionPath,C.base);if(!w)return null;let A=await i({currentFile:d.currentFile,callPath:w.callPath,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!A||!Array.isArray(A.value))return null;let P=A.value.map((k,T)=>{let _=Qe(A.value,[{kind:"index",index:T},...w.basePath,...C.path]);return WI(_)});if(P.some(k=>k===null)||g!==null&&g!==P.length)return null;g=P.length,h??=A.collectionIndexMap,E.push(P)}if(g===null||g===0)return null;let S=[];for(let v=0;v<g;v+=1){let C=[...d.rootPath],w=0;for(let A of d.segments){if(A.kind==="dynamic"){let P=E[w]?.[v];if(!P)return null;C.push(P),w+=1;continue}C.push({...A})}S.push(C)}return{...h?{collectionIndexMap:h}:{},collectionPathMap:S}}return{resolveRepeatCollectionTarget:i,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:YI,evaluateStaticExpression:Ui}=Dp({resolveBindingTarget:e=>Ac(e)}),{resolveRepeatCollectionTarget:ZI,resolveCollectionCallTarget:QI,resolveDynamicMemberPathMap:qI}=Zp({resolveBindingTarget:e=>Ac(e),evaluateStaticExpression:Ui,buildExpressionSourceInfo:$t,resolveSourceInfoProvenance:ht}),{resolveExportValue:ek,resolveComponentPropBinding:tk,resolveBindingTarget:Ac}=Jp({resolveExternalExpression:Fc,resolveCollectionCallTarget:QI,evaluateStaticExpression:Ui,resolveSourceInfoProvenance:ht,buildExpressionSourceInfo:$t});function im(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}function Qp(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 sm(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=ji(s,t,n);if(!a)return null;let c=$i(a,r.sourceRange);if(!c)return null;let l=await $t({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await Dc({currentFile:t,expressionPath:c,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});return m?wc(m,ir(c.node,n)):null}let u=new Set,f=await Ik({currentFile:t,expressionPath:c,segment:{...r,source:l},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:u});return f?wc(f,l.expression):null}async function ar(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=ji(i,t,n);if(!s)return null;let a=e.sourceRange?$i(s,e.sourceRange):e.expression!==void 0?oo(s,n,e.expression):null;if(!a)return null;let c=Lc(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await $t({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),f=u?await ht({currentFile:t,expressionPath:c,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l}):await kk({currentFile:t,expressionPath:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l});return wc(f,e.expression??ir(c.node,n))}async function Tc(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=ji(i,t,n);if(!s)return ot("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?nk({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}):rk({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function $t(e){if(H.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!H.isMemberExpression(e.expression))return null;let t=await YI(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:ir(e.expression,e.source),base:t.base,path:t.path}:null}function wc(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 nk(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=$i(r,o.sourceRange),u=l?await $t({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null;if(!u){if(!l||l.isStringLiteral()||l.isTemplateLiteral()&&l.node.expressions.length===0)return qp(t,o.value);let m=await Dc({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return m?m.kind==="external"?om(t,m):Pc(t,ir(l.node,n),m):ok({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return ot("unsupported-expression","Unable to locate text expression for provenance resolution");let f=await ht({currentFile:t,expressionPath:l,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!f){let m=Nc(l.node);if(m)return ot(m.code,m.message);let d=l.scope.getBinding(u.base);if(d?.path.isVariableDeclarator()){let g=Nc(d.path.node.init);if(g)return ot(g.code,g.message)}return d?.path.isVariableDeclarator()&&H.isCallExpression(d.path.node.init)?ik("unsupported-expression",dm(d.path.node.init,e.functionCallContracts)):ot("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return f.kind==="external"?om(t,f):Pc(t,u.expression,f)}async function rk(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return ot("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=oo(r,n,o.conditionExpression);if(!l)return ot("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await ht({currentFile:t,expressionPath:l,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!u)return ot("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return ot("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=Pc(t,o.conditionExpression,u);return f.finalSource?{...f,finalSource:{...f.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...f.chain,{kind:"conditional-branch",file:u.file,displayName:o.conditionExpression,canEditHere:!0}]}:f}function qp(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 ok(e){let t=await cm(e);if(t.length===0)return ot("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(sk(e.expression))return am(t);if(um(e.expression))return ot("unsupported-expression","i18n helpers require a static message id string");if(H.isMemberExpression(e.expression)&&e.expression.computed&&!H.isNumericLiteral(e.expression.property)&&!H.isStringLiteral(e.expression.property))return ot("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return ot(n.code,n.message)}function ot(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function ik(e,t){return am([{code:e,message:t}])}function am(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function sk(e){return H.isCallExpression(e)||H.isConditionalExpression(e)||H.isLogicalExpression(e)||H.isBinaryExpression(e)}function ao(e){let t=new Set;return e.filter(n=>{let r=`${n.code}:${n.message}`;return t.has(r)?!1:(t.add(r),!0)})}async function cm(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Nc(t);if(l)return[l];if(H.isCallExpression(t))return[{code:"unsupported-expression",message:dm(t,c)}];if(H.isMemberExpression(t)&&t.computed){let u=t.property;if(!H.isNumericLiteral(u)&&!H.isStringLiteral(u)){if(!H.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let m=await Ui(u,n,r,o,i,s,a);if(typeof m!="string"&&!Number.isInteger(m))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return H.isBinaryExpression(t)?ao([...await Cc(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):H.isLogicalExpression(t)?ao([...await Cc(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"}]):H.isConditionalExpression(t)?ao([...await Cc(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 Nc(e){return um(e)?em("i18n helpers require a static message id string"):dk(e)?em("CMS helpers require static entry id and field path string arguments"):null}async function Cc(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await cm({...t,expression:o}));return r}function ak(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:[ck(e.sourceType)]}}async function Fc(e){for(let n of gk){if(!tm(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return rm(nm(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(!tm(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return rm(nm(r),e.externalAdapters)}return null}function ck(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function lk(e){return{code:"external-source-readonly",message:e}}function em(e){return{code:"unsupported-expression",message:e}}function _c(e){return!e||!H.isCallExpression(e)?null:H.isIdentifier(e.callee)?e.callee.name:H.isMemberExpression(e.callee)&&!e.callee.computed&&H.isIdentifier(e.callee.object)&&H.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function tm(e,t){if(!t||t.length===0)return!0;let n=_c(e.node);return n?t.includes(n):!1}function nm(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:ao(e.diagnostics??[])}:{match:e,diagnostics:[]}}function rm(e,t){let n=ak(e.match,t);return{kind:"external",file:e.match.file,sourceType:e.match.sourceType,sourceId:e.match.sourceId,adapterId:e.match.adapterId??n.adapterId,displayPath:e.match.displayPath,editMode:e.editMode==="readonly"?"readonly":n.editMode,diagnostics:ao([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function uk(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!H.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!H.isStringLiteral(n)||!H.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 dk(e){return!!e&&H.isCallExpression(e)&&H.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!H.isStringLiteral(e.arguments[0])||!H.isStringLiteral(e.arguments[1]))}function lm(e){if(!(!e||!H.isCallExpression(e))){if(H.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&H.isStringLiteral(t)?t.value:null}if(H.isMemberExpression(e.callee)&&!e.callee.computed&&H.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&H.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!H.isObjectExpression(t))return null;for(let n of t.properties)if(H.isObjectProperty(n)&&!n.computed&&(H.isIdentifier(n.key)&&n.key.name==="id"||H.isStringLiteral(n.key)&&n.key.value==="id")&&H.isStringLiteral(n.value))return n.value.value;return null}}}function um(e){return lm(e)===null}async function fk(e,t,n){let r=new Set,o=so.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=so.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"]:[so.posix.join(i,"locales"),so.posix.join(i,"messages")];for(let a of s){let c=so.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function pk(e){let t=lm(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await fk(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function mk(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!H.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!H.isExpression(n))return null;let o=await Ui(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:[lk("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var gk=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>uk(e)},{helperNames:["apiField"],resolve:e=>mk(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>pk({currentFile:e,expressionPath:t,exists:n})}];function Oc(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function om(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 Pc(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(l=>l.kind==="index"),i=vk(n),s;n.semanticKind?s=n.semanticKind:i?s="config-entry":n.sourceKind==="repeat-template"?s="repeat-template":n.path.length===0?s=n.sourceKind==="imported-binding"?"imported-binding":"binding":s=o?"array-item":"object-field";let a=n.displayExpression??t,c=[...n.chainPrefix??[]];return n.sourceKind==="binding"?c.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:n.editMode!=="readonly"}):n.sourceKind==="imported-binding"?c.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:n.editMode!=="readonly"}):n.sourceKind==="repeat-template"&&c.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:n.editMode!=="readonly"}),n.path.length>0&&n.sourceKind!=="repeat-template"&&c.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:n.editMode!=="readonly"}),i&&c.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:n.editMode!=="readonly"}),{finalSource:{kind:s,file:n.file,locator:r,root:n.root,path:n.path,displayPath:a,externalSource:i?{sourceType:"config-entry",sourceId:i.sourceId}:void 0},chain:n.editMode==="readonly"?c.map(l=>({...l,canEditHere:!1})):c,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var hk=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Mc(e,t){let n=[...hk,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function dm(e,t){let n=e.callee;return H.isIdentifier(n)&&Mc(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 Dc(e){let t=await Fc(e);if(t)return t;let n=await fm({...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 $t({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 ht({...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 Sk(e)}async function fm(e){let t=await It({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=Lc(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:Oc(t.provenance)}async function It(e){let t=Lc(e.expressionPath),n=bk(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 $t({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 ht({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 $t({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 ht({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 It({...e,expressionPath:r,allowComposed:!0}),a=await It({...e,expressionPath:o,allowComposed:!1}),c=await It({...e,expressionPath:i,allowComposed:!1});return Rc(s,a,c)}if(t.isCallExpression())return yk({...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 It({...e,expressionPath:r,allowComposed:!0}),s=await It({...e,expressionPath:o,allowComposed:!0});return Rc(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 It({...e,expressionPath:r,allowComposed:!0}),s=await It({...e,expressionPath:o,allowComposed:!0});return Rc(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:It({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Lc(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 yk(e){let t=_c(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:It({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(H.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:It({...e,expressionPath:o,allowComposed:!1})}}return null}function Rc(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!xk(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function xk(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 bk(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function Sk(e){if(!e.expressionPath.isCallExpression())return null;let t=_c(e.expressionPath.node);if(!t)return null;let n=Mc(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 pm({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?Oc(i):null}async function pm(e){let t=await Fc({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 $t({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 ht({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 Dc({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 Ek(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!H.isCallExpression(t))return null;let n=t.callee;if(!H.isIdentifier(n))return null;let r=Mc(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 pm({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?Oc(a):null}function vk(e){if(e.sourceKind!=="imported-binding")return null;let t=e.root.kind==="binding"||e.root.kind==="named-export"?e.root.name:e.root.kind==="default-export"?"default":null;if(!t)return null;let n=/(^|[\/.-])(config|settings)([\/.-]|$)/i.test(e.file),r=/config|settings/i.test(t);if(!n&&!r)return null;let o=sr(t,e.path);return{sourceId:o,displayPath:o}}async function Ik(e){let t=e.segment.source;return t?ht({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 ht(e){let t=e.sourceInfo,n=kc(e.expressionPath,t.base);if(n){let l=await ZI({currentFile:e.currentFile,callPath:n.callPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:e.fileCache,visited:e.visited});if(!l){let h=Hp(n.callPath,[...n.basePath,...t.path]);return Ur(h)?Qp(e.currentFile,h.sourceId,h.displayPath):null}let u=Yp(l,[...n.basePath,...t.path]),f=l.collectionIndexMap?.[0]??0,m=[...l.pathPrefix??[],{kind:"index",index:f},...n.basePath,...t.path],d=[{kind:"index",index:0},...n.basePath,...t.path];return Qe(l.value,d)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??m,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],u=r.path.parentPath;if(!l||l.kind!=="property"||!u?.isImportDeclaration())return null;let f=await hn(e.currentFile,u.node.source.value,e.exists);if(!f)return null;let m=await ek({file:f,exportName:l.name,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!m||m.kind==="external")return null;let d=t.path.slice(1);return Qe(m.value,d)===void 0?null:{kind:"value",file:m.file,root:m.root,path:d,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=Zd(r);if(o){let l=o.expressionPath,u=await $t({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let f=await ht({...e,expressionPath:l,sourceInfo:{...u,expression:sr(u.expression,t.path),path:[...u.path,...t.path]}});if(f)return f}if(t.path.length===0){let f=await fm({currentFile:e.currentFile,expressionPath:l,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(f)return f}}if(r.kind==="param")return tk({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 Ek({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=mi(r,t.path);if(Ur(s))return Qp(e.currentFile,s.sourceId,s.displayPath);let a=await Ac({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:Qe(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 kk(e){let t=Wp(e.expressionPath.node);if(!t||!Gp(t.segments))return null;let n=await ht({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 qI({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:ir(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function mm(e){let t=Ck(e.propertyName);if(t.owner==="blocked")return an(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return an(t.owner,{code:"owner-delegated",message:`Property '${e.propertyName}' is owned by ${t.owner}`});let n=e.element.attributes?.filter(l=>l.name===e.propertyName)??[];if(n.length>1)return an("generic",{code:"duplicate-property-source",message:`Property '${e.propertyName}' has multiple explicit sources`});let r=n[0],o=[];r&&o.push({kind:"attribute",order:r.order??e.element.attributes.indexOf(r),attribute:r});let i=e.element.attributeSpreads??[];for(let l of i)o.push({kind:"spread",order:l.order,spread:l,target:await wk(e,l)});o.sort((l,u)=>l.order-u.order);let s=o.at(-1);if(!s)return{status:"missing",owner:"generic"};if(o.filter(l=>l.kind==="spread"&&l.order>s.order).some(l=>!l.target))return an("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}:an("generic",{code:"ambiguous-property-source",message:`The final spread source for '${e.propertyName}' is not provably writable`});let c=o.filter(l=>l.kind==="spread"&&l.order<s.order);return e.operation==="remove"&&c.length>0?an("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):Rk(e,s.attribute)}async function Rk(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await ar({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}}:an("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 ar({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"?an("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 wk(e,t){let n=t.source?.expression;if(!n)return;let r=await ar({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:Nk(r,e.propertyName)}}function Nk(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 an(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function gm(e){let{key:t,element:n,graph:r,provenances:o}=e,i=Ak(t,n,r),s=i?.tag??(Tn(n.tag)?n.tag:n.componentName),a=i?.identity.key??hm(n,r)??t,c=_k(i),l=Ok(t,n,r,o,i),u=Pk(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:Fk(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:u,impactScope:Mk(u),alternativeStrategies:Dk(u)}}function Pk(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Bc(e,n)?"instance":!Tn(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function hm(e,t){if(Tn(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&Tk(r,e.componentName));return n.length!==1?null:n[0].identity.key}function Ak(e,t,n){if(Tn(t.tag))return t;let r=Bc(e,n);if(r)return r;let o=hm(t,n);return o?n.elements.get(o)??null:null}function Tk(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function Fk(e,t){return Tn(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function _k(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 Ok(e,t,n,r,o){let i=new Set,s=Bc(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(u=>u.kind==="component-prop");if(!c)continue;let l=c.displayName.split(".").pop();l&&i.add(l)}return i.size===0&&Tn(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Bc(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Tn(r.tag))return r;n=r.parentKey}return null}function Tn(e){return/^[A-Z]/.test(e)}function Mk(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function Dk(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function bm(e){let t=e.isRepeat??(e.graph?Xk(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=Jk(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>Lk({attribute:u,element:e.element,isRepeat:t,selectionRef:e.selectionRef,provenance:n.get(u.name),repeatTarget:r.get(u.name)})),a=(e.element.attributeSpreads?.length??0)>0,c=(e.element.attributeSpreads??[]).slice().sort((u,f)=>u.order-f.order).map(u=>({raw:u.raw,sourceRange:zk(u.sourceRange,e.source),order:u.order,diagnostics:u.source?[]:[{code:"unsupported-spread-source",message:"The spread source cannot be resolved safely, so property ownership is conservative."}]})),l=t&&e.selectionRef?.instanceIndex!==void 0&&i;return{documentVersion:e.documentVersion,...e.selectionRef?{selectionRef:e.selectionRef}:{},items:s,spreads:c,creation:t?{selection:l?"materialize":"unsupported",template:"unsupported"}:{selection:a?"unsupported":"direct",template:a?"unsupported":"direct"}}}function Lk(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=Bk(t,n,e.isRepeat),s=["selection","template"].map(E=>({scope:E,result:Ii({state:n,scope:E,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:E})=>E.ok)?.result,c=a?.ok?a.target:void 0,l=c?.kind==="value-binding"&&o&&(JSON.stringify(c.locator.root)!==JSON.stringify(o.selectedParentObjectLocator.root)||JSON.stringify(c.locator.path??[])!==JSON.stringify([...o.selectedParentObjectLocator.path??[],{kind:"property",name:t.name}]))?null:o,u=jk(t,n,l,e.isRepeat),f=c?Uk(c,e.element,t.name):void 0,m=s.filter(({result:E})=>E.ok).map(({scope:E})=>E),d=m.length>0?Vk(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=Kk(t,n,r);if(m.length===0&&h.length===0){let E=s.find(({result:S})=>!S.ok)?.result;E&&!E.ok&&h.push({code:E.code,message:E.reason})}return{name:t.name,source:i,resolution:u,editMode:d,sourceScope:g,allowedWriteScopes:m,...f?{effectiveWriteTarget:f}:{},diagnostics:h}}function Bk(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 jk(e,t,n,r){return n?ym(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:ym($k(e))}function $k(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 ym(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function Vk(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 Uk(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:xm({...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:xm(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function Kk(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 Jk(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function Xk(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 xm(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 zk(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 Hk(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var Wk=160;function Sm(e,t,n,r={}){let o=Kn(e),i=[];for(let[s,a]of e.elements){let c=n.get(s),l={canUpdateText:r.canUpdateTextByKey?.get(s)??c?.canUpdateText??!1,canInsertChild:c?.canInsertChild??!1,canMove:c?.canMove??!1,canRemove:c?.canRemove??!1};i.push({key:s,tag:a.tag,label:a.tag===a.componentName?a.tag:`${a.tag} (${a.componentName})`,parentKey:a.parentKey,childKeys:[...a.childKeys],operationSummary:l,...r.dynamicDataSummaryByKey?.get(s)?{dynamicDataSummary:r.dynamicDataSummaryByKey.get(s)}:{}})}return{composition:o,routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:i}}function Em(e,t,n,r,o,i,s,a,c,l,u){let f=Kn(t),m=t.elements.get(e),d=n.nodes.get(e),g=r.get(e);if(!m||!d||!g)throw new Error(`Node not found: ${e}`);let h=Rm(m.textSegments,s),E=wm(e,t,m,g,h),S=h?Zk(h):void 0,v=Qk(i,h),C=m.textSegments.map(k=>({index:k.index,value:k.value,editable:Nm(k,g,s?.get(k.index)??null),source:o.get(k.index)??null})),w=km(m,t),A=m.childKeys.map(k=>{let T=t.elements.get(k);return T?{key:k,tag:T.tag,label:T.tag}:null}).filter(k=>k!==null),P=[];if(m.parentKey){let k=t.elements.get(m.parentKey);if(k)for(let T of k.childKeys){if(T===e)continue;let _=t.elements.get(T);_&&P.push({key:T,tag:_.tag,label:_.tag})}}return{composition:f,key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:Im(m),label:m.tag,capabilities:E,writeTarget:i,effectiveWriteTarget:v,provenanceChain:S,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:C,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:w,children:A,siblings:P}}function vm(e,t,n,r,o,i,s,a){let c=Kn(t),l=t.elements.get(e),u=n.nodes.get(e),f=r.get(e);if(!l||!u||!f)throw new Error(`Node not found: ${e}`);let m=Rm(l.textSegments,i);return{composition:c,key:e,tag:l.tag,componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:Im(l),label:l.tag,capabilities:wm(e,t,l,f,m),provenanceChain:m?{editMode:m.editMode,diagnostics:m.diagnostics.map(d=>({code:d.code,message:d.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(d=>{let g=o.get(d.index);return{index:d.index,editable:Nm(d,f,i?.get(d.index)??null),source:g?{kind:g.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:km(l,t)}}function Im(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:Gk(e.sourceRange),structuralPath:e.identity.structuralPath,...Yk(e.textSegments)}}function km(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 Gk(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Yk(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,Wk)}:{}}function Cm(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 Rm(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function wm(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(u=>u.kind==="repeat-region"&&u.childKeys.includes(e)),a=o?.diagnostics.find(u=>u.code==="missing-adapter"||u.code==="external-source-readonly")?.code,c=r.canUpdateText?{mode:o?.editMode??"direct",reasonCode:a??(o?.editMode==="upstream"?"component-prop":o?.finalSource?.kind==="repeat-template"?"repeat-item-data":void 0)}:{mode:"unsupported",reasonCode:"capability-denied"},l=r.canUpdateText&&Pm(c.mode);return{...r,canUpdateText:l,editModes:{updateText:c,insertChild:r.canInsertChild?{mode:"direct",reasonCode:i||s?"repeat-template":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},move:r.canMove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},remove:r.canRemove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"}}}}function Nm(e,t,n){return!e.editable||!t.canUpdateText?!1:n?Pm(n.editMode):!0}function Pm(e){return e==="direct"||e==="proxy"||e==="upstream"}function Zk(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 Qk(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}:Hk(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 jc=["set-class-name-source","apply-style-draft"];function Am(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:jc,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:jc,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:jc}}function Tm(e){let t=new Map;for(let[n,r]of e.elements){let o=/^[A-Z]/.test(r.tag),i={file:r.sourceFile,componentName:r.componentName,isProxy:o},s=r.boundaryKind,a=[];r.isOpaque&&a.push({kind:"opaque-region",reason:`Component '${r.tag}' is opaque: internal structure not editable`}),o&&!r.isOpaque&&a.push({kind:"component-boundary",reason:`Component '${r.tag}' boundary: editing requires source file access`});let c={key:n,writeTarget:i,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,c)}for(let n of e.regions){let r=n.kind==="repeat-region"?"repeat-region":n.kind==="conditional-region"?"conditional-region":n.kind==="opaque-region"?"opaque-region":"component-boundary",o=n.kind==="repeat-region"?"Node is inside a repeat region: operations affect the template, not individual instances":n.kind==="conditional-region"?"Node is inside a conditional region: visibility depends on runtime condition":`Node is inside a ${n.kind}`;for(let i of n.childKeys){let s=t.get(i);s&&s.constraints.push({kind:r,reason:o}),Fm(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Fm(e,t,n,r,o){let i=o.elements.get(e);if(i)for(let s of i.childKeys){let a=r.get(s);a&&!a.constraints.some(c=>c.kind===t)&&(a.constraints.push({kind:t,reason:n}),Fm(s,t,n,r,o))}}import _m from"node:path";function Vc(){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 Mm(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=nC(i.path);if(!s.ok)return s;let a=s.path;if(o.has(a))return{ok:!1,code:"duplicate-target",path:a,reason:`Duplicate file target: ${a}`};if(o.add(a),i.kind==="create-only"){let c=t.has(a),l=n?await n(a):!1;if(c||l)return{ok:!1,code:"create-only-exists",path:a,reason:`Create-only file already exists: ${a}`}}r.push({...i,path:a})}return{ok:!0,plan:{operationId:e.operationId,intents:r}}}async function Ki(e){let t=()=>qk(e);return e.mutex?e.mutex.runExclusive(t):t()}async function qk(e){let t=await Mm(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=eC(e.overlay,t.plan),r;try{r=await e.buildCandidate({overlay:n,plan:t.plan})}catch(l){return{ok:!1,stage:"build",reason:"Candidate build failed.",error:l,recoveryRequired:!1}}let o,i;try{o=await e.prepareHistory?.({candidate:r,plan:t.plan}),await e.reverify?.({candidate:r,plan:t.plan,history:o}),i=await e.writeCandidate({candidate:r,plan:t.plan}),await e.markCandidateWritten?.({candidate:r,plan:t.plan,history:o,receipt:i})}catch(l){return $c({candidate:r,plan:t.plan,failedStage:"commit",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let s=r;try{let l=await e.validateCandidate({candidate:r,plan:t.plan,receipt:i});l!==void 0&&(s=l)}catch(l){return $c({candidate:r,plan:t.plan,failedStage:"validate",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let a;try{a=await e.publishCandidate({candidate:s,plan:t.plan,history:o,receipt:i})}catch(l){return $c({candidate:s,plan:t.plan,failedStage:"publish",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let c={candidate:s,plan:t.plan,history:o,receipt:i,published:a};try{await e.swapCandidate?.(c)}catch(l){return Om("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return Om("finalize",l,"Transaction finalization failed after live state swap.")}try{e.emitCommitted?.({candidate:s,plan:t.plan,published:a})}catch{}return{ok:!0,stage:"publish",published:a,plan:t.plan}}function eC(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 $c(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:tC(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 Om(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function tC(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 nC(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)||_m.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=_m.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 rC=50,oC=8*1024*1024;function jm(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??rC),s=Math.max(0,t.maxUndoBytes??oC);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:f};async function a(k){let T=[...k.steps].sort((Y,ue)=>Y.order-ue.order),_=T.filter(Y=>Y.type!=="invoke-external-adapter");if(_.length!==T.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let L=new Set(_.map(Y=>Y.file)),G=await v(L),ne=new Map(G.map(Y=>[Y.file,Y.exists===!1?"":Y.content])),ve;for(let Y of _){let ue=Bm(Y,ne.get(Y.file)??"");if(!ue.ok)return{ok:!1,errorCode:ue.errorCode,reason:ue.reason};ne.set(Y.file,ue.source),ve=ue.selectionRef??ve}return{ok:!0,filePlan:{operationId:k.operationId,kind:"source-edit",target:k.target,documentVersion:k.documentVersion,conflictPolicy:"compare-and-swap",edits:[...ne].map(([Y,ue])=>({operation:"upsert",file:Y,content:ue,baseContentHash:G.find(Ae=>Ae.file===Y)?.sha256??null}))},...ve?{selectionRef:ve}:{}}}async function c(k){let T=[...k.steps].sort((Ae,zt)=>Ae.order-zt.order),_=T.filter(Ae=>Ae.type!=="invoke-external-adapter"),L=T.filter(Ae=>Ae.type==="invoke-external-adapter"),G=new Set(_.map(Ae=>Ae.file));if(_.length>0&&L.length>0)return{ok:!1,operationId:k.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(_.length===0)return E(k,L);let ne=await v(G),ve=new Map;for(let Ae of ne)ve.set(Ae.file,Ae.exists===!1?"":Ae.content);let Y;for(let Ae of _){let zt=ve.get(Ae.file)??"",Ht=Bm(Ae,zt);if(!Ht.ok)return{ok:!1,operationId:k.operationId,errorCode:Ht.errorCode,reason:Ht.reason,rolledBack:!1};ve.set(Ae.file,Ht.source),Ht.selectionRef&&(Y=Ht.selectionRef)}let ue=await w([...ve].map(([Ae,zt])=>({file:Ae,content:zt,exists:!0,version:0,sha256:be(zt)})),ne);return ue.ok===!1?{ok:!1,operationId:k.operationId,errorCode:ue.rolledBack?"writeback-failed":"rollback-failed",reason:ue.reason,rolledBack:ue.rolledBack}:(n.push({operationId:k.operationId,preSnapshots:ne,postSnapshots:ue.snapshots,plan:k}),m(),r.length=0,{ok:!0,operationId:k.operationId,kind:k.kind,target:k.target,resultVersion:Math.max(...ue.snapshots.map(Ae=>Ae.version)),affectedFiles:[...G],...Y?{selectionRef:Y}:{}})}async function l(k){let T=new Set(k.edits.map(ue=>ue.file)),_=await v(T),L=S(k,_);if(L)return{ok:!1,operationId:k.operationId,errorCode:"stale-version",reason:L.reason,affectedFiles:[L.file],rolledBack:!1};let G=new Map(_.map(ue=>[ue.file,ue])),ne=k.edits.find(ue=>ue.operation==="create-only"&&G.get(ue.file)?.exists!==!1);if(ne)return{ok:!1,operationId:k.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${ne.file}`,affectedFiles:[ne.file],rolledBack:!1};let ve=k.edits.map(ue=>ue.operation==="delete"?{file:ue.file,content:"",exists:!1,version:0}:{file:ue.file,content:ue.content,exists:!0,version:0,sha256:be(ue.content)}),Y=await w(ve,_,new Set(k.edits.filter(ue=>ue.operation==="create-only").map(ue=>ue.file)));return Y.ok===!1?{ok:!1,operationId:k.operationId,errorCode:Y.rolledBack?"writeback-failed":"rollback-failed",reason:Y.reason,rolledBack:Y.rolledBack}:(n.push({operationId:k.operationId,preSnapshots:_,postSnapshots:Y.snapshots,plan:{operationId:k.operationId,kind:k.kind,target:k.target,documentVersion:k.documentVersion,steps:[],preSnapshots:_}}),m(),r.length=0,{ok:!0,operationId:k.operationId,kind:k.kind,target:k.target,resultVersion:Math.max(...Y.snapshots.map(ue=>ue.version)),affectedFiles:[...T]})}async function u(){let k=n.at(-1);if(!k)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let T=await w(k.preSnapshots,k.postSnapshots);return T.ok===!1?{ok:!1,operationId:k.operationId,errorCode:T.rolledBack?"writeback-failed":"rollback-failed",reason:T.reason,rolledBack:T.rolledBack}:(n.pop(),r.push(k),{ok:!0,operationId:k.operationId,kind:k.plan.kind,target:k.plan.target,resultVersion:Math.max(...T.snapshots.map(_=>_.version)),affectedFiles:k.preSnapshots.map(_=>_.file)})}async function f(){let k=r.at(-1);if(!k)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let T=await w(k.postSnapshots,k.preSnapshots);return T.ok===!1?{ok:!1,operationId:k.operationId,errorCode:T.rolledBack?"writeback-failed":"rollback-failed",reason:T.reason,rolledBack:T.rolledBack}:(r.pop(),n.push(k),m(),{ok:!0,operationId:k.operationId,kind:k.plan.kind,target:k.plan.target,resultVersion:Math.max(...T.snapshots.map(_=>_.version)),affectedFiles:k.postSnapshots.map(_=>_.file)})}function m(){for(;n.length>i;)n.shift();for(;n.length>0&&d()>s;)n.shift()}function d(){return n.reduce((k,T)=>k+g(T),0)}function g(k){return h(k.preSnapshots)+h(k.postSnapshots)}function h(k){return k.reduce((T,_)=>T+_.file.length+_.content.length,0)}async function E(k,T){let _=[];for(let L of T){let G=L.capability??"write-text",ne=o.find(Y=>Y.sourceType===L.sourceType&&(L.adapterId===void 0||Y.adapterId===L.adapterId)&&(Y.capabilities===void 0||Y.capabilities.includes(G)));if(!ne)return{ok:!1,operationId:k.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${L.sourceType}`,rolledBack:!1};let ve=await ne.execute(L);if(!ve.ok)return{ok:!1,operationId:k.operationId,errorCode:"writeback-failed",reason:ve.reason??`External adapter failed for ${L.sourceType}`,rolledBack:!1};_.push(L.file)}return{ok:!0,operationId:k.operationId,kind:k.kind,target:k.target,resultVersion:0,affectedFiles:_}}function S(k,T){if(k.conflictPolicy!=="compare-and-swap")return null;let _=new Map(T.map(L=>[L.file,L]));for(let L of k.edits){if(L.operation==="create-only")continue;if(L.baseContentHash===void 0)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};let G=_.get(L.file),ne=L.baseContentHash;if(ne===null){if(G?.exists!==!1)return{file:L.file,reason:`Source file ${L.file} was created or changed before save.`};continue}if(!ne)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};if(G?.exists===!1||G?.sha256!==ne)return{file:L.file,reason:`Source file ${L.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function v(k){let T=[];for(let _ of k)T.push(await C(_));return T}async function C(k){if(!await e.exists(k))return{file:k,content:"",version:0,exists:!1};let _=Math.max(1,e.getVersion(k)),L=await e.readFile(k);return{file:k,content:L,version:_,exists:!0,sha256:be(L)}}async function w(k,T,_=new Set){let L=[];try{for(let G of k){if(_.has(G.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(G.file,G.content)}else await A(G);let ne=e.bumpVersion(G.file);L.push(G.file),G.version=ne}}catch(G){let ne=await P(T.filter(Y=>L.includes(Y.file)));if(ne.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${ne.failedFiles.join(", ")}: ${Lm(G)}`,rolledBack:!1,instanceConflict:Dm(G)};let ve=Dm(G);return{ok:!1,reason:`${ve?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Lm(G)}`,rolledBack:!0,instanceConflict:ve}}return{ok:!0,snapshots:k.map(iC)}}async function A(k){if(k.exists===!1){await e.deleteFile(k.file);return}await e.writeFile(k.file,k.content)}async function P(k){let T=[];for(let _ of k)try{await A(_),e.bumpVersion(_.file)}catch{T.push(_.file)}return T.length===0?{ok:!0}:{ok:!1,failedFiles:T}}}function Dm(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function iC(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:be(e.content)}:{}}}function Lm(e){return e instanceof Error?e.message:String(e)}function Bm(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 ze(Vn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return ze(Un({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return ze(Ln({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return ze(Bn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return ze(Fo({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return ze(vr({source:t,locator:e.locator,next:e.value}));case"update-array-item":return ze(vr({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return ze(Bo({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return ze(Oo({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return ze(jo({source:t,locator:e.locator,index:e.index}));case"move-array-item":return ze($o({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return ze(jn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return ze(Mo({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 sC(e,t);case"set-property-changes":return ze(Do({source:t,locator:e.locator,changes:e.changes}));case"set-property-binding":return ze(Lo({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return ze(Uo({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function sC(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!wu(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!==be(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:Ru({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function ze(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 Ji,SiteEditCompositionContextSchema as aC,SiteEditCompositionSelectorSchema as cC}from"@vcp-dev/contracts";var He=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function $m(e,t){throw new He("INVALID_COMPOSITION",e,{value:t})}function Xi(e){let t=aC.safeParse(e);return t.success?t.data:$m("Invalid SiteEditCompositionContext.",e)}function Vm(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=Xi(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new He("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=Ji(u);if(n.has(f))throw new He("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:u});let m=r.get(l.entryFile);if(m)throw new He("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:m});let d={context:u,entryFile:l.entryFile,key:f};t.push(d),n.set(f,d),r.set(l.entryFile,f)}if(t.length===0)throw new He("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=Xi(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new He("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let f=Ji(u);if(!n.has(f))throw new He("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:f});if(o.has(f))throw new He("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:f});o.set(f,l.version)}function i(l){let u=cC.safeParse(l);if(!u.success)return $m("Invalid SiteEditCompositionSelector.",l);let f=t.filter(({context:m})=>m.routeId===u.data.routeId&&(u.data.templateId===void 0?m.effectiveTemplateId===void 0:m.effectiveTemplateId===u.data.templateId));if(f.length===1)return f[0];throw f.length>1?new He("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new He("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=Xi(l),f=Ji(u),m=n.get(f);if(!m)throw new He("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:f});return m}function a(l){let u=Xi(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new He("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=Ji(u),m=n.get(f);if(m){if(m.entryFile===l.entryFile)return m;throw new He("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:u})}let d=[...n.values()].find(h=>h.entryFile===l.entryFile);if(d)throw new He("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:d.context});let g={context:u,entryFile:l.entryFile,key:f};return t.push(g),n.set(f,g),g}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let f=t.findIndex(m=>m.key===l);return f>=0&&t.splice(f,1),o.delete(l),u}return{entries:t,byKey:n,initialVersions:o,register:a,unregister:c,resolveSelector:i,resolveContext:s,getByKey:l=>n.get(l),routeIds:()=>[...new Set(t.map(({context:l})=>l.routeId))]}}import{composeSiteEditRepeatInstanceKey as lC,stripSiteEditRepeatInstanceKeys as Um}from"@vcp-dev/contracts";function Km(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Um(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 uC(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 zi(e){return e?.map(t=>({...t}))}function Uc(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=zi(e.collectionPathMap?.[t])??zi(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:zi(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>zi(o)??[])}}function Jm(e,t,n){let r=new Set;for(let d of t.regions)if(d.kind==="repeat-region")for(let g of d.childKeys)r.add(g);if(r.size===0)return e;let o=new Map(e.entries.map(d=>[d.key,d])),i=[],s=new Map,a=(d,g)=>lC(d,g),c=(d,g,h)=>{let E=o.get(d);if(!E)return a(d,h);let S=a(d,h),v={...E,key:S,parentKey:g,childKeys:[]};return i.push(v),v.childKeys=E.childKeys.flatMap(C=>l(C,h,S)),S},l=(d,g,h)=>{if(!r.has(d))return[c(d,h,g)];let E=f(d,g),S=[];for(let v=0;v<E;v+=1)S.push(c(d,h,[...g,v]));return S},u=Array.from(new Set([...e.rootKeys,...e.entries.filter(d=>d.parentKey===null).map(d=>d.key)]));for(let d of u){if(!r.has(d)){c(d,null,[]);continue}let g=f(d,[]);for(let h=0;h<g;h+=1)c(d,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function f(d,g){let h=new Set;for(let E of m(d)){let S=n.get(E);if(S){for(let v of[...S.textTargets.values(),...S.elementPropertyTargets.values()])if(!(v?.kind!=="value-binding"||v.sourceKind!=="repeat-template"))for(let C of dC(v))C.length<=g.length||fC(C,g)&&h.add(C[g.length])}}return h.size>0?h.size:uC(n.get(d))}function m(d){let g=s.get(d);if(g)return g;let h=[d],E=o.get(d);for(let S of E?.childKeys??[])h.push(...m(S));return s.set(d,h),h}}function Xm(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function zm(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((Um(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function dC(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 fC(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 Hm(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(u=>[u.key,u])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let u=o.get(a);if(!u)break;s.push({key:u.key,tag:u.tag,label:u.label}),a=u.parentKey}s.reverse();let c=i.childKeys.map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label})),l=i.parentKey===null?[]:(o.get(i.parentKey)?.childKeys??[]).filter(u=>u!==i.key).map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label}));return{...e,key:i.key,ancestors:s,children:c,siblings:l}}function Wm(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(c=>[c.key,c])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let c=o.get(a);if(!c)break;s.push({key:c.key,tag:c.tag,label:c.label}),a=c.parentKey}return s.reverse(),{...e,key:i.key,ancestors:s}}function Gm(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function pC(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var co=class extends Error{constructor(t){let n=t.map(Gm);super(pC(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Ym(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof co?{routeId:e,message:n,diagnostics:t.diagnostics.map(Gm)}:{routeId:e,message:n}}function Kc(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Jc(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function cr(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Zm(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function Xc(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 Qm(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((l,u)=>l.preDigest===r[u]),i=t.files.every((l,u)=>l.postDigest===r[u]),s=t.historyTransition,a=n.digest===s.expectedIndexDigest,c=n.digest===s.publishedIndexDigest&&n.cursor===s.publishedCursor&&n.currentId===s.publishedCurrentId;return o&&a?"safely-uncommitted":i&&c?"durably-committed":"ambiguous"}var SC=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,EC=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],qm=32,eg=256;function vC(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var tg={maxEntries:50,maxBytes:8*1024*1024};function IC(){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 Jo(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}}}function kC(){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>tg.maxEntries||CC(e)>tg.maxBytes;)e.shift()}}function CC(e){return e.reduce((t,n)=>t+RC(n),0)}function RC(e){return ng(e.preSnapshots)+ng(e.postSnapshots)+wC(e.provenance)}function wC(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function ng(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function rg(e,t){return{key:mC(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document:null,pageComposition:null,pageCompositionProjection:null,documentIndex:null,pagePlacementByKey:null,pagePlacementUnitByKey:null,pageUnitByKey:null,pagePlacementsByUnitKey:null,dependencyFiles:new Set([t]),detailProjections:null,fileVersions:new Map,styleContext:null}}var Wi=class extends Error{constructor(t){super(t.reason),this.result=t}},Fn=class extends Error{constructor(t){super(Kc(t)),this.failedRoutes=t}};function og(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=yt(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(yt(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function NC(e,t,n){if(!n)return;let r=yt(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 PC=/\.(?:[cm]?[jt]sx?)$/i,AC=/\.json$/i,TC=/\.(?:css|scss|sass)$/i,FC=/\.mdx$/i,_C=/\.ya?ml$/i;function OC(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 MC(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function DC(e,t){let n=new Map;for(let r of t)n.set(r.path,r.operation==="delete"?{exists:!1}:{exists:!0,content:r.content});return{async readFile(r){let o=n.get(r);if(o){if(!o.exists)throw new Error(`Source file not found: ${r}`);return o.content}return e.readFile(r)},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(r){let o=n.get(r);return o?o.exists:e.exists(r)},async getFileInfo(r){let o=n.get(r);return o?o.exists?{path:r,sizeBytes:Buffer.byteLength(o.content,"utf8")}:null:e.getFileInfo?.(r)??null},async listFiles(r={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let o=lg(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(LC(a,r.roots??[])){if(!c.exists){i.delete(a);continue}i.set(a,{path:a,sizeBytes:Buffer.byteLength(c.content,"utf8")})}let s=[...i.values()].sort((a,c)=>a.path.localeCompare(c.path));return o.truncated?{files:s,truncated:o.truncated}:s},getVersion(r){return e.getVersion(r)},bumpVersion(r){return e.getVersion(r)}}}function LC(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function lg(e){return Array.isArray(e)?{files:e}:e}function BC(e){if(!hC(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!==xC||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=gC(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(PC.test(e.path)){let t=Rt({source:e.content,profile:pn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(AC.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Ge(t)}`,details:{path:e.path}}}if(TC.test(e.path)){let t=ig({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(FC.test(e.path)){let t=ig({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(_C.test(e.path))try{bC(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Ge(t)}`,details:{path:e.path}}}return{ok:!0}}function ig({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let f=0;f<e.length;f+=1){let m=e[f]??"",d=e[f+1]??"";if(n==="mdx"&&l&&e.startsWith("```",f)){c=!c;let g=e.indexOf(`
1
+ import{SiteEditOperationRequestSchema as bR,SiteEditPatchPlanSchema as SR}from"@vcp-dev/contracts";function dn(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function Io(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 ko(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,...n.pageCompositionUnitKey?{pageCompositionUnitKey:n.pageCompositionUnitKey}:{},operationSummary:{canUpdateText:n.operationSummary.canUpdateText,canInsertChild:n.operationSummary.canInsertChild,canMove:n.operationSummary.canMove,canRemove:n.operationSummary.canRemove},...n.dynamicDataSummary?{dynamicDataSummary:n.dynamicDataSummary}:{}})),pageComposition:e.pageComposition.status==="unsupported"?{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics}:{status:"supported",containerKey:e.pageComposition.container.key,hasBusinessMembers:e.pageComposition.businessMembers.length>0,placementUnitKeys:e.pageComposition.placementUnits.map(n=>n.key),placements:e.pageComposition.placements.map(n=>({placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,relation:n.relation}))}}}function Co(e){return{composition:e.composition,key:e.key,tag:e.tag,label:e.label,sourceLocator:e.sourceLocator,isOpaque:e.isOpaque,ancestors:e.ancestors,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:dh(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 Ro(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:dn(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 dh(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 OC,computeSiteEditCompositionKey as MC,getSiteEditSourceDeleteProtectionReason as DC,isSiteEditTextSourcePath as LC,parseSiteEditRepeatInstanceKey as BC,SITE_EDIT_SOURCE_DELETE_CAPABILITY as jC,stripSiteEditRepeatInstanceKeys as yt}from"@vcp-dev/contracts";import Yi from"node:path";import{parse as $C}from"yaml";import Ss from"node:path";import{TextDecoder as ph}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Xl,SITE_EDIT_SOURCE_ALLOWED_DIRS as zl,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Hl,SiteEditCompositionContextSchema as mh,SiteEditSourceFileResponseSchema as hs,SiteEditSourceLocationSchema as gh,SiteEditSourcePathSchema as wo,SiteEditSourceTreeResponseSchema as hh,isSiteEditTextSourcePath as yh}from"@vcp-dev/contracts";import{createHash as fh}from"node:crypto";var pr=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function be(e){return`sha256:${fh("sha256").update(e).digest("hex")}`}var xh=[...Hl,...Xl,...zl];function Es(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return mh.parse(e.composition)}var ys=2e3,xs=12,bs=24*1024*1024,Jl=512*1024,bh=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),Sh={".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"},Eh={".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"},vh=new ph("utf-8",{fatal:!0});async function No(e,t={}){let n=Es(t),{files:r,truncated:o}=await Ph(e,t),i=Fh(r.map(s=>s.metadata));return hh.parse({composition:n,nodes:i,defaultPath:_h(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Po(e,t,n={}){let r=Es(n),o=wo.parse(t.path),i=await kh(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Is(o)){let a=Yl(o),c=await Rh(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return hs.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await vs(e,o);return s.ok?hs.parse({composition:r,path:o,kind:"text",language:Zl(o),sizeBytes:s.sizeBytes,contentHash:be(s.content),readonly:!1,content:s.content}):hs.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function vs(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=Ih(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 Ih(e){if(e.includes(0))return null;try{return vh.decode(e)}catch{return null}}async function kh(e,t,n){if(!wh(t,n))return null;let r=await Ch(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function Ch(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Wl(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(Is(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function Rh(e,t){if(!bh.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Jl)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Jl?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function wh(e,t){return Hl.some(n=>n===e)||Xl.some(n=>n===e)||zl.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=wo.safeParse(n);return r.success&&r.data===e})}function Ao(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return gh.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 Wl(e){return Array.isArray(e)?{files:e}:e}function Nh(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function Ph(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Wl(await e.listFiles({roots:Ah(t),maxFiles:ys+1,maxDepth:xs,maxTotalBytes:bs+1})),r=new Map,o=new Set(n.truncated?.reasons),i=0;for(let a of[...n.files].sort((c,l)=>c.path.localeCompare(l.path))){let c=wo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>xs){o.add("max-depth");continue}if(r.size>=ys){o.add("max-files");break}if(i+a.sizeBytes>bs){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:Th(l,a.sizeBytes,Es(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:Nh([...o]),maxFiles:ys,maxDepth:xs,maxTotalBytes:bs}}:{}}}function Ah(e){let t=new Set(xh);for(let n of e.routeEntryFiles??[]){let r=wo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function Th(e,t,n){return Is(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Yl(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Zl(e),sizeBytes:t,readonly:!1}}function Fh(e){let t=[];for(let n of e){let r=n.path.split("/"),o=t,i="";for(let[s,a]of r.entries()){i=i?`${i}/${a}`:a;let c=s===r.length-1,l=o.find(u=>u.name===a);if(l||(l=c?{kind:"file",name:a,path:i,file:n}:{kind:"directory",name:a,path:i,children:[]},o.push(l)),c){if(l.kind!=="file")throw new Error(`Source tree path collision: ${n.path}`);l.file=n}else{if(l.kind!=="directory")throw new Error(`Source tree path collision: ${n.path}`);o=l.children}}}return Gl(t)}function Gl(e){return e.map(t=>t.kind==="directory"?{...t,children:Gl(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function _h(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 Is(e){return!yh(e)}function Yl(e){let t=Ss.posix.extname(e).toLowerCase();return!t&&Ss.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":Sh[t]??"application/octet-stream"}function Zl(e){let t=Ss.posix.extname(e).toLowerCase();return Eh[t]??"plaintext"}import*as Ql from"@babel/parser";function fn(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function $(e,t,n,r,o){return{ok:!1,source:e,diagnostic:fn(t,n,r,o)}}function ks(e,t,n,r,o){return{ok:!1,source:e,diagnostic:fn(t,n,r,o)}}var Oh={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Rt(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Ql.parse(t,{sourceType:"module",plugins:Oh[n]})}}catch(r){return{ok:!1,source:t,diagnostic:fn("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Cs(e,t){return Rt({source:e,profile:ql(t.kind)})}function mr(e,t){return Rt({source:e,profile:ql(t)})}function ql(e){return"next-app-entry"}function pn(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"}import Rs from"@babel/traverse";import*as wt from"@babel/types";function Oe(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(wt.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(wt.isIdentifier(s)&&s.name==="Fragment"||wt.isStringLiteral(s)&&s.value==="Fragment")&&eu(i.parentPath)}if(!wt.isJSXMemberExpression(t)||!wt.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!wt.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())&&eu(r.parentPath)}function eu(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var Wt=typeof Rs=="function"?Rs:Rs.default,To=new WeakMap,tu=new WeakMap;function Nt(e,t){let n=Cs(e,t);if(!n.ok)return ks(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=ie(n.ast,t);return r.ok?{ok:!0,match:{locatorKind:r.match.locatorKind,node:r.match.node,start:r.match.start,end:r.match.end}}:ks(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ie(e,t){return t.kind==="jsx-node"?iu(e,t):t.kind==="jsx-attribute"?$h(e,t):t.kind==="value"?Vh(e,t):t.kind==="expression"?Uh(e,t):t.kind==="directive"?Kh(e,t):t.kind==="export"?Jh(e,t):{ok:!1,diagnostic:fn("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function iu(e,t){return t.strategy==="source-range"?Mh(e,t):Dh(e,t)}function Mh(e,t){let n=null;if(Wt(e,{JSXElement(o){if(!mn(o.node,t.sourceRange))return;let i=_e("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!mn(o.node,t.sourceRange))return;let i=_e("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!mn(o.node,t.sourceRange))return;let i=_e("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!mn(o.node,t.sourceRange))return;let i=_e("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Me("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!ny(r.path,t.expectedIdentity)?Me("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function Dh(e,t){if(t.structuralPath===""){let r=Bh(e,t.component);if(r){let o=jh(r);if(o)return o}}let n=null;return Wt(e,{JSXElement(r){if(hr(r)!==t.component||Ns(r)!==t.structuralPath)return;let i=_e("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(hr(r)!==t.component||Ns(r)!==t.structuralPath)return;let i=_e("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Lh(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Me("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Lh(e,t,n){let r=null;return Wt(e,{JSXElement(o){if(hr(o)!==t||!mn(o.node,n))return;let i=_e("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(hr(o)!==t||!mn(o.node,n))return;let i=_e("jsx-node",o);i&&(r=i,o.stop())}}),r}function Bh(e,t){let n=null;return Wt(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 jh(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 Me("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Me("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 Me("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function $h(e,t){let n=iu(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>ry(c,t.name));if(!s||!s.isJSXAttribute())return Me("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=_e("jsx-attribute",s);return a?{ok:!0,match:a}:Me("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function Vh(e,t){let n=Xh(e,t);if(!n.ok)return n;let r=zh(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Ut(r.match.path.node.loc,t.expectedRange)?Me("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function Uh(e,t){let n=null;return Wt(e,{Identifier(r){if(!Qh(r))return;let o=ru(r);if(!o||!ou(o,t))return;let i=_e("expression",r);i&&(t.expectedRange&&!Ut(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=ru(r);if(!o||!ou(o,t))return;let i=_e("expression",r);i&&(t.expectedRange&&!Ut(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Me("expression","locator-miss","Expression not found")}function Kh(e,t){let n=null;return Wt(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Ut(i.node.loc,t.expectedRange))return;let s=_e("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Me("directive","locator-miss",`Directive '${t.value}' not found`)}function Jh(e,t){let n=null;return Wt(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let m=_e("export",c);if(!m||t.expectedRange&&!Ut(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=Ps(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let f=_e("export",u);if(!f||t.expectedRange&&!Ut(u.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Ps(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Ut(s.node.loc,t.expectedRange))return;let a=_e("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=_e("export",o);i&&(t.expectedRange&&!Ut(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Me("export","export-not-found",`Export '${ty(t)}' not found`)}function Xh(e,t){let n=null;return Wt(e,{Expression(r){if(n||t.root.kind!=="expression"||!mn(r.node,t.root.sourceRange))return;let o=_e("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 d=r.get("init");if(!d.node)return;let g=_e("value",d);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(d=>d?.type==="Identifier"&&d.name===o.name)!==0)return;let c=s.node.callee;if((c.type==="Identifier"?c.name:c.type==="MemberExpression"&&c.property.type==="Identifier"?c.property.name:null)!==o.hook)return;let u=o.hook==="useReducer"?1:0,f=r.get(`init.arguments.${u}`);if(!f||Array.isArray(f)||!f.node)return;let m=_e("value",f);m&&(n=m,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Ps(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=_e("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=_e("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:Me("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 zh(e,t){let n=ws(e);for(let o of t){if(n=ws(n),o.kind==="property"){if(!n.isObjectExpression())return Me("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return Me("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>oy(l,o.name));if(!c||!c.isObjectProperty())return Me("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return Me("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return Me("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return Me("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=ws(n);let r=_e("value",n);return r?{ok:!0,match:r}:Me("value","locator-miss","Resolved value has no source range")}function ws(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function _e(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 mn(e,t){return Ut(e.loc,t)}function Ut(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 Ns(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Oe(n)){let o=su(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${nu(n,o)}`):t.unshift(`${o}#${nu(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Yh(n.parentPath)&&!Zh(n.parentPath))break;n=n.parentPath}return t.join("/")}function nu(e,t){let n=Hh(e);if(!n)return 0;let r=To.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=To.get(n.node)?.get(t);if(!i){let s=To.get(n.node);s||(s=new Map,To.set(n.node,s)),i=new WeakMap,s.set(t,i)}for(let s of gr(n))if(su(s.node.openingElement)===t){if(i.set(s.node,o),s.node===e.node)return o;o++}return i.get(e.node)??0}function Hh(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Oe(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function gr(e){let t=tu.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(Oe(o)){n.push(...gr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...gr(o));continue}o.isJSXExpressionContainer()&&n.push(...Vt(o.get("expression")))}return tu.set(e.node,n),n}function Vt(e){if(e.isJSXElement())return Oe(e)?gr(e):[e];if(e.isJSXFragment())return gr(e);if(e.isParenthesizedExpression())return Vt(e.get("expression"));if(e.isLogicalExpression()&&Wh(e.node.operator))return Vt(e.get("right"));if(e.isCallExpression()||e.isOptionalCallExpression()){let t=e.get("callee"),n=!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())?t.get("property"):null;if(!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())&&!t.node.computed&&n!==null&&!Array.isArray(n)&&n.isIdentifier()&&n.node.name==="map"){let r=e.get("arguments").find(o=>!Array.isArray(o)&&(o.isArrowFunctionExpression()||o.isFunctionExpression()));if(r&&!Array.isArray(r)){let o=r.get("body");if(!Array.isArray(o)){if(o.isBlockStatement()){let i=[];for(let s of o.get("body")){if(s.isVariableDeclaration())for(let a of s.get("declarations")){let c=a.get("init");(c.isJSXElement()||c.isJSXFragment())&&i.push(...Vt(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Vt(a));break}}return i}else if(o.node&&o.isExpression())return Vt(o)}}}}return e.isConditionalExpression()?[...Vt(e.get("consequent")),...Vt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Vt(t)):[]}function Wh(e){return e==="&&"||e==="||"||e==="??"}function su(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Gh(e.name):null}function Gh(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 hr(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 Yh(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Zh(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 Qh(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function ru(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 ou(e,t){return e.base===t.base&&qh(e.path,t.path??[])}function qh(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 ey(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function ty(e){return e.exportKind==="named"?e.name:e.exportKind}function Me(e,t,n,r){return{ok:!1,diagnostic:fn(t,n,e,r)}}function ny(e,t){return hr(e)!==t.component?!1:Ns(e)===t.structuralPath}function ry(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Ps(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function oy(e,t){return e.isObjectProperty()?ey(e.node)===t:!1}import*as cu from"@babel/parser";import{arrayExpression as ly,booleanLiteral as uy,identifier as dy,jsxAttribute as fy,jsxExpressionContainer as py,jsxIdentifier as my,nullLiteral as gy,numericLiteral as hy,objectExpression as yy,objectProperty as xy,stringLiteral as Ts}from"@babel/types";import As from"@babel/generator";var iy=typeof As=="function"?As:As.default;function sy(e){let t=e.split(`
2
+ `),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let c=a[1];c.includes(" ")?r=!0:c.length>0&&n.push(c.length)}}if(r&&t.every(a=>{let c=a.match(/^(\s+)/);return!c||c[1].includes(" ")}))return"tab";if(n.length===0)return"2";function o(s,a){return a===0?s:o(a,s%a)}let i=n[0];for(let s=1;s<n.length;s++)i=o(i,n[s]);return i>=4?"4":"2"}function ay(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 cy(e,t){return e.split(`
3
+ `).map(r=>ay(r,t)).join(`
4
+ `)}function Fo(e){let{ast:t,source:n}=e;try{let r=sy(n),i=iy(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=cy(i,r)),{ok:!0,source:i}}catch(r){return $(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function au(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 yr(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:au(e),afterSourceHash:au(t),inverse:n.inverse}}}function fe(e,t,n){let r=Fo({ast:e,source:t});return r.ok?yr(t,r.source,n):r}function ke(e,t){let n=mr(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function _o(e,t){return Fo({ast:e,source:t})}function by(e,t,n){let r=ie(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Oo(e,t,n){let r=by(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:$(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function Gt(e){return typeof e=="string"?Ts(e):typeof e=="number"?hy(e):typeof e=="boolean"?uy(e):e===null?gy():Array.isArray(e)?ly(e.map(t=>Gt(t))):yy(Object.entries(e).map(([t,n])=>{let r=xy(Fs(t),Gt(n));return t==="__proto__"&&(r.computed=!0),r}))}function Sy(e){return typeof e=="string"?Ts(e):py(Gt(e))}function xr(e,t){return fy(my(e),Sy(t))}function Mo(e,t){try{let r=cu.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:$(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:$(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Fs(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?dy(e):Ts(e)}function Do(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=ke(t,"jsx-node");if(!i.ok)return i.result;let s=ie(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=Ey(s.match.path)[r];if(!c)return $(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=vy(c.path.node.value,o);break;case"string-literal":c.path.node.value=o;break;case"template-literal":{let l=c.quasiIndex;c.path.node.quasis[l].value.raw=o,c.path.node.quasis[l].value.cooked=o;break}}return fe(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function Ey(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=Iy(r.get("expression"));o.length>0&&t.push(...o)}}return t}function vy(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Iy(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&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as _s}from"@babel/types";function Ln(e){let{source:t,locator:n}=e,r=ke(t,"jsx-node");if(!r.ok)return r.result;let o=ie(r.ast,n);return o.ok?(ky(o.match.path),fe(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function ky(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(_s());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(_s());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(_s());return}e.remove()}import{cloneNode as Cy}from"@babel/types";function Lo(e){let t=ke(e.source,"jsx-node");if(!t.ok)return t.result;let n=ie(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=Mo(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(Cy(r.node,!0)),fe(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as Dy}from"@babel/types";import Os from"@babel/traverse";import*as Z from"@babel/types";function br(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 Ry=typeof Os=="function"?Os:Os.default;function ft(e,t,n,r){if(!e.ok)return e;let o=dt(n,t);if(!o)return e;let i=wy(t,o,r);return i?{...e,selectionRef:i}:e}function wy(e,t,n){let r=Ny(e,t);if(!r)return;let o=n.sourceLocator?lu(n.sourceLocator):void 0,i=n.targetParentLocator?lu(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??Ay(r)??i?.component??o?.component;if(!(!s||!a))return{key:br(s,a,Ty(r))}}function lu(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Ny(e,t){let n=gu(e,t);return!n||n.node.type!=="JSXElement"?null:n}function gu(e,t){let n=null;return Ry(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function dt(e,t){if(!e)return null;if(Z.isJSXElement(e))return My(t,e)?uu(e.children,t):e;if(Z.isJSXFragment(e))return uu(e.children,t);if(Z.isJSXExpressionContainer(e)||Z.isParenthesizedExpression(e)||Z.isTSAsExpression(e)||Z.isTSSatisfiesExpression(e)||Z.isTSTypeAssertion(e)||Z.isTSNonNullExpression(e))return dt(e.expression,t);if(Z.isLogicalExpression(e))return dt(e.right,t);if(Z.isConditionalExpression(e))return dt(e.consequent,t)??dt(e.alternate,t);if(Z.isCallExpression(e)||Z.isOptionalCallExpression(e))return hu(e)?Py(e.arguments[0],t):null;if(Z.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=dt(n,t);if(r)return r}return null}function uu(e,t){for(let n of e){let r=dt(n,t);if(r)return r}return null}function Py(e,t){return!e||!Z.isArrowFunctionExpression(e)&&!Z.isFunctionExpression(e)?null:Z.isBlockStatement(e.body)?Sr(e.body.body,t):dt(e.body,t)}function Sr(e,t){for(let n of e){if(Z.isReturnStatement(n)){let r=dt(n.argument,t);if(r)return r;continue}if(Z.isBlockStatement(n)){let r=Sr(n.body,t);if(r)return r;continue}if(Z.isIfStatement(n)){let r=du(n.consequent,t);if(r)return r;let o=n.alternate?du(n.alternate,t):null;if(o)return o;continue}if(Z.isSwitchStatement(n))for(let r of n.cases){let o=Sr(r.consequent,t);if(o)return o}}return null}function du(e,t){return Z.isBlockStatement(e)?Sr(e.body,t):Sr([e],t)}function Ay(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(Z.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&Z.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 fu=new WeakMap,pu=new WeakMap,Ms=new WeakMap;function Ty(e){let t=fu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Fy(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return fu.set(e.node,o),o}function Fy(e){let t=yu(e.node.openingElement.name);return!t||Oe(e)?null:/^[A-Z]/.test(t)?`component:${t}#${mu(e,t)}`:`${t}#${mu(e,t)}`}function mu(e,t){let n=_y(e);if(!n)return 0;let r=Ms.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Ms.get(n.node);o||(o=new Map,Ms.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of gn(n))if(yu(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 _y(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Oe(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function gn(e){let t=pu.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(Oe(o)){n.push(...gn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...gn(o));continue}o.isJSXExpressionContainer()&&n.push(...Pt(o.get("expression")))}return pu.set(e.node,n),n}function Pt(e){if(e.isJSXElement())return Oe(e)?gn(e):[e];if(e.isJSXFragment())return gn(e);if(e.isParenthesizedExpression())return Pt(e.get("expression"));if(e.isLogicalExpression())return Pt(e.get("right"));if(e.isConditionalExpression())return[...Pt(e.get("consequent")),...Pt(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Pt(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&hu(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?Oy(n):[]}return[]}function Oy(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Oe(t)?gn(t):[t];if(t.isJSXFragment())return gn(t);if(t.isParenthesizedExpression())return Pt(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Pt(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(...Pt(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...Pt(o)),n}return n}function hu(e){let t=e.callee;return(Z.isMemberExpression(t)||Z.isOptionalMemberExpression(t))&&Z.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function My(e,t){let n=gu(e,t);return n?Oe(n):!1}function yu(e){return Z.isJSXIdentifier(e)?e.name:Z.isJSXMemberExpression(e)?xu(e):Z.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function xu(e){return`${Z.isJSXIdentifier(e.object)?e.object.name:xu(e.object)}.${e.property.name}`}function Yt(e,t){if(t.parentPath===e&&t.listKey==="children"&&Ds(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!Ds(n))return null;let r=n;for(;r&&r!==e;){if(!Ds(r)||!Oe(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function Ds(e){return e.isJSXElement()||e.isJSXFragment()}function Bn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ke(t,"jsx-node");if(!a.ok)return a.result;let c=ie(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return $(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let l=c.match.path;if(c.match.path.isJSXElement()){let C=c.match.path.node;if(!C.closingElement||C.openingElement.selfClosing)return $(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=Mo(t,r.jsx);if(!u.ok)return u.result;let f=Dy(u.node,!0),m=l.node.children,d={...s,targetParentLocator:n},g=C=>s?ft(C,a.ast,f,d):C;if(o==="append")return m.push(f),g(fe(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(f),g(fe(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=ie(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let E=Yt(c.match.path,h.match.path);if(!E)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=E;let S=l.node.children,v=S.findIndex(C=>C===h.match.path.node);return v===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(S.splice(o==="before"?v:v+1,0,f),g(fe(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as bu from"@babel/parser";import{cloneNode as Ly}from"@babel/types";function Bo(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ke(t,"jsx-node");if(!a.ok)return a.result;let c=By(t,r);if(!c.ok)return c.result;let l=ie(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return $(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let S=l.match.path.node;if(!S.closingElement||S.openingElement.selfClosing)return $(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,f=null;if(i){let S=ie(a.ast,i);if(!S.ok)return{ok:!1,source:t,diagnostic:S.diagnostic};let v=Yt(l.match.path,S.match.path);if(!v)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=v,f=S.match.path.node}else if(o==="before"||o==="after")return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=Ly(c.node,!0),d=u.node.children,g={...s,targetParentLocator:n},h=S=>s?ft(S,a.ast,m,g):S;if(o==="append")return d.push(m),h(fe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return d.unshift(m),h(fe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let E=d.findIndex(S=>S===f);return E===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(d.splice(o==="before"?E:E+1,0,m),h(fe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function By(e,t){try{let r=bu.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:$(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:$(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as jy,nullLiteral as Ls}from"@babel/types";import*as Zt from"@babel/types";function jn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ke(t,"jsx-node");if(!a.ok)return a.result;let c=ie(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=ie(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return $(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let u=l.match.path;if(l.match.path.isJSXElement()){let v=l.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return $(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let f=null;if(i){let v=ie(a.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let C=Yt(l.match.path,v.match.path);if(!C)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=C,f=v.match.path}else if(o==="before"||o==="after")return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=f&&typeof f.key=="number"?f.key:-1;if(f&&m===-1)return $(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let d=jy(c.match.path.node,!0);if(!Zt.isJSXElement(d)&&!Zt.isJSXExpressionContainer(d)&&!Zt.isJSXFragment(d)&&!Zt.isJSXText(d))return $(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let g=c.match.path.parentPath?.node===u.node&&typeof c.match.path.key=="number"?c.match.path.key:-1;if(f&&c.match.path.parentPath?.node===f.parentPath?.node&&c.match.path.key===f.key)return $(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");$y(c.match.path);let h=u.node.children,E={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return h.push(d),ft(_o(a.ast,t),a.ast,d,E);if(o==="prepend")return h.unshift(d),ft(_o(a.ast,t),a.ast,d,E);let S=m-(g!==-1&&g<m?1:0);return h.splice(o==="before"?S:S+1,0,d),ft(_o(a.ast,t),a.ast,d,E)}function $y(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ls());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ls());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ls());return}e.remove()}import*as Su from"@babel/parser";import{cloneNode as Vy,nullLiteral as Bs}from"@babel/types";function jo(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=ke(t,"jsx-node");if(!c.ok)return c.result;let l=Uy(t,s);if(!l.ok)return l.result;let u=ie(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let f=ie(c.ast,r);if(!f.ok)return{ok:!1,source:t,diagnostic:f.diagnostic};if(!f.match.path.isJSXElement()&&!f.match.path.isJSXFragment())return $(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(f.match.path.isJSXElement()){let C=f.match.path.node;if(!C.closingElement||C.openingElement.selfClosing)return $(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=f.match.path,d=null;if(i){let C=ie(c.ast,i);if(!C.ok)return{ok:!1,source:t,diagnostic:C.diagnostic};let N=Yt(f.match.path,C.match.path);if(!N)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=N,d=C.match.path.node}else if(o==="before"||o==="after")return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return $(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=m.node,h=Vy(l.node,!0);Ky(u.match.path);let E={...a,sourceLocator:n,targetParentLocator:r},S=g.children;if(o==="append")return S.push(h),ft(fe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,E);if(o==="prepend")return S.unshift(h),ft(fe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,E);let v=S.findIndex(C=>C===d);return v===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(S.splice(o==="before"?v:v+1,0,h),ft(fe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,E))}function Uy(e,t){try{let r=Su.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:$(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:$(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Ky(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Bs());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Bs());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Bs());return}e.remove()}import{SiteEditSetPropsParamsSchema as Jy,classifySiteEditPropertyName as Xy}from"@vcp-dev/contracts";import*as $n from"@babel/types";function $o(e){let t=Jy.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return $(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=ke(e.source,"jsx-node");if(!n.ok)return n.result;let r=Oo(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=Xy(a.name);if(c.owner!=="generic")return $(e.source,"unsupported-syntax",c.diagnostic?.message??`Property '${a.name}' is not owned by the generic JSX primitive`,"jsx-node")}let o=r.match.path.node.openingElement,i=o.attributes.filter($n.isJSXAttribute),s=new Map;for(let a of i){let c=zy(a);if(!c)continue;let l=s.get(c)??[];l.push(a),s.set(c,l)}for(let a of t.data.changes)if((s.get(a.name)??[]).length>1)return $(e.source,"unsupported-syntax",`JSX attribute '${a.name}' has multiple sources`,"jsx-node");for(let a of t.data.changes){let c=s.get(a.name)?.[0];if(a.operation==="remove"){c&&(o.attributes=o.attributes.filter(u=>u!==c));continue}let l=xr(a.name,a.value).value;c?c.value=l:o.attributes.push(xr(a.name,a.value))}return fe(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function zy(e){return $n.isJSXIdentifier(e.name)?e.name.name:$n.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import*as je from"@babel/types";import{classifySiteEditPropertyName as Eu}from"@vcp-dev/contracts";function Vo(e){let t=Eu(e.name),n=Eu(e.property);if(t.owner!=="generic"||n.owner!=="generic")return $(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!vu(e.object))return $(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return $(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=ke(e.source,"jsx-node");if(!r.ok)return r.result;let o=Oo(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>je.isJSXAttribute(l)&&Wy(l)===e.name);if(s.length>1)return $(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=Hy(e.object,e.property),c=s[0];if(c)c.value=je.jsxExpressionContainer(a);else{let l=xr(e.name,"");l.value=je.jsxExpressionContainer(a),i.attributes.push(l)}return fe(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function Hy(e,t){return vu(t)?je.memberExpression(je.identifier(e),je.identifier(t)):je.memberExpression(je.identifier(e),je.stringLiteral(t),!0)}function vu(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function Wy(e){return je.isJSXIdentifier(e.name)?e.name.name:je.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as Yy,identifier as Er,importDeclaration as Zy,importDefaultSpecifier as Qy,importNamespaceSpecifier as qy,importSpecifier as ex,isImportDefaultSpecifier as Iu,isImportNamespaceSpecifier as ku,isImportSpecifier as Cu,stringLiteral as tx}from"@babel/types";function Vn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(E=>!ux(E));if(o!==-1){let E=r[o],S=E&&typeof E=="object"&&"kind"in E?E.kind:void 0;return $(t,"unsupported-syntax",`Unsupported import spec kind: ${String(S)}`)}let i=ax(r);if(!i.ok)return $(t,"unsupported-syntax",i.message);let s=ke(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(E=>E.type==="ImportDeclaration"&&E.source.value===n),u=new Set(l.flatMap(E=>E.specifiers.flatMap(S=>{let v=dx(E,S);return v?[v]:[]}))),f=i.imports.filter(E=>!u.has(Tu(E)));if(f.length===0)return yr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=cx(c.body),d=f.find(E=>m.has(js(E)));if(d)return $(t,"unsupported-syntax",`Import local binding already exists: ${js(d)}`);let g=sx(f);if(g.reduce((E,S)=>E+S.length,0)!==f.length)return $(t,"unsupported-syntax","Unsupported import specifier grouping");for(let E of g){if(!Pu(wu(E)))return $(t,"unsupported-syntax","Unsupported import specifier combination");let S=l.find(v=>nx(v,E));if(S)rx(S,E);else{let v=Zy(Ru(E),tx(n));lx(c.body,v),l.push(v)}}return fe(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function nx(e,t){return e.importKind==="type"?!1:Pu(ix(ox(e),wu(t)))}function rx(e,t){let n=!1,r=new Set(e.specifiers.map(o=>$s(o)));for(let o of Ru(t)){let i=$s(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return Au(e.specifiers),{changed:n}}function Ru(e){let t=e.map(n=>{switch(n.kind){case"named":return ex(n.local?Er(n.local):Er(n.imported),Er(n.imported));case"default":return Qy(Er(n.local));case"namespace":return qy(Er(n.local));default:return n}});return Au(t),t}function wu(e){let t=Nu();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 ox(e){let t=Nu();for(let n of e.specifiers)Iu(n)?t.defaultLocals.add(n.local.name):ku(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Nu(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function ix(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Pu(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function Au(e){let t=[...e.filter(n=>Iu(n)),...e.filter(n=>ku(n)),...e.filter(n=>Cu(n))];e.splice(0,e.length,...t)}function sx(e){let t=e.filter(i=>i.kind==="default"),n=e.filter(i=>i.kind==="namespace"),r=e.filter(i=>i.kind==="named"),o=[];if(n.length>0){let i=Math.max(t.length,n.length);for(let s=0;s<i;s+=1){let a=[],c=t[s],l=n[s];c&&a.push(c),l&&a.push(l),o.push(a)}return r.length>0&&o.push(r),o}if(t.length>0){o.push([t[0],...r]);for(let i of t.slice(1))o.push([i])}else r.length>0&&o.push(r);return o}function ax(e){let t=new Map,n=new Map;for(let r of e){let o=Tu(r);if(t.has(o))continue;let i=js(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 cx(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(Yy(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 lx(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 ux(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 Tu(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 js(e){return e.kind==="named"?e.local??e.imported:e.local}function dx(e,t){return e.importKind==="type"||Cu(t)&&t.importKind==="type"?null:$s(t)}function $s(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 Un(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!px(u));if(o!==-1){let u=r[o],f=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return $(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(f)}`)}let i=ke(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(c===-1)return yr(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),fe(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(f=>fx(u,f))),l.specifiers.length===0&&a.body.splice(c,1),fe(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function fx(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 px(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 vr(e){let{source:t,locator:n,next:r}=e,o=Xo(t,n);return o.ok?(o.path.replaceWith(Gt(r)),fe(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Uo(e){let{source:t,locator:n,index:r,value:o}=e,i=Xo(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?$(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?$(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,Gt(o)),fe(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):$(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function Ko(e){let{source:t,locator:n,index:r}=e,o=Xo(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?$(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?$(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),fe(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):$(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function Jo(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=Xo(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return $(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return $(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 $(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),fe(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function Xo(e,t){let n=ke(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=ie(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as Ve from"@babel/types";function zo(e){let t=ke(e.source,"value");if(!t.ok)return t.result;let n=ie(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return $(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Ve.isSpreadElement(a)||Ve.isObjectProperty(a)&&a.computed))return $(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Ve.isObjectProperty(a)&&mx(a.key)===e.name);if(o.length>1)return $(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Ve.unaryExpression("void",Ve.numericLiteral(0)):Gt(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Ve.objectProperty(Fs(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return fe(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function mx(e){return Ve.isIdentifier(e)?e.name:Ve.isStringLiteral(e)?e.value:Ve.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as gx,isSiteEditRuntimeVoidElementTag as hx}from"@vcp-dev/contracts/site-edit-runtime-capability";function Kn(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function yx(e,t,n){let r=Kn(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(N=>({kind:N.kind,message:N.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),f=i.tag!==u,m=!f&&hx(u),d=f||gx(u),g=f&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(N=>N.editable);m&&!s.some(N=>N.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!m&&!d&&!s.some(N=>N.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let E=h&&(!a||i.importedFrom==="next/link"),S=!i.isPublicUiComponent&&!m&&d&&(!a||g);return{composition:r,key:e,canUpdateText:E,canInsertChild:S,canMove:!l,canRemove:!l,constraints:s}}function Fu(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,yx(r,e,t));return n}function Vs(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:be(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=xx(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:be(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(c=>c.type==="JSXAttribute"&&c.name.type==="JSXIdentifier"&&c.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:Ou(r),version:{documentVersion:e.route.graph.version,contentHash:be(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:_u(e.route.source,o),valueRaw:s?_u(e.route.source,s):null,attrRange:Ou(o),diagnostics:[]}}function Mu(e){let{source:t,oldAttrRange:n,openingElementRange:r,newAttrRaw:o}=e;if(n){let a=n.start>0&&/\s/.test(t[n.start-1]??"")?n.start-1:n.start,c=o?`${a<n.start?" ":""}${o}`:"";return t.slice(0,a)+c+t.slice(n.end)}if(!o)return t;let i=r.end,s=t.slice(Math.max(0,i-2),i)==="/>"?i-2:i-1;return t.slice(0,s)+` ${o}`+t.slice(s)}function xx(e,t){let n=Rt({source:e,profile:pn({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=ie(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:bx(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function Du(e){let t=Rt({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 _u(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Ou(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 bx(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Lu(){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 Sx}from"node:crypto";import Ho from"node:fs/promises";import Us from"node:path";import{setTimeout as Ex}from"node:timers/promises";var vx={async mkdir(e,t){await Ho.mkdir(e,t)},async writeFile(e,t,n){await Ho.writeFile(e,t,n)},async rename(e,t){await Ho.rename(e,t)},async rm(e,t){await Ho.rm(e,t)}},Ix=new Set(["EACCES","EBUSY","EPERM"]),kx=[10,20,40,80,160];async function Cx(e,t,n){for(let r of kx)try{await e.rename(t,n);return}catch(o){if(!Rx(o))throw o;await Ex(r)}await e.rename(t,n)}function Rx(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Ix.has(e.code)}async function Wo(e,t,n=vx){let r=Us.dirname(e),o=Us.basename(e),i=Us.join(r,`.${o}.${process.pid}.${Sx()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await Cx(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import zs from"@babel/traverse";import*as b from"@babel/types";import*as ce from"@babel/types";function At(e,t={}){if(ce.isTSAsExpression(e)||ce.isTSSatisfiesExpression(e)||ce.isTSNonNullExpression(e)||ce.isTypeCastExpression(e)||ce.isParenthesizedExpression(e))return At(e.expression,t);if(ce.isStringLiteral(e))return{status:"resolved",value:e.value};if(ce.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(ce.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(ce.isNullLiteral(e))return{status:"resolved",value:null};if(ce.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(ce.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(ce.isUnaryExpression(e)&&e.operator==="void"&&ce.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(ce.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||ce.isSpreadElement(r))return{status:"unresolved"};let o=At(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(ce.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!ce.isObjectProperty(r)||r.computed||!ce.isExpression(r.value))return{status:"unresolved"};let o=wx(r.key);if(o===null)return{status:"unresolved"};let i=At(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 ce.isMemberExpression(e)||ce.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function wx(e){return ce.isIdentifier(e)?e.name:ce.isStringLiteral(e)?e.value:ce.isNumericLiteral(e)?String(e.value):null}import{createHash as _x}from"node:crypto";import*as Nx from"@babel/parser";import*as Jn from"@babel/types";import*as Qt from"node:path";var Ks=[".tsx",".ts",".jsx",".js"],Px=Ks.map(e=>`/index${e}`),Ax=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 Bu(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&Ax.has(n[1].toLowerCase())}function ju(e){let t=[];for(let n of e.program.body)Jn.isImportDeclaration(n)&&typeof n.source.value=="string"&&Tt(n.source.value)&&t.push(n.source.value),Jn.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&Tt(n.source.value)&&t.push(n.source.value),Jn.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&Tt(n.source.value)&&t.push(n.source.value);return Js(e.program,t),t}function Js(e,t){if(!e||typeof e!="object")return;let n=e;if(n.type==="CallExpression"&&n.callee?.type==="Import"){let r=n.arguments?.[0];r?.type==="StringLiteral"&&typeof r.value=="string"&&Tt(r.value)&&t.push(r.value)}for(let r of Object.values(n))if(Array.isArray(r))for(let o of r)Js(o,t);else r&&typeof r=="object"&&Js(r,t)}function Tt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Ir(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=Qt.dirname(e);return Qt.join(n,t).replace(/\\/g,"/")}async function Tx(e,t){if(Ks.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Ks){let r=`${e}${n}`;if(await t(r))return r}for(let n of Px){let r=`${e}${n}`;if(await t(r))return r}return null}async function hn(e,t,n){let r=await Go(e,t,n);return r.ok?r.path:null}async function Go(e,t,n){let r=Ir(e,t);try{if(!Fx(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 Tx(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 Fx(e,t,n){if(!Tt(t)||t.includes("\0")||t.includes("\\")||Qt.posix.isAbsolute(n))return!1;let r=Qt.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!Qt.posix.isAbsolute(e)}var kr=(e,t)=>{let n=Rt({source:t,profile:pn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${_x("sha256").update(t).digest("hex")}`,ast:n.ast,imports:ju(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};var Yo="components/ui";function yn(e){if(!e)return!1;let t=Xs(e);return t===Yo||t.startsWith(`${Yo}/`)||t.includes(`/${Yo}/`)||t.endsWith(`/${Yo}`)}function Cr(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?yn(e.slice(2)):e.startsWith("./")||e.startsWith("../")?yn(Xs(`${Ox(t)}/${e}`)):yn(e):!1}function Xs(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let o of n.split("/"))if(!(!o||o===".")){if(o===".."){r.pop();continue}r.push(o)}return r.join("/")}function Ox(e){let t=Xs(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var Mx=typeof zs=="function"?zs:zs.default;function Xe(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 Dx(e){return/^[A-Z]/.test(e)}function Zs(e){let t=e.openingElement;return b.isJSXIdentifier(t.name)?t.name.name==="Fragment":b.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function zn(e){return b.isJSXFragment(e)}function Vu(e){return b.isJSXIdentifier(e.name)?e.name.name:b.isJSXMemberExpression(e.name)?Uu(e.name):b.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Uu(e){return b.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:b.isJSXMemberExpression(e.object)?`${Uu(e.object)}.${e.property.name}`:e.property.name}function Lx(e){return e.split(".")[0]??e}function Bx(e){let t=e;for(;t;){let n=t.node;if(b.isFunctionDeclaration(n)&&n.id||b.isVariableDeclarator(n)&&b.isIdentifier(n.id))return n.id.name;if(b.isExportDefaultDeclaration(n)){let r=n.declaration;if(b.isFunctionDeclaration(r)&&r.id)return r.id.name;if(b.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function jx(){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 $x(e){let t=new Map;for(let n of e.program.body){if(!b.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(b.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(b.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(b.isImportSpecifier(o)){let i=b.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Kt(e,t=[]){if(b.isIdentifier(e))return t.push(e.name),t;if(b.isObjectPattern(e)){for(let n of e.properties)b.isObjectProperty(n)?Kt(n.value,t):b.isRestElement(n)&&Kt(n.argument,t);return t}if(b.isArrayPattern(e)){for(let n of e.elements)n&&(b.isRestElement(n)?Kt(n.argument,t):Kt(n,t));return t}return b.isAssignmentPattern(e)?(Kt(e.left,t),t):(b.isRestElement(e)&&Kt(e.argument,t),t)}function bt(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Rr(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 Vx(e,t,n){e.set(t,{resolved:!0,value:n})}function Qs(e,t){e.set(t,{resolved:!1})}function Ku(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 Le(e,t,n){if(b.isTSAsExpression(e)||b.isTSSatisfiesExpression(e)||b.isTSNonNullExpression(e)||b.isTypeCastExpression(e)||b.isParenthesizedExpression(e))return Le(e.expression,t,n);if(b.isLogicalExpression(e))return Zo([Le(e.left,t,n),Le(e.right,t,n)]);if(b.isBinaryExpression(e))return Zo([b.isExpression(e.left)?Le(e.left,t,n):null,b.isExpression(e.right)?Le(e.right,t,n):null]);if(b.isConditionalExpression(e))return Zo([Le(e.consequent,t,n),Le(e.alternate,t,n)]);if(b.isTemplateLiteral(e))return Zo(e.expressions.filter(b.isExpression).map(i=>Le(i,t,n)));if(b.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!b.isMemberExpression(e)&&!b.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;b.isMemberExpression(o)||b.isOptionalMemberExpression(o);){if(o.computed)if(b.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(b.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&b.isExpression(o.property)){let i=qt(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(!b.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return b.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:bt(e,t),base:o.name,path:r}:null}function Zo(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 qt(e,t){if(b.isStringLiteral(e)||b.isNumericLiteral(e)||b.isBooleanLiteral(e))return e.value;if(b.isNullLiteral(e))return null;if(b.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(b.isIdentifier(e)){let n=Rr(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(b.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||b.isSpreadElement(r))return;let o=qt(r,t);if(o===void 0)return;n.push(o)}return n}if(b.isObjectExpression(e)){let n={};for(let r of e.properties){if(!b.isObjectProperty(r)||r.computed||!b.isExpression(r.value))return;let o=null;if(b.isIdentifier(r.key)?o=r.key.name:b.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!b.isIdentifier(r.value))return;let s=Rr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=qt(r.value,t);if(i===void 0)return;n[o]=i}return n}if(b.isMemberExpression(e)){let n=Le(e,"",t);if(!n)return;let r=Rr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Ku(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(b.isCallExpression(e))return Xu(e,t)??void 0}function Ju(e,t,n){let r=Le(e,n,t);if(!r)return b.isMemberExpression(e)||b.isBinaryExpression(e)||b.isLogicalExpression(e)||b.isConditionalExpression(e)||b.isCallExpression(e)?{value:bt(e,n),source:null}:null;let o=Rr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Ku(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 Hs(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:jx(),parentStack:[],valueScopes:i,importMap:o}}function Gs(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Kt(o.id))Qs(n,s);if(!b.isIdentifier(o.id)||!o.init||!b.isExpression(o.init))continue;let i=qt(o.init,t);i!==void 0&&Vx(n,o.id.name,i)}}function Ux(e){let t=[];for(let n of e){if(b.isVariableDeclaration(n)){t.push(n);continue}b.isExportNamedDeclaration(n)&&n.declaration&&b.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function Kx(e,t,n){let r=[],o=0;for(let i of e)if(b.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Xe(i),editable:!0,source:null})}else if(b.isJSXExpressionContainer(i)&&b.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Xe(i),editable:!0,source:null});else if(b.isJSXExpressionContainer(i)&&b.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:Xe(i),editable:!0,source:null}):r.push({index:o++,value:bt(s,n),sourceRange:Xe(i),editable:!0,source:Le(s,n,t)})}else if(b.isJSXExpressionContainer(i)&&b.isExpression(i.expression)){let s=Ju(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Xe(i),editable:!0,source:s.source})}return r}function Jx(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!b.isJSXAttribute(i))continue;let s=zx(i.name);if(!s)continue;let a=bt(i,n);if(b.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Xe(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:Xe(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(b.isJSXExpressionContainer(i.value)&&b.isExpression(i.value.expression)){let c=qt(i.value.expression,t);if(s==="className"){let d=typeof c=="string"?c:c===void 0?Xu(i.value.expression,t):null;if(d){r.push({name:s,value:d,sourceRange:Xe(i),source:null,resolvedValue:d,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:d}});continue}}let l=Ju(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:qx(c),sourceRange:Xe(i),source:Le(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=Hx(i.value.expression,t),f=Le(i.value.expression,n,t),m=l?.value??bt(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":m,sourceRange:Xe(i),source:l?.source??f,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function Xx(e,t,n){return e.attributes.flatMap((r,o)=>!b.isJSXSpreadAttribute(r)||!b.isExpression(r.argument)?[]:[{raw:bt(r.argument,n),sourceRange:Xe(r),order:o,source:Le(r.argument,n,t)}])}function zx(e){return b.isJSXIdentifier(e)?e.name:b.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Hx(e,t){return At(e,{resolveIdentifier(n){let r=Rr(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=qt(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function Xu(e,t){let n=Xn(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function Xn(e,t){if(b.isStringLiteral(e))return[e.value];if(b.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(b.isNullLiteral(e))return[];if(b.isBooleanLiteral(e))return e.value?null:[];if(b.isIdentifier(e)||b.isMemberExpression(e)){if(b.isIdentifier(e)&&e.name==="undefined")return[];let n=qt(e,t);return typeof n=="string"?[n]:null}if(b.isConditionalExpression(e)){let n=Xn(e.consequent,t),r=Xn(e.alternate,t);return!n||!r?null:[...n,...r]}if(b.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=qt(e.left,t);return n===!1||n===null?[]:Xn(e.right,t)}if(b.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||b.isSpreadElement(r))return null;let o=Xn(r,t);if(!o)return null;n.push(...o)}return n}if(b.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!b.isObjectProperty(r))return null;let o=Gx(r.key);if(!o)return null;n.push(o)}return n}if(b.isCallExpression(e)){let n=Wx(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!b.isExpression(o))return null;let i=Xn(o,t);if(!i)return null;r.push(...i)}return r}return null}function Wx(e){return b.isIdentifier(e)?e.name:b.isMemberExpression(e)&&b.isIdentifier(e.property)?e.property.name:null}function Gx(e){return b.isIdentifier(e)?e.name:b.isStringLiteral(e)?e.value:null}function Yx(e,t){let n=e.attributes.find(r=>b.isJSXAttribute(r)&&b.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!b.isJSXAttribute(n)||!b.isJSXExpressionContainer(n.value)?null:n.value.expression}function Zx(e,t){for(let n of t){let r=Yx(e,n);if(r)return r}return null}function Qx(e){return b.isJSXIdentifier(e.name)?e.name.name:null}function qx(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function eb(e){if(!b.isCallExpression(e)&&!b.isOptionalCallExpression(e))return null;let t=e.callee;return!b.isMemberExpression(t)&&!b.isOptionalMemberExpression(t)||!b.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!b.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Ws(e){return b.isArrowFunctionExpression(e)||b.isFunctionExpression(e)}function tb(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function nb(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function $u(e,t,n,r){if(!e||!b.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:bt(e,n),collectionSource:Le(e,n,r)};if(t){let i=t.params[0],s=t.params[1];b.isIdentifier(i)&&(o.itemParamName=i.name),b.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Jt(e,t,n){if(!e)return[];if(b.isJSXElement(e)){if(Zs(e))return ni(e.children,t,n);let r=ei(e,t,n);return r?[r]:[]}return zn(e)?ti(e,t,n):b.isParenthesizedExpression(e)?Jt(e.expression,t,n):b.isExpression(e)?ri(e,t,n):[]}function Qo(e,t,n){let r=new Map;for(let o of e.params)for(let i of Kt(o))Qs(r,i);t.valueScopes.push(r);try{if(!b.isBlockStatement(e.body))return Jt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return zu(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function zu(e,t,n){let r=[];for(let o of e){if(b.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){Gs([o],t,i);for(let s of o.declarations)b.isIdentifier(s.id)&&(b.isJSXElement(s.init)||b.isJSXFragment(s.init))&&r.push(...Jt(s.init,t,n))}continue}r.push(...Ys(o,t,n))}return r}function Ys(e,t,n){if(b.isReturnStatement(e))return e.argument?Jt(e.argument,t,n):[];if(b.isBlockStatement(e))return xn(e.body,t,n);if(b.isIfStatement(e)){let r=b.isBlockStatement(e.consequent)?xn(e.consequent.body,t,n):Ys(e.consequent,t,n),o=e.alternate?b.isBlockStatement(e.alternate)?xn(e.alternate.body,t,n):Ys(e.alternate,t,n):[];return[...r,...o]}if(b.isSwitchStatement(e))return xn(e.cases.flatMap(r=>r.consequent),t,n);if(b.isTryStatement(e)){let r=xn(e.block.body,t,n);return e.handler&&r.push(...xn(e.handler.body.body,t,n)),e.finalizer&&r.push(...xn(e.finalizer.body,t,n)),r}return[]}function xn(e,t,n){let r=new Map;t.valueScopes.push(r);try{return zu(e,t,n)}finally{t.valueScopes.pop()}}function qo(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Xe(r),sourceCandidates:i&&i.length>0?i:void 0})}function rb(e,t,n,r){let o=Zx(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Vu(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!b.isJSXAttribute(s))continue;let a=Qx(s);if(!a||!b.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!b.isJSXEmptyExpression(c)){if(tb(a)&&Ws(c)){let l=Qo(c,n,r),u=$u(o,c,r,n);qo(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(nb(a)){let l=Ws(c)?Qo(c,n,r):Jt(c,n,r);qo(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!b.isJSXExpressionContainer(s)||!Ws(s.expression))continue;let a=Qo(s.expression,n,r),c=$u(o,s.expression,r,n);qo(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function ei(e,t,n){let r=Vu(e.openingElement);if(r==="Fragment"||Zs(e))return ni(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=Dx(r),a;if(s){let N=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${N}`}else{let N=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${N}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=br(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:u},m=s?"component-boundary":null,d=Kx(e.children,t,n),g=Jx(e.openingElement,t,n),h=Xx(e.openingElement,t,n),E,S,v=!1;if(s){let N=t.importMap.get(r)??t.importMap.get(Lx(r));N&&(E=N.specifier,S=N.exportName,v=Cr(N.specifier,t.file))}let C={identity:f,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Xe(e),parentKey:i,childKeys:[],textSegments:d,attributes:g.length>0?g:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:m,isOpaque:s,...v?{isPublicUiComponent:!0}:{},importedFrom:E,exportName:S};return t.elements.set(u,C),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),rb(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),ob(e.children,t,n),t.parentStack.pop()),u}function ti(e,t,n){return ni(e.children,t,n)}function ni(e,t,n){let r=[];for(let o of e)if(b.isJSXElement(o))if(Zs(o))r.push(...ni(o.children,t,n));else{let i=ei(o,t,n);i&&r.push(i)}else zn(o)?r.push(...ti(o,t,n)):b.isJSXExpressionContainer(o)&&r.push(...ri(o.expression,t,n));return r}function ob(e,t,n){for(let r of e)b.isJSXElement(r)?ei(r,t,n):zn(r)?ti(r,t,n):b.isJSXExpressionContainer(r)&&ri(r.expression,t,n)}function ib(e){return e==="&&"||e==="||"||e==="??"}function ri(e,t,n){if(b.isJSXEmptyExpression(e))return[];let r=eb(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:bt(r.collection,n),collectionSource:Le(r.collection,n,t)};if(b.isArrowFunctionExpression(a)||b.isFunctionExpression(a)){let u=a.params[0],f=a.params[1];b.isIdentifier(u)&&(c.itemParamName=u.name),b.isIdentifier(f)&&(c.indexParamName=f.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Xe(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(b.isArrowFunctionExpression(a)||b.isFunctionExpression(a))&&l.childKeys.push(...Qo(a,t,n)),l.childKeys}if(b.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:bt(e.test,n),conditionSource:Le(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Xe(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Jt(e.consequent,t,n)),s.childKeys.push(...Jt(e.alternate,t,n)),s.childKeys}if(b.isLogicalExpression(e)&&ib(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:bt(e.left,n),conditionSource:Le(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Xe(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Jt(e.right,t,n)),s.childKeys}if(b.isParenthesizedExpression(e))return ri(e.expression,t,n);if(b.isJSXElement(e)){let o=ei(e,t,n);return o?[o]:[]}return zn(e)?ti(e,t,n):[]}function sb(e){let t=e.argument;return t&&(b.isExpression(t)||zn(t))?t:null}function wr(e,t){let n=[];for(let r of e){if(b.isReturnStatement(r)){let o=sb(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(b.isIfStatement(r)){let o=b.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...wr(o,r.test)),r.alternate){let i=b.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...wr(i,r.test))}continue}if(b.isSwitchStatement(r))for(let o of r.cases){let i=o.test?b.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...wr(o.consequent,i))}}return n}function Hu(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier),i=new Map,s=[],a=[],c=new Map,l=$x(r);Mx(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let m=Bx(f);if(!m)return;let d=f.node,g=[];if(b.isArrowFunctionExpression(d))b.isExpression(d.body)||zn(d.body)?g=[{argument:d.body,statement:b.returnStatement(b.isExpression(d.body)?d.body:null)}]:b.isBlockStatement(d.body)&&(g=wr(d.body.body));else{let N=d.body;b.isBlockStatement(N)&&(g=wr(N.body))}if(g.length===0){f.skip();return}let h=new Map;Gs(Ux(r.program.body),Hs(t,m,i,s,l,[h]),h);let E=new Map;for(let N of d.params)for(let A of Kt(N))Qs(E,A);let S=b.isBlockStatement(d.body)?d.body.body:[],v=g[0]?.statement??null;for(let N of S){if(v&&N===v)break;b.isVariableDeclaration(N)&&Gs([N],Hs(t,m,i,s,l,[h,E]),E)}let C=Hs(t,m,i,s,l,[h,E]);for(let N of g){let A=Jt(N.argument,C,n);for(let P of A)a.includes(P)||a.push(P);if(N.condition){let P={kind:"conditional-branch",conditionExpression:bt(N.condition,n),conditionSource:Le(N.condition,n,C)};qo(C,"conditional-region","",N.statement,A,[P])}}f.skip()}});let u=[...i.keys()];return u.length>0&&c.set(t,u),{graph:{routeId:t,rootKeys:a,elements:i,regions:s,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function qs(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function oi(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Wu(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??kr,c=new Map,l=new Map,u=new Map,f=[],m=new Set,d=S=>{let v=`${S.path}\0${S.code}\0${S.message}\0${JSON.stringify(S.details??{})}`;m.has(v)||(m.add(v),f.push(S))},g=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(S=>({file:S.file,source:S.source,depth:0,diagnosticEntryFile:S.file,importStack:[]}))],h=new Set;for(;g.length>0;){let S=g.shift(),{file:v,source:C,depth:N,diagnosticEntryFile:A,importStack:P}=S;if(h.has(v))continue;h.add(v),c.set(v,C);let k=a(v,C);if(!k.ok){d(oi(k.diagnostic,A,P));continue}u.set(v,k.module);let{graph:T,localImports:O}=Hu(k.module);for(let L of T.elements.values())if(L.importedFrom&&Tt(L.importedFrom)){let G=L.importedFrom,ne=await Go(v,G,r);ne.ok?(L.importedFrom=ne.path,yn(ne.path)&&(L.isPublicUiComponent=!0)):Cr(G,v)||d(oi(ne.diagnostic,A,qs(P,v,G,ne.diagnostic.path)))}if(l.set(v,T),!(N>=i))for(let L of O){if(Bu(L))continue;let G=await Go(v,L,r);if(!G.ok){Cr(L,v)||d(oi(G.diagnostic,A,qs(P,v,L,G.diagnostic.path)));continue}let ne=G.path;if(h.has(ne)||yn(ne))continue;let ve=qs(P,v,L,ne);try{let Y=await n(ne);g.push({file:ne,source:Y,depth:N+1,diagnosticEntryFile:A,importStack:ve})}catch(Y){d(oi({path:ne,code:"import-read-failed",message:`Failed to read imported file: ${ne}`,details:{fromFile:v,specifier:L,reason:Y instanceof Error?Y.message:String(Y)}},A,ve))}}}let E=ab(e,l,s,(o.additionalEntries??[]).map(S=>S.file));return E.diagnostics=f,{graph:E,allSources:c,diagnostics:f,parsedModules:u,entryModule:u.get(e)??null}}function ab(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,f]of l.elements)o.set(u,f);for(let u of l.regions)i.push(u);for(let[u,f]of l.fileIndex){let m=s.get(u)??[];s.set(u,[...m,...f])}if(c===e){a=l.rootKeys;continue}r.includes(c)&&(a=[...a,...l.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}import{SiteEditHistoryProvenanceSchema as cb}from"@vcp-dev/contracts";var lb={affectedCompositions:[]};function ed(e){let t=null,n=new WeakMap;async function r(){return t??=ub(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(Qu(o),{durableManifest:!1}),a;try{a=await e.previewStagedAppend(s.entryId,i.digest)}catch(l){throw await e.discardStage(s.stageId),l}let c={kind:"append",entry:o,historyTransition:a};return n.set(c,{expectedDigest:i.digest,stageId:s.stageId,entryId:s.entryId}),c},async prepareUndo(){let i=(await r()).undo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("undo entry is missing from index");let c=a-1,l=await e.previewCursor(c,s.digest),u={kind:"undo",entry:i,historyTransition:l};return n.set(u,{expectedDigest:s.digest,cursor:c}),u},async prepareRedo(){let i=(await r()).redo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("redo entry is missing from index");let c=a,l=await e.previewCursor(c,s.digest),u={kind:"redo",entry:i,historyTransition:l};return n.set(u,{expectedDigest:s.digest,cursor:c}),u},async publishPrepared(o){let i=n.get(o);if(!i)throw new Error("history mutation was not prepared");let s=await r();if(o.kind==="append"){if(!i.entryId)throw new Error("staged entry id is missing");let a=await e.publishStagedAppend(i.entryId,i.expectedDigest,i.stageId);Gu(a,o.historyTransition),o.entry.historyId=i.entryId,s.entryIds=[...a.entryIds],s.cursor=a.cursor,s.undo.push(o.entry),s.redo.length=0}else{if(i.cursor===void 0)throw new Error("prepared cursor is missing");let a=await e.setCursor(i.cursor,i.expectedDigest);if(Gu(a,o.historyTransition),o.kind==="undo"){if(s.undo.at(-1)!==o.entry)throw new Error("undo state changed before publish");s.undo.pop(),s.redo.push(o.entry)}else{if(s.redo.at(-1)!==o.entry)throw new Error("redo state changed before publish");s.redo.pop(),s.undo.push(o.entry)}s.cursor=i.cursor}n.delete(o)},async discardPrepared(o){let i=n.get(o);if(!i)return;let s=o.historyTransition;if(s){let a=await e.readIndex();if(a.digest===s.publishedIndexDigest&&a.cursor===s.publishedCursor&&a.currentId===s.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}i.stageId&&await e.discardStage(i.stageId),n.delete(o)},async peekUndo(){return(await r()).undo.at(-1)??null},async pushUndo(o){let i=await r(),s=o;if(s.historyId){let l=i.entryIds.indexOf(s.historyId);if(l>=0)try{await e.setCursor(l),i.undo.push(o),i.cursor=l;return}catch(u){throw i.redo.push(o),u}}let a=await e.append(Qu(o)),c=a.currentId;if(!c)throw new Error("history store did not publish an entry");o.historyId=c,i.entryIds=[...a.entryIds],i.cursor=a.cursor,i.undo.push(o),i.redo.length=0},async popUndo(){return(await r()).undo.pop()??null},async peekRedo(){return(await r()).redo.at(-1)??null},async pushRedo(o){let i=await r(),s=o;if(!s.historyId)throw i.undo.push(o),new Error("cannot move an unpersisted history entry to redo");let a=i.entryIds.indexOf(s.historyId);if(a<0)throw i.undo.push(o),new Error("history entry is missing from the durable index");try{await e.setCursor(a-1),i.cursor=a-1,i.redo.push(o)}catch(c){throw i.undo.push(o),c}},async popRedo(){return(await r()).redo.pop()??null},async clearRedo(){(await r()).redo.length=0},async getStatus(){let o=await e.readStatus();return{canUndo:o.canUndo,canRedo:o.canRedo,undoDepth:o.undoDepth,redoDepth:o.redoDepth,recoveryRequired:o.recoveryRequired}},async markRecoveryRequired(o){await e.markRecoveryRequired(o)}}}function Gu(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")}async function ub(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>Yu(e,o))),r=await Promise.all(t.redoIds.map(async o=>Yu(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function Yu(e,t){let n=await e.readEntry(t),r=db(n),o=r.provenance??lb;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 Zu(e,n,r.preSnapshots),postSnapshots:await Zu(e,n,r.postSnapshots)}}async function Zu(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(mb(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Qu(e){let t=[],n=(i,s)=>i.map((a,c)=>{let l={file:a.file,exists:a.exists!==!1,version:a.version,...a.sha256?{sha256:a.sha256}:{}};if(l.exists){let u=`${s}-${c}`;l.blobName=u,t.push({name:u,data:a.content})}return l}),r=fb(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 db(e){if(!nd(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:td(t.provenance)}:{},preSnapshots:qu(t.preSnapshots,"preSnapshots"),postSnapshots:qu(t.postSnapshots,"postSnapshots")}}function fb(e){if(e.provenance!==void 0)return td(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function td(e){let t=cb.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 qu(e,t){return e.map((n,r)=>{if(!nd(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&&!pb(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 pb(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function mb(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function nd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{COMPONENT_I18N_FILE_SUFFIX as gb,parseComponentI18nResourcesJson as hb,resolveSiteTextDirection as yb,SiteLocaleSchema as xb}from"@vcp-dev/contracts";var bb=["i18next","react-i18next"],Sb="components/ui/site-locale-provider.tsx",Eb="components/ui/component-i18n-provider.tsx",rd="app/layout.tsx";async function ta(e){let t=e.files.filter(m=>m.path.endsWith(gb));if(t.length===0)return{ok:!0};for(let m of["package.json",rd,Sb,Eb])if(!await e.exists(m))return bn(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return bn("Target snapshot package.json is invalid.")}let r=od(n)&&od(n.dependencies)?n.dependencies:{},o=bb.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return bn(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(rd),s=ea(i,"html","lang"),a=ea(i,"html","dir"),c=ea(i,"SiteLocaleProvider","locale"),l=xb.safeParse(s);if(!l.success||!a||!c||s!==c||a!==yb(l.data))return bn("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 bn("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data,f=u.split("-")[0];for(let m of t){let d=hb(m.content);if(!d.success)return bn(`Component i18n resource is invalid: ${m.path}.`);if(!Object.hasOwn(d.data,u)&&!Object.hasOwn(d.data,f))return bn(`Component i18n resource ${m.path} has no locale for ${u} or ${f}.`)}return{ok:!0}}function ea(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 od(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bn(e){return{ok:!1,message:e}}import{randomBytes as Db}from"node:crypto";import si from"node:path";import{parse as sa}from"@babel/parser";import Lb from"@babel/traverse";import*as pd from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as ra,PageResourceArtifactSchema as Bb,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as jb,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as $b,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as Vb,parseComponentI18nResourcesJson as Ub}from"@vcp-dev/contracts";var sd=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,ad=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,vb=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,Ib=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,kb=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Cb=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,Rb=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,wb=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Nb=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,Pb=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Ab=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,Tb=/\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,Fb=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,_b=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Nr(e,t){let n=ii([...pt(e,vb),...pt(e,Ib),...pt(e,kb),...pt(e,t.includeRgbBackgroundImage?Cb:Rb),...t.includeExtendedColorFunctions?[...pt(e,wb),...pt(e,Nb)]:[]]),r=ii([...pt(e,Pb),...pt(e,Ab)]).filter(o=>t.colorMixPolicy==="always"||sd.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...pt(e,Tb).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...pt(e,_b).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:ii(pt(e,ad)),hardCodedSurfaceOccurrences:Mb(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?ii(pt(e,Fb)):[]}}function pt(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var id=160,Ob=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function Mb(e){let t=new RegExp(ad.source,"g"),n=[0];for(let s=0;s<e.length;s+=1)e[s]===`
5
+ `&&n.push(s+1);let r=s=>{let a=0,c=n.length-1;for(;a<c;){let l=Math.ceil((a+c)/2);(n[l]??0)<=s?a=l:c=l-1}return a},o=[],i;for(;(i=t.exec(e))!==null;){let s=i[0],a=s.endsWith("/")?s.slice(0,-1):s,c=/^\/(\d+)/.exec(e.slice(i.index+a.length)),l=e.slice(Math.max(0,i.index-64),i.index),u=Ob.exec(l),f=r(i.index),m=e.indexOf(`
6
+ `,i.index),d=e.slice(n[f]??0,m===-1?void 0:m).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:f+1,snippet:d.length>id?`${d.slice(0,id-1)}\u2026`:d})}return o}function ii(e){return[...new Set(e)]}var oa="{{$INSTANCE}}",Kb=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Jb=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,ia="components/site/generated",Xb=/\.(?:tsx?|json)$/,zb=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Hb=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Wb=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),na=Lb,Gb=typeof na=="function"?na:na.default;async function aa(e){let t=Bb.safeParse(e.artifact);if(!t.success)return me("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>Db(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=sS(r());if(!i)return me("Random instance suffix must be 8 lowercase hex chars.");let s=`${aS(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let C of n.pages){let N=C.final_route.slice(1);a.set(C.template_page_id,C.final_route),c.set(C.template_page_id,C.title),l.push({template_page_id:C.template_page_id,title:C.title,final_route:C.final_route,route_file_path:`app/${N}/page.tsx`})}let u=[],f=new Set,m=new Set,d=new Map,g=new Map,h=[],E=new Set(n.pages.flatMap(C=>C.components.map(N=>N.component_id)));for(let C of n.components){if(!E.has(C.component_id))continue;let N=cd({materialization:C.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!N.ok)return N;for(let A of N.files){let P=ud(A,f,u);if(P)return P}m.add(N.entry),g.set(N.entry,N.entryExport),d.set(C.component_id,N.entry)}for(let[C,N]of n.pages.entries()){let A=l[C],P=cd({materialization:N.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:A.route_file_path,pageTitle:A.title});if(!P.ok)return P;for(let O of P.files){let L=ud(O,f,u);if(L)return L}m.add(P.entry),g.set(P.entry,P.entryExport),h.push({entry:P.entry,declaredComponentIds:new Set(N.components.map(O=>O.component_id))});let k=u.find(O=>O.file===A.route_file_path);if(!k)return me("Page materialization entry did not resolve to its final route file.",A.route_file_path);if(eS(k.content,A.route_file_path)!==A.final_route)return me(`Page ${N.template_page_id} requires a static PAGE_SEO.path equal to ${A.final_route}.`,A.route_file_path)}let S=Zb(u,m,s,d,h,g);if(!S.ok)return S;for(let C of u)if(await e.exists(C.file))return!C.file.startsWith("app/")&&o>1?aa({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${C.file}`,path:C.file};let v=Qb(u);return v||(u.sort((C,N)=>C.file.localeCompare(N.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function cd(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:ld(o.pathTemplate,e.packageInstanceId);if(!s)return me("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=Yb(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?tS(a.data,e.pageTitle,s):a;if(!c.ok)return c;n.push({operation:"create-only",file:s,content:c.data})}let r=e.pageEntryTarget??ld(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?me("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function Yb(e,t,n,r){let o,i=e.replace(Kb,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return me(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(Jb,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return me(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(oa,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?me("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function ld(e,t){let n=`${ia}/${t}`;if(e.split(oa).length>2)return null;let o=e.replace(oa,t),i=`${ia}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=si.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!Xb.test(a)||zb.test(a)?null:a}function ud(e,t,n){return t.has(e.file)?me(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function Zb(e,t,n,r,o,i){let s=new Set(e.map(d=>d.file)),a=`${ia}/${n}`,c=new Map(e.map(d=>[d.file,new Set])),l=new Map;for(let d of e){if(d.file.endsWith(".json")){try{JSON.parse(d.content)}catch{return me("Materialization JSON file must contain valid JSON.",d.file)}if(d.file.endsWith(ra)&&!Ub(d.content).success)return me("Materialization component i18n resources are invalid.",d.file);continue}try{let h=sa(d.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(d.file,h);for(let S of h.program.body)if((S.type==="ImportDeclaration"||S.type==="ExportAllDeclaration"||S.type==="ExportNamedDeclaration"&&S.source)&&S.source){let v=S.source.value,C=oS(d.file,v,s,a);if(!C.allowed)return me(`Materialization import is outside the controlled package: ${v}`,d.file);C.internalPath&&c.get(d.file).add(C.internalPath)}let E;if(Gb(h,{Identifier(S){S.isReferencedIdentifier()&&Wb.has(S.node.name)&&(E??=S.node.name,S.stop())},JSXAttribute(S){S.node.name.type==="JSXIdentifier"&&S.node.name.name==="style"&&(E??="inline style",S.stop())},JSXOpeningElement(S){S.node.name.type==="JSXIdentifier"&&S.node.name.name.toLowerCase()==="style"&&(E??="style element",S.stop())}}),E)return me(`Materialization source uses forbidden capability: ${E}`,d.file)}catch{return me("Materialization source must parse as TS/TSX.",d.file)}let g=Nr(d.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(g.hardCodedSurfaceHits.length>0||g.rawColorHits.length>0||g.privateTokenHits.length>0)return me("Materialization source violates the public theme token policy.",d.file)}if([...t].some(d=>!s.has(d)))return me("Materialization entry is outside the controlled package.");for(let d of t)if(d.endsWith(".json"))return me("Materialization JSON files cannot be package entries.");for(let[d,g]of i){let h=l.get(d);if(!h||!qb(h,g))return me("Materialization entry does not declare its contracted export.",d)}let u=new Map([...r].map(([d,g])=>[g,d]));for(let d of o){let g=fd(d.entry,c);for(let h of d.declaredComponentIds){let E=r.get(h);if(!E||!g.has(E))return me(`Page entry does not reach declared component: ${h}`,d.entry)}for(let h of g){let E=u.get(h);if(E&&!d.declaredComponentIds.has(E))return me(`Page entry imports undeclared component: ${E}`,d.entry)}}let f=new Set;for(let d of t)for(let g of fd(d,c))f.add(g);if(f.size!==e.length)return me("Every materialization file must be reachable from a package entry.");let m=iS(e,l,c);return m||{ok:!0}}function Qb(e){if(e.length>jb)return me("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>$b)return me("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>Vb?me("Page resource exceeds the aggregate content byte limit."):null}function qb(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 eS(e,t){let n;try{n=sa(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}for(let r of n.program.body){let o=r.type==="VariableDeclaration"?r:r.type==="ExportNamedDeclaration"&&r.declaration?.type==="VariableDeclaration"?r.declaration:null;if(o)for(let i of o.declarations){if(i.id.type!=="Identifier"||i.id.name!=="PAGE_SEO")continue;let s=ai(i.init);if(s?.type!=="ObjectExpression")return null;for(let a of s.properties){if(a.type!=="ObjectProperty"||a.computed||!nS(a.key))continue;let c=ai(a.value);return c?.type==="StringLiteral"?c.value:c?.type==="TemplateLiteral"&&c.expressions.length===0?c.quasis[0]?.value.cooked??null:null}return null}}return null}function tS(e,t,n){let r;try{r=sa(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return me("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=ai(s.init);if(a?.type!=="ObjectExpression")return me("Page materialization PAGE_SEO must be a static object.",n);let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&rS(u.key));if(!c||c.type!=="ObjectProperty")return me("Page materialization PAGE_SEO must declare a static title.",n);let l=ai(c.value);return!l||l.type!=="StringLiteral"&&l.type!=="TemplateLiteral"||l.type==="TemplateLiteral"&&l.expressions.length>0||typeof l.start!="number"||typeof l.end!="number"?me("Page materialization PAGE_SEO.title must be a static string.",n):{ok:!0,data:e.slice(0,l.start)+JSON.stringify(t)+e.slice(l.end)}}}return me("Page materialization must declare a top-level PAGE_SEO object.",n)}function ai(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&pd.isExpression(t)?t:null}function nS(e){return e.type==="Identifier"&&e.name==="path"||e.type==="StringLiteral"&&e.value==="path"}function rS(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function oS(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=dd(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:Hb.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=si.posix.normalize(si.posix.join(si.posix.dirname(e),t)),i=dd(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function dd(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 iS(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(ra))continue;let i=o.file.slice(0,-ra.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return me("Component i18n resources require a same-name TS/TSX companion.",o.file);let c=t.get(s)?.program.directives.some(u=>u.value.value==="use client"),l=[...n].filter(([,u])=>u.has(o.file));if(!c||l.length!==1||l[0]?.[0]!==s)return me("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function fd(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 sS(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function aS(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function me(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as cS}from"node:crypto";import Xt from"node:path";import{parse as lS}from"@babel/parser";import uS from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as ci,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as md,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as dS,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as fS,SiteEditMaterializationSchema as pS,parseComponentI18nResourcesJson as mS}from"@vcp-dev/contracts";var ua="components/site/generated",gd="{{$INSTANCE}}",li=5,gS=/^[a-z][a-z0-9-]{0,48}$/,hS=/^[a-f0-9]{8}$/,hd=/\.tsx?$/,yS=/\.json$/,xS=/\.(?:tsx?|json)$/,bS=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,SS=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],ca=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),la=uS,ES=typeof la=="function"?la:la.default;function vS(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>md)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=_S(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=pS.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=AS(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${ua}.`,path:e.generatedRoot}};if(!vd(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=bd(r.data.files),s=bd(e.controlledFiles);if(!OS(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>md)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[c,l]of r.data.files.entries()){let u=Buffer.byteLength(l.content,"utf8");if(u>dS)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file exceeds the per-file content limit.",file:l.pathTemplate,path:`files[${c}]`}};a+=u}return a>fS?{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 IS(e){let t=vS(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=vd(e.manifest.instanceBaseName),o=Math.max(1,Math.min(li,e.maxAttempts??li));for(let i=0;i<o;i+=1){let s=TS(e.instanceNameGenerator?.()??cS(4).toString("hex"));if(!s)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let a=`${r}-${s}`,c=kd(n,a),l=kS({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,allowedExternalImports:e.allowedExternalImports??SS});if(!l.ok)return l;if(!await CS(e.exists,c,l.data.files))return{ok:!0,data:l.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function Ed(e){let t=Math.max(1,Math.min(li,e.maxAttempts??li));for(let n=0;n<t;n+=1){let r=await IS({...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 kS(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=yd({pathTemplate:i.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!s.ok)return s;if(n.has(s.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${s.data}`,path:s.data}};n.add(s.data),t.push({kind:"create-only",path:s.data,content:i.content,...i.role?{role:i.role}:{},sourcePathTemplate:i.pathTemplate})}t.sort((i,s)=>i.path.localeCompare(s.path));let r=yd({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!r.ok)return r;if(!t.some(i=>i.path===r.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:r.data}};let o=RS(t,e.instanceRoot,r.data,e.manifest.entry.export,e.allowedExternalImports);return o.ok?{ok:!0,data:{kind:"static-prefab-materialization",instanceName:e.instanceName,generatedRoot:e.generatedRoot,instanceRoot:e.instanceRoot,entry:{path:r.data,export:e.manifest.entry.export},files:t}}:o}async function CS(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function yd(e){if(e.pathTemplate.split(gd).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(gd,e.instanceName),n=FS(t);return n?kd(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||!xS.test(n)||bS.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 RS(e,t,n,r,o){let i=new Set(e.map(f=>f.path)),s=new Map,a=new Map(e.map(f=>[f.path,new Set])),c=new Map;for(let f of e){if(yS.test(f.path)){if(f.path.endsWith(ci)){let g=mS(f.content);if(!g.success)return Sn("MATERIALIZATION_DATA_UNSUPPORTED",g.error.message,f.path);c.set(f.path,new Set)}else try{JSON.parse(f.content)}catch{return Sn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",f.path)}continue}let m;try{m=lS(f.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:f.path}}}let d=Nr(f.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(d.hardCodedSurfaceHits.length>0||d.rawColorHits.length>0||d.privateTokenHits.length>0)return{ok:!1,error:{code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source must use public semantic design tokens instead of raw colors or private tokens.",file:f.path}};s.set(f.path,m)}for(let f of e){if(!hd.test(f.path))continue;let m=s.get(f.path),d=null;if(ES(m,{ImportDeclaration(g){let h=xd({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!h.allowed)d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:f.path},g.stop();else if(h.internalPath&&(a.get(f.path).add(h.internalPath),h.internalPath.endsWith(ci))){let E=wS({importer:f.path,imported:h.internalPath,source:g.node.source.value,ast:m});E.ok?c.get(h.internalPath).add(f.path):(d??=E.error,g.stop())}},ExportAllDeclaration(g){d??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:f.path},g.stop()},ExportNamedDeclaration(g){if(g.node.source){let h=xd({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!h.allowed||!h.internalPath?(d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:f.path},g.stop()):a.get(f.path).add(h.internalPath)}},CallExpression(g){if(g.node.callee.type==="Import"){d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:f.path},g.stop();return}g.node.callee.type==="Identifier"&&g.node.callee.name==="require"&&(d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:f.path},g.stop())},NewExpression(g){g.node.callee.type==="Identifier"&&g.node.callee.name==="Function"&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:f.path},g.stop())},MetaProperty(g){g.node.meta.type==="Identifier"&&g.node.meta.name==="import"&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:f.path},g.stop())},MemberExpression(g){let h=Sd(g.node);h&&ca.has(h)&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},OptionalMemberExpression(g){let h=Sd(g.node);h&&ca.has(h)&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&ca.has(g.node.name)&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${g.node.name}.`,file:f.path},g.stop())},JSXAttribute(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name==="style"&&(d??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:f.path},g.stop())},JSXOpeningElement(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name.toLowerCase()==="style"&&(d??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:f.path},g.stop())}}),d)return{ok:!1,error:d}}if(!hd.test(n))return Sn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return Sn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!NS(l,r))return Sn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[f,m]of c)if(m.size!==1)return Sn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",f);return PS(n,a).size!==e.length?Sn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:ua,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function xd(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return e.source.startsWith("@/components/site/generated/")?{allowed:!1}:{allowed:e.allowedExternalImports.some(o=>o.endsWith("/")?e.source.startsWith(o):e.source===o)};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Xt.posix.normalize(Xt.posix.join(Xt.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 wS(e){let t=Xt.posix.dirname(e.importer),n=Xt.posix.dirname(e.imported),r=Xt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Xt.posix.basename(e.imported).slice(0,-ci.length),i=`./${r}${ci}`;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 NS(e,t){for(let n of e.program.body){if(t.kind==="default"&&n.type==="ExportDefaultDeclaration")return!0;if(t.kind!=="named"||n.type!=="ExportNamedDeclaration")continue;if(n.specifiers.some(o=>o.exported.type==="Identifier"&&o.exported.name===t.name))return!0;let r=n.declaration;if((r?.type==="FunctionDeclaration"||r?.type==="ClassDeclaration")&&r.id?.name===t.name||r?.type==="VariableDeclaration"&&r.declarations.some(o=>o.id.type==="Identifier"&&o.id.name===t.name))return!0}return!1}function PS(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 Sn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function AS(e){let t=Id(e);return t===ua?t:null}function TS(e){let t=e.trim().toLowerCase();return hS.test(t)?t:null}function vd(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 gS.test(t)?t:null}function Id(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Xt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function FS(e){let t=Id(e);return!t||t!==e?null:t}function kd(...e){return Xt.posix.join(...e)}function bd(e){return new Set(e.map(t=>t.pathTemplate))}function _S(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 OS(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Sd(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 Ca}from"node:crypto";import xa from"@babel/traverse";function da(e){let t=new Map,n=new Map;for(let s of e){if(t.has(s.placementKey))throw new Error(`Duplicate placement key in page composition projection: ${s.placementKey}`);t.set(s.placementKey,s);let a=n.get(s.placementUnitKey)??[];a.push(s),n.set(s.placementUnitKey,a)}let r=new Map,o=new Map,i=new Map;for(let[s,a]of n){let c=Object.freeze([...a]),l=c.find(u=>u.anchorSourceRange!==null&&u.members.length>0)??c.find(u=>u.members.length>0)??c[0];l&&(o.set(s,c),i.set(s,l),r.set(s,Object.freeze({placementUnitKey:s,placementKeys:Object.freeze(c.map(u=>u.placementKey)),sourcePlacementKey:l.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}import{createHash as MS}from"node:crypto";import Cd from"node:path";import*as Pd from"@babel/parser";import fa from"@babel/generator";import*as $e from"@babel/types";var Rd=typeof fa=="function"?fa:fa.default;function ma(e){let t=Fd(e);if(t)return{ok:!1,error:t};let n=e.projection,r=ya(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=BS(n,o),s={jsx:`<${e.component.localName} />`},a=DS(e);if(i){let d=Ad(e);return d.ok?{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:a,rewriteStep:{kind:"insert-root-expression",locator:d.locator,sourceHash:d.sourceHash,node:s,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:d.result}let c=o.containerSourceRange??n.container.sourceRange,l=o.containerSourceHash??(ha(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return pa("Route page composition does not expose a verifiable container boundary.");let u=Ar(c),f=wd(e.source,u,l,"Route page composition container");if(!f.ok)return f.result;let m=o.anchorSourceRange?Ar(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return pa("Route page composition placement does not expose a verifiable anchor boundary.");let d=wd(e.source,m,o.anchorSourceHash,"Route page composition anchor");if(!d.ok)return d.result}return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:a,rewriteStep:{kind:"insert-child",parentLocator:u,node:s,placement:o.relation,...m?{anchorLocator:m}:{}}}}}function DS(e){let t=US(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 ui(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return En(e.source,"Root expression rewrite requires an exact expression locator.");let t=mr(e.source,"value");if(!t.ok)return En(e.source,t.diagnostic.message);let n=ie(t.ast,e.locator);if(!n.ok)return En(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return En(e.source,"Resolved value locator does not point to an expression.");let o=Hn(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return En(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith($e.nullLiteral()),{ok:!0,source:Rd(t.ast,{}).code};let i;try{i=Pd.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return En(e.source,s instanceof Error?s.message:String(s))}return!$e.isJSXElement(i)&&!$e.isJSXFragment(i)?En(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(LS(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Rd(t.ast,{}).code})}function LS(e,t,n,r){if($e.isNullLiteral(e)||r)return t;let o=$e.isJSXFragment(e)?[...e.children]:[$e.isJSXElement(e)?e:$e.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return $e.jsxFragment($e.jsxOpeningFragment(),$e.jsxClosingFragment(),s)}function En(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function ga(e){let t=Fd(e);if(t)return{ok:!1,error:t};let n=e.projection,r=_d(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(jS(n,o)){let h=Ad(e);return h.ok?e.operation==="move-node"?pa("A singleton root expression cannot be moved without a safe parent boundary."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:h.sourceHash,rewriteStep:{kind:e.operation==="remove-node"?"remove-root-expression":"replace-root-expression",locator:h.locator,sourceHash:h.sourceHash}}}:h.result}let s=Ar(o.sourceRange),a=Nt(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?[]:[Pr(a.diagnostic)]}};if(Hn(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")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:"remove-node",locator:s}}};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||!VS(e.targetPlacement.composition,e.composition))return{ok:!1,error:{code:"CROSS_PAGE_MOVE_UNSUPPORTED",message:"Page-unit move across routes or composition templates is not supported.",diagnostics:[]}};if(e.targetPlacement.documentVersion!==e.expectedDocumentVersion)return{ok:!1,error:{code:"VERSION_STALE",message:"Page-unit target placement belongs to a different document version.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Page-unit target placement belongs to a different document version."}]}};let l=ya(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!l.ok)return{ok:!1,error:{code:l.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:l.diagnostic.message,diagnostics:[l.diagnostic]}};let u=l.placement;if(u.placementUnitKey!==e.targetPlacement.placementUnitKey||u.relation!==e.targetPlacement.relation)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit target placement metadata does not match the cached projection.",diagnostics:[]}};let f=u.containerSourceRange;if(!f||!u.containerSourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable container boundary.",diagnostics:[]}};let m=Ar(f),d=Nt(e.source,m);if(!d.ok||!d.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:d.ok===!1?d.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:d.ok?[]:[Pr(d.diagnostic)]}};if(Hn(e.source,d.match.node.start??null,d.match.node.end??null)!==u.containerSourceHash)return Nd("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let h=u.anchorSourceRange,E=u.anchorSourceHash;if(!h||!E)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let S=Ar(h),v=Nt(e.source,S);return!v.ok||!v.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:v.ok===!1?v.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:v.ok?[]:[Pr(v.diagnostic)]}}:Hn(e.source,v.match.node.start??null,v.match.node.end??null)!==E?Nd("Route page composition target anchor hash no longer matches the current source."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:m,anchorLocator:S,placement:u.relation}}}}return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:m,placement:u.relation}}}}function BS(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&ha(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 jS(e,t){return e.container.kind!=="jsx-container"&&ha(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function Ad(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Nt(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?[]:[Pr(r.diagnostic)]}}}:Hn(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Td("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function wd(e,t,n,r){let o=Nt(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?[]:[Pr(o.diagnostic)]}}}:Hn(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Td(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Td(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function pa(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Nd(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Pr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Fd(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&&!$S(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 $S(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function VS(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function US(e,t){let n=Cd.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Cd.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Ar(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Hn(e,t,n){return t==null||n==null?null:`sha256:${MS("sha256").update(e.slice(t,n)).digest("hex")}`}function ha(e,t){return e===null||t===null?e===t:e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}var KS=typeof xa=="function"?xa:xa.default;function Ld(e){if(!e.ast)return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=ZS(e.ast);if(!t)return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=qS(t);if(!n.ok)return St(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=tE(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(rE(r,t))return St(e,[Be("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return Sa(e,t,"virtual-route-root",r);if(nE(r)){let o=aE({input:e,source:e.source,expression:r});return ba(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Oe(r)&&!en(r)){let o=Ia(r),i=Dd({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return ba(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=iE(r);if(!o.ok)return St(e,[o.diagnostic]);let i=Wn(o.path);if(i.unsupported)return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(oE(e.source,r,i.members))return Sa(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Oe(r);if(i.members.length===0&&s)return Sa(e,t,"virtual-route-root",r);let a=o.path===r&&s?"virtual-route-root":"jsx-container",c=o.path.isJSXFragment()?"jsx-fragment":"jsx-element",l=Dd({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return ba(e,t,l,{kind:a,sourceKind:c},r)}return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function ya(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Be("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:Be("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function _d(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Be("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:Be("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Bd(e){return e.ok?JS(e.projection):XS(e.projection)}function JS(e){let t=new Map,n=[];for(let l of e.placements)l.members.length===0&&e.placements.length>1||l.members.length>0&&!l.anchorSourceRange||t.has(l.placementUnitKey)||t.set(l.placementUnitKey,l);let r=new Map,o=new Map;for(let[l,u]of t){let f=u.members.flatMap((h,E)=>jd(e,u,h,E,e.container.placementKey)),m=f.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>HS(l,h,u.independent)),d=f.length>0?f:[{sourceMember:{key:`source:${l}:empty`,kind:e.container.kind==="starter-placeholder"?"starter-placeholder":"null-return",containerKey:e.container.placementKey,label:"empty-page",sourceFile:e.entryFile,isAtomic:!0},member:null}];r.set(l,d.map(({sourceMember:h})=>h)),o.set(l,m);let g=d[0]?.sourceMember.key??l;n.push({key:l,containerKey:g,businessMemberKeys:m.map(h=>h.key),isMultiMember:u.memberCount>1})}let i=[...r.values()].flat(),s=[...o.values()].flat(),a=i[0]?.key??null,c=e.placements.map(l=>({kind:"page-composition",placementKey:l.placementKey,documentVersion:e.documentVersion,composition:e.composition,placementUnitKey:l.placementUnitKey,relation:l.relation}));return{status:"supported",version:e.version,composition:e.composition,container:zS(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function XS(e){let t=e.diagnostics.map(WS);return{status:"unsupported",version:e.version,composition:e.composition,reason:GS(e.diagnostics),diagnostics:t}}function zS(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 jd(e,t,n,r,o){let i=`source:${t.placementUnitKey}:${r}:${n.memberKey}`;return[{sourceMember:{key:i,kind:n.kind==="jsx-element"?"jsx-element":"jsx-expression",containerKey:o,label:n.label,sourceFile:e.entryFile,isAtomic:n.kind!=="jsx-element"},member:n},...n.children.flatMap((a,c)=>jd(e,t,a,c,i))]}function HS(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function WS(e){return{code:YS(e),message:e.message}}function GS(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 YS(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 ZS(e){let t=null;return KS(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=QS(o.path);i&&(t=i,n.stop())}}),t}function QS(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 qS(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Fr(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Be("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:Be("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Be("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(!eE(s))return{ok:!1,diagnostic:Be("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if($d(s)||Vd(s))return{ok:!1,diagnostic:Be("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=Fr(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Be("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function eE(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($d(o)||Vd(o))return null;return r}function $d(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function Vd(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function tE(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=Fr(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 nE(e){return e.isConditionalExpression()?Od(Fr(e.get("consequent")))&&Od(Fr(e.get("alternate"))):!1}function Od(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Fr(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 rE(e,t){if(e.isIdentifier())return Md(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Md(n.node.name,t)}return!1}function Md(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 oE(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&va(t)}function va(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(!va(t))return!1;continue}if(t.isJSXElement()&&!va(t))return!1}return!0}function iE(e){let t=e;if(e.isJSXFragment()||Oe(e)){let r=Tr(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&en(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&en(t);){let r=Tr(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!en(o))return{ok:!0,path:t};if(Tr(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function Tr(e){let t=[];for(let n of e.get("children"))if(!Array.isArray(n)){if(n.isJSXText()){n.node.value.trim()&&t.push(n);continue}if(n.isJSXExpressionContainer()){let r=n.get("expression");!r.isJSXEmptyExpression()&&!r.isNullLiteral()&&t.push(n);continue}if(n.isJSXFragment()){t.push(...Tr(n));continue}n.isJSXElement()&&(Oe(n)?t.push(...Tr(n)):t.push(n))}return t}function Wn(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:ka(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:mt(r.node.loc),businessMemberCount:0,parentSourceRange:mt(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=Wn(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=en(o)?Wn(o):null;n||=i?.unsupported??!1,t.push({...Ia(o,i?.members),sourceRange:mt(r.node.loc),parentSourceRange:mt(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:ka(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:mt(r.node.loc),businessMemberCount:1,parentSourceRange:mt(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Oe(r)){let o=Wn(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=en(r)?Wn(r):null;n||=o?.unsupported??!1,t.push({...Ia(r,o?.members),parentSourceRange:mt(e.node.loc)})}}return{members:t,unsupported:n}}function Ia(e,t){let n=e.isJSXElement()&&en(e)?t??Wn(e).members:[],r=e.isJSXElement()&&!en(e)&&!Oe(e);return{memberKey:ka(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:mt(e.node.loc),businessMemberCount:r?1:Ud(n),parentSourceRange:mt(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:sE(e)}}function en(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function sE(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 Ud(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function di(e){return e.length===0?0:Math.max(1,Ud(e))}function Dd(e){let t=mt(e.containerPath.node.loc),n=Ra(e.source,e.containerPath.node.start,e.containerPath.node.end),r=gt(e.input,e.containerKind,e.sourceKind,t),o=gt(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:di(e.members)<=1,memberCount:di(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function aE(e){let t=mt(e.expression.node.loc),n=Ra(e.source,e.expression.node.start,e.expression.node.end),r=gt(e.input,"virtual-route-root","atomic-expression",t),o=gt(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:gt(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 Kd(e,t){let n=mt(t.node.loc),r=Ra(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function ba(e,t,n,r,o){let i=Kd(e,o);if(!i)return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=cE(e,n,s),c=da(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Xd(t),container:{kind:r.kind,placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,version:e.version,isEmptyPage:n.memberCount===0,sourceKind:r.sourceKind,sourceRange:s,sourceHash:n.sourceHash},placements:a,diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:i};return Object.defineProperties(l,{placementByKey:{value:c.placementByKey,enumerable:!1},unitByKey:{value:c.unitByKey,enumerable:!1},placementsByUnitKey:{value:c.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:c.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:l}}function cE(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,f,m,d,g,h=n)=>({...t,placementKey:u,placementUnitKey:f,containerKey:t.placementKey,independent:di(g)<=1,memberCount:di(g),sourceRange:m,sourceHash:m?Ea(e.source,m):null,relation:l,containerSourceRange:h,containerSourceHash:h?Ea(e.source,h):null,anchorSourceRange:d,anchorSourceHash:d?Ea(e.source,d):null,members:g}),i=t.placementKey,s=t.members.map(l=>gt(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",gt(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,f=gt(e,i,"placement-unit",l.sourceRange);r.push(o("before",gt(e,f,"before",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",gt(e,f,"after",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function Sa(e,t,n,r){let o=Kd(e,r);if(!o)return St(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=gt(e,n,"empty-container",void 0),s=gt(e,n,"empty-unit",void 0),a={placementKey:i,placementUnitKey:s,version:e.version,containerKey:i,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},c=da([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Xd(t),container:{kind:n,placementKey:i,placementUnitKey:s,version:e.version,isEmptyPage:!0,sourceKind:n==="starter-placeholder"?"starter-placeholder":"jsx-fragment",sourceRange:null,sourceHash:null},placements:[a],diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:o};return Object.defineProperties(l,{placementByKey:{value:c.placementByKey,enumerable:!1},unitByKey:{value:c.unitByKey,enumerable:!1},placementsByUnitKey:{value:c.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:c.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:l}}function St(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 Be(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function gt(e,t,n,r){return Jd([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function ka(e,t,n){return Jd(["member",e,String(t??-1),String(n??-1)])}function Jd(e){return`pc_${Ca("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Ra(e,t,n){return t==null||n==null?null:`sha256:${Ca("sha256").update(e.slice(t,n)).digest("hex")}`}function Ea(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:${Ca("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function mt(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Xd(e){if(e.isFunctionDeclaration())return e.node.id?.name??null;let t=e.parentPath;return t?.isVariableDeclarator()&&t.node.id.type==="Identifier"?t.node.id.name:null}import{PageTemplateIdSchema as SE}from"@vcp-dev/contracts";import UA from"node:fs";import JA from"node:path";var uE=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function _r(e){let t=e.map(r=>bE(r.path)),n=dE(t);return n?t.filter(r=>pE(n,r)).map(r=>({routeId:mE(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function wa(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=xE(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function dE(e){return e.some(r=>r.startsWith("app/")&&!fE(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function fE(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function pE(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return uE.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function mE(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(hE).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function gE(e){return e.startsWith("(")&&e.endsWith(")")}function hE(e){return!e||e.startsWith("@")||e.startsWith("_")||gE(e)?null:yE(e)}function yE(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function xE(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function bE(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Or=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function Ze(e,t={}){throw new Or("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Na(e){return SE.safeParse(e).success||Ze("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function zd(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||Ze("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return Ze("invalid-template-key",{path:e})}return Na(t)!==e&&Ze("noncanonical-template-key",{path:e}),t}function EE(e){let t=wa(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("(")||vE(r)&&!Hd(r)))&&Ze("invalid-public-route",{routeId:e}),t}function vE(e){return e.includes("[")||e.includes("]")}function Hd(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function Wd(e){return e.some(Hd)}function Gd(e,t,n="app"){n!=="app"&&n!=="src/app"&&Ze("invalid-app-root");let r=EE(e),o=Na(t),i=Wd(r.slice(1).split("/")),s=i?`${n}/.vcp/page-templates/${o}${r}`:`${n}/.vcp/page-templates${r==="/"?"":r}`,a=i?`${s}/page.tsx`:`${s}/${o}/page.tsx`;return(Buffer.byteLength(a,"utf8")>4095||a.split("/").some(c=>Buffer.byteLength(c,"utf8")>255))&&Ze("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function Yd(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function Zd(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===".")&&Ze("invalid-file-path",{path:i}),n.has(i)&&Ze("duplicate-file-path",{path:i}),n.set(i,o)}return n}function pi(e){let t=Zd(e.files),n=_r([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Or("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(!Yd(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||Ze("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=Wd(c),u=l?c[0]:c.pop(),f=l?c.slice(1):c,m=zd(u),d=f.length?`/${f.join("/")}`:"/";Gd(d,m,a).templateEntryFile!==i&&Ze("candidate-path-mismatch",{path:i,routeId:d});let h=r.get(d);(!h||!h.startsWith(`${a}/`))&&Ze("canonical-entry-missing",{path:i,routeId:d}),o.push({routeId:d,templateId:m,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>fi(i.routeId,s.routeId)||fi(i.templateId,s.templateId))}function Qd(e){let t=Zd(e.files),n=pi({files:t}),r=_r([...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)=>fi(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:fi(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function IE(e){let t=wa(e.selector.routeId),n=Qd({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&Ze("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||Ze("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function fi(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as LE}from"@vcp-dev/contracts";import{parse as XT}from"@babel/parser";import{parse as qA}from"@babel/parser";import{FormBlockIdSchema as tT,FormSpecV1Schema as nT}from"@vcp-dev/contracts";var Mr="components/site/generated/forms",rT=`${Mr}/vcp-form-runtime.tsx`,mi="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",oT=new RegExp(`^${Mr}/form-(${mi})\\.spec\\.ts$`),iT=new RegExp(`^${Mr}/form-(${mi})\\.tsx$`),sT=new RegExp(`^@/${Mr}/form-(${mi})$`),aT=new RegExp(`(?:^|/)${Mr}/form-(${mi})(?:\\.tsx?)?$`);var cT=Symbol("invalid-literal");import{createHash as dT}from"node:crypto";import{posix as pT}from"node:path";import{parse as gT}from"@babel/parser";import{FormSpecV1Schema as yT}from"@vcp-dev/contracts";var xT=Symbol("dynamic");import{parse as kE}from"@babel/parser";function gi(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var CE=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function RE(e){let t=CE.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 wE(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function qd(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function NE(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Pa(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(Pa);if(t?.type==="ObjectExpression"){let n={};for(let r of gi(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=qd(r.key);if(!o)throw new Error("unsupported object key");n[o]=Pa(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Aa(e,t){let n=[],r=RE(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=kE(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(l){return n.push({code:"page-seo.parse-failed",message:l instanceof Error?l.message:String(l)}),{found:!1,seo:null,diagnostics:n}}let i;for(let l of gi(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let f of gi(u.declarations)){let m=f.id;m?.type==="Identifier"&&m.name==="PAGE_SEO"&&(i=f.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=NE(i);if(!s)return{found:!1,seo:null,diagnostics:n};if(s.type!=="ObjectExpression")return n.push({code:"page-seo.dynamic-declaration",message:"PAGE_SEO is not a static object literal"}),{found:!1,seo:null,diagnostics:n};let a={};for(let l of gi(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=qd(l.key);if(!(u!=="path"&&u!=="title"&&u!=="description"&&u!=="keywords"&&u!=="meta_tags_json"&&u!=="schema_json"&&u!=="breadcrumbs_json")){if(u==="path"||u==="title"||u==="description"||u==="keywords"){let f=wE(l.value);if(f===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static string; skipped`});continue}a[u]=f;continue}try{let f=Pa(l.value);u==="meta_tags_json"&&f!==null&&typeof f=="object"&&!Array.isArray(f)?a.meta_tags_json=f:u==="schema_json"&&f!==null&&typeof f=="object"?a.schema_json=f:u==="breadcrumbs_json"&&Array.isArray(f)?a.breadcrumbs_json=f:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} has unsupported static shape; skipped`})}catch(f){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static JSON-like value; skipped: ${f instanceof Error?f.message:String(f)}`})}}}let c=r;return a.path!==void 0&&(a.path!==r&&n.push({code:"page-seo.path-mismatch",message:`PAGE_SEO.path "${a.path}" != derived "${r}"; using PAGE_SEO.path`}),c=a.path),{found:!0,seo:{path:c,...a.title!==void 0?{title:a.title}:{},...a.description!==void 0?{description:a.description}:{},...a.keywords!==void 0?{keywords:a.keywords}:{},...a.meta_tags_json!==void 0?{meta_tags_json:a.meta_tags_json}:{},...a.schema_json!==void 0?{schema_json:a.schema_json}:{},...a.breadcrumbs_json!==void 0?{breadcrumbs_json:a.breadcrumbs_json}:{}},diagnostics:n}}import{parse as PE}from"@babel/parser";var ef=["page","anchor","external","email","phone","group","file"],AE=["link","cta"],nf=["description","badge","iconKey"],Ta=["label","targetType","href","role","openInNewTab","nofollow","children",...nf],TE=new Set(Ta);function Lr(e){return Array.isArray(e)?e:[]}function Dr(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function FE(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function tf(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Fa(e){let t=[],n;try{n=PE(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 Lr(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of Lr(s.declarations)){let c=a.id;c?.type==="Identifier"&&c.name==="NAV_ITEMS"&&(r=a.init)}}for(;r&&(r.type==="TSAsExpression"||r.type==="TSSatisfiesExpression"||r.type==="TSInstantiationExpression");)r=r.expression;if(!r||r.type!=="ArrayExpression")return{items:[],diagnostics:[{severity:"fatal",path:"NAV_ITEMS",message:"missing top-level NAV_ITEMS array literal"}]};let o=[];return Lr(r.elements).forEach((i,s)=>{let a=rf(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function rf(e,t,n){if(e?.type!=="ObjectExpression")return n.push({severity:"fatal",path:t,message:"nav item must be an object literal"}),null;let r={};for(let l of Lr(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=FE(l.key);u&&(r[u]=l.value)}let o=Dr(r.label),i=Dr(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!ef.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${ef.join("/")}`}),null;r.group!==void 0&&n.push({severity:"warning",code:"leaf-group-field",path:`${t}.group`,message:'unsupported leaf group field ignored; use a canonical targetType: "group" node with children'});let s={label:o,targetType:i};for(let l of nf){if(r[l]===void 0)continue;let u=Dr(r[l]);u!==void 0?s[l]=u:n.push({severity:"warning",path:`${t}.${l}`,message:`${l} ignored: not a static string`})}r.icon!==void 0&&n.push({severity:"warning",path:`${t}.icon`,message:"icon component ref ignored; use static iconKey"});for(let l of Object.keys(r))TE.has(l)||l==="group"||l==="icon"||n.push({severity:"warning",code:"unknown-field",path:`${t}.${l}`,message:`unsupported field \`${l}\` ignored; NAV_ITEMS only carries ${Ta.join("/")}`});if(r.children!==void 0){if(r.children.type!=="ArrayExpression")return n.push({severity:"fatal",path:`${t}.children`,message:"children must be a static array"}),null;let l=[];Lr(r.children.elements).forEach((u,f)=>{let m=rf(u,`${t}.children[${f}]`,n);m&&l.push(m)}),s.children=l}if(i==="group")return s.children?s:(n.push({severity:"fatal",path:`${t}.children`,message:"group item requires children"}),null);let a=Dr(r.href);if(!a)return n.push({severity:"fatal",path:`${t}.href`,message:"href must be a static string for non-group item"}),null;s.href=a;let c=Dr(r.role);if(c!==void 0&&(AE.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=tf(r.openInNewTab);l!==void 0?s.openInNewTab=l:n.push({severity:"warning",path:`${t}.openInNewTab`,message:"openInNewTab ignored: not a static boolean"})}if(r.nofollow!==void 0){let l=tf(r.nofollow);l!==void 0?s.nofollow=l:n.push({severity:"warning",path:`${t}.nofollow`,message:"nofollow ignored: not a static boolean"})}return s}import{parse as _E}from"@babel/parser";function Br(e){return Array.isArray(e)?e:[]}function of(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function OE(e){let t;try{t=_E(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of Br(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of Br(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=of(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 _a(e,t){let n=sf(t);if(!n)return{status:"unsupported",source:e};let r=OE(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Fa(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=Br(l.elements);for(let[f,m]of u.entries()){if(DE(m,n)){let g=u[f+1],h=u[f-1],E=m.start,S=m.end;if(typeof E!="number"||typeof S!="number")continue;if(g&&typeof g.start=="number")s.push({start:E,end:g.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:S});else{let v=/^\s*,/.exec(e.slice(S));s.push({start:E,end:v?S+v[0].length:S})}continue}let d=ME(m);d&&a(d)}};if(a(o),s.length===0)return{status:"not_found",source:e};let c=e;for(let l of s.sort((u,f)=>f.start-u.start))c=c.slice(0,l.start)+c.slice(l.end);return{status:"removed",source:c,removedCount:s.length}}function ME(e){if(e.type==="ObjectExpression")for(let t of Br(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return of(t.value)}}function sf(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function DE(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Br(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"&&sf(n??"")===t}import{estimateNavLabelWidth as NT}from"@vcp-dev/contracts";import{parse as TT}from"@babel/parser";var BE="components/site/generated/",jr=[".tsx",".ts",".jsx",".js"];function af(e){if(e.expectedUrlPath===LE)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(_r(Object.keys(e.files).map(m=>({path:m}))).map(m=>m.entryFile)),n=Object.entries(e.files).filter(([m,d])=>{let g=m.replace(/\\/g,"/");if(!t.has(g))return!1;let h=Aa(d,g);return h.found&&h.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];try{if(pi({files:new Map(Object.entries(e.files))}).some(d=>d.canonicalEntryFile===r))return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:"Clean up page template candidates before deleting their canonical page."}}catch(m){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:m instanceof Error?m.message:"Invalid page template source."}}let o=jE(e.files);if(!o.ok)return o.error;let i=o.graph,s=KE(r,i),a=JE(r,s,i),c=[...s].filter(m=>!a.has(m)).sort((m,d)=>m.localeCompare(d)),l=[{operation:"delete",file:r},...[...a].sort((m,d)=>m.localeCompare(d)).map(m=>({operation:"delete",file:m}))],u=[],f=[];for(let[m,d]of Object.entries(e.files))if(m!==r){if(d.includes("NAV_ITEMS")){let g=_a(d,e.expectedUrlPath);g.status==="removed"?(l.push({operation:"upsert",file:m,content:g.source}),u.push(m)):g.status==="unsupported"&&f.push(`unsupported_navigation:${m}`)}d.includes(e.expectedUrlPath)&&!d.includes("NAV_ITEMS")&&f.push(`preserved_link:${m}`)}return{ok:!0,edits:l,deletedFiles:[r,...[...a].sort((m,d)=>m.localeCompare(d))],updatedFiles:u,preservedSharedFiles:c,warnings:f}}function jE(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")||!$E(r))continue;let s=kr(r,o);if(!s.ok)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} (parse-failed).`}};let a=new Set;for(let{specifier:c}of s.module.imports){if(VE(c))continue;let l=Ir(r,c),u=UE(l,t);if(!u)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${c} (import-not-found).`}};a.add(u)}n.set(r,a)}return{ok:!0,graph:n}}function $E(e){let t=e.toLowerCase();return jr.some(n=>t.endsWith(n))}function VE(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!jr.some(n=>e.endsWith(n)))}function UE(e,t){let n=e.replace(/\\/g,"/");return(jr.some(o=>n.endsWith(o))?[n]:[...jr.map(o=>`${n}${o}`),...jr.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function KE(e,t){let n=new Set,r=[...t.get(e)??[]];for(;r.length>0;){let o=r.pop();!o.startsWith(BE)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function JE(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,c])=>a!==e&&!r.has(a)&&c.has(i))&&(r.delete(i),o=!0)}return r}import*as ip from"@babel/parser";import*as le from"@babel/types";import*as _i from"node:path";import*as ge from"@babel/types";function cf(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 Ft(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return vn(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(ge.isObjectPattern(n)||ge.isArrayPattern(n))return vn(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(zE(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function vn(e,t,n=!1){return ge.isIdentifier(e)?e.name===t&&n:ge.isObjectPattern(e)?e.properties.some(r=>ge.isObjectProperty(r)?vn(r.value,t,n):vn(r.argument,t,n)):ge.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=ge.isRestElement(r)?r.argument:r;return vn(o,t,n)}):ge.isAssignmentPattern(e)?vn(e.left,t,!0):ge.isRestElement(e)?vn(e.argument,t,n):!1}function Gn(e,t){if(e.path.isObjectPattern()){if(t){let r=Et(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Ft(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Ft(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=lf(r),i=!1,s=o?o.initBinding&&Oa(o.initBinding)?(i=Ft(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=Gn(o.initBinding,{kind:"identifier",expression:o.initBinding.identifier.name,base:o.initBinding.identifier.name,path:[]});return i=c?.hasDefault??!1,c?[{kind:"property",name:c.propName},...c.remainingPath,...o.initPathPrefix]:null})():null:null,a=Et(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...u]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||Ft(e)}}}}let n=GE(e);if(n){let r=XE(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||Ft(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=HE(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Ft(e)}}let i=$r(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Ft(e)}:null}if(Oa(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Ft(e)}}return null}function XE(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=lf(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Oa(i)?(a=Ft(i),[...s]):(()=>{let u=Gn(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=u?.hasDefault??!1,u?[{kind:"property",name:u.propName},...u.remainingPath,...s]:null})();if(!c)return null;let l=Et(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Ft(t)}:null}function lf(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=YE(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Oa(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function zE(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function HE(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=Et(i.node,t);if(a)return a}return null}function uf(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=hi(a,e.identifier.name);if(c&&(!n||c.propName===n))return{propName:c.propName,componentName:t,expressionPath:c.expressionPath,displayPath:`${t}.${c.propName}.default`}}}if(e.path.isObjectPattern())for(let a of e.path.get("properties")){if(!a.isObjectProperty())continue;let c=$r(a.node);if(!c||n&&c!==n)continue;let l=a.get("value");if(!l.isAssignmentPattern())continue;let u=l.get("right");if(u.isExpression())return{propName:c,componentName:t,expressionPath:u,displayPath:`${t}.${c}.default`}}let r=WE(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=$r(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 hi(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=$r(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&Et(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=hi(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=hi(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=hi(r,t);if(o)return o}}return null}function Et(e,t,n=[]){if(ge.isIdentifier(e))return e.name===t?n:null;if(ge.isObjectPattern(e)){for(let r of e.properties)if(ge.isObjectProperty(r)){let o=$r(r);if(!o)continue;let i=Et(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(ge.isRestElement(r)){let o=Et(r.argument,t,n);if(o)return o}}if(ge.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=ge.isRestElement(o)?o.argument:o,s=Et(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return ge.isAssignmentPattern(e)?Et(e.left,t,n):null}function WE(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function GE(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 $r(e){return e.computed?null:ge.isIdentifier(e.key)?e.key.name:ge.isStringLiteral(e.key)?e.key.value:null}function YE(e){let t=[],n=e;for(;ge.isMemberExpression(n);){if(n.computed)if(ge.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ge.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ge.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ge.isIdentifier(n)?{base:n.name,path:t}:null}import*as gf from"@babel/parser";import La from"@babel/traverse";import*as Yn from"@babel/types";import*as oe from"@babel/types";function bi(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?yi(n,t):null}if(e.isMemberExpression()){let n=nv(e.node),r=ZE(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?yi(o,[...r,...t]):null}return e.isAwaitExpression()||Da(e.node)?tn(ov(e.node),t,"awaited or fetched expression"):null}function ZE(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 yi(e,t=[]){let n=QE(e,t);if(n)return n;let r=qE(e,t);if(r)return r;let o=ev(e,t);return o||null}function Ur(e){return e?.kind==="api-source"}function QE(e,t){if(e.path.isVariableDeclarator()&&oe.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Ma(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return tn(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(c=>oe.isObjectProperty(c)&&pf(c)==="data"&&Vr(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Ma(a.node))return tn(e.identifier.name,t,"query hook data binding")}let n=tv(e);if(!n||pf(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()||!Ma(i.node)?null:tn(e.identifier.name,t,"query hook data binding")}function qE(e,t){if(e.path.isVariableDeclarator()&&oe.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!ff(a.node))return null;let[c,l]=e.path.node.id.elements;return!oe.isIdentifier(c)||c.name!==e.identifier.name||!oe.isIdentifier(l)?null:df(e,l.name)?tn(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let n=e.path.parentPath;if(!n?.isArrayPattern())return null;let r=n.parentPath;if(!r?.isVariableDeclarator())return null;let o=r.get("init");if(!o?.isCallExpression()||!ff(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return oe.isIdentifier(s)&&df(e,s.name)?tn(e.identifier.name,t,"state setter is updated by API data"):null}function ev(e,t){let n=e.path.isVariableDeclarator()?e.path:e.path.findParent(o=>o.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");return r?.isExpression()?r.isAwaitExpression()?tn(e.identifier.name,t,"awaited binding result"):Da(r.node)?tn(e.identifier.name,t,"fetch-backed binding result"):null:null}function tv(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 Vr(e,t){return oe.isIdentifier(e)?e.name===t:oe.isAssignmentPattern(e)?Vr(e.left,t):oe.isObjectPattern(e)?e.properties.some(n=>oe.isObjectProperty(n)?Vr(n.value,t):Vr(n.argument,t)):oe.isArrayPattern(e)?e.elements.some(n=>!!n&&Vr(oe.isRestElement(n)?n.argument:n,t)):!1}function df(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Da(i.node)&&(n=!0),(rv(i.node.callee,t)||i.node.arguments.some(s=>oe.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function Ma(e){let t=Si(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function ff(e){return Si(e.callee)==="useState"}function Da(e){return xi(e,t=>oe.isCallExpression(t)&&Si(t.callee)==="fetch")}function nv(e){let t=e;for(;oe.isMemberExpression(t);)t=t.object;return oe.isIdentifier(t)?t.name:null}function pf(e){return e.computed?null:oe.isIdentifier(e.key)?e.key.name:oe.isStringLiteral(e.key)?e.key.value:null}function Si(e){return oe.isIdentifier(e)?e.name:oe.isMemberExpression(e)&&oe.isIdentifier(e.property)?e.property.name:null}function rv(e,t){return xi(e,n=>oe.isIdentifier(n)&&n.name===t)}function xi(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)&&xi(i,t))return!0;continue}if(oe.isNode(o)&&xi(o,t))return!0}return!1}function ov(e){return oe.isIdentifier(e)?e.name:oe.isCallExpression(e)?Si(e.callee)??"api":oe.isAwaitExpression(e)?"awaited-api":"api"}function tn(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:iv(e,t),reason:n}}function iv(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var hf=typeof La=="function"?La:La.default;function yf(e,t){let n=bf(e);if(!n)return{allowed:!0};let r=!1;return hf(n,{CallExpression(o){if(!Sf(o.node,t.sourceRange)||!sv(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||Ur(bi(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function xf(e,t){let n=bf(e);if(!n)return{allowed:!0};let r=!1;return hf(n,{JSXExpressionContainer(o){Sf(o.node,t.sourceRange)&&(Yn.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 bf(e){try{return gf.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function sv(e){let t=e.callee;return Yn.isMemberExpression(t)&&Yn.isIdentifier(t.property)&&t.property.name==="map"}function Sf(e,t){let n=e.loc;return n?mf({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&mf({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function mf(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 V from"@babel/types";import*as Ef from"@babel/parser";import Ba from"@babel/traverse";import*as Re from"@babel/types";import*as Zn from"node:path";var vt=typeof Ba=="function"?Ba:Ba.default;function Ue(e){try{return Ef.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ja(e){return e.computed?Re.isStringLiteral(e.key)||Re.isNumericLiteral(e.key)?String(e.key.value):null:av(e.key)}function av(e){return Re.isIdentifier(e)?e.name:Re.isStringLiteral(e)||Re.isNumericLiteral(e)?String(e.value):null}function In(e){return Re.isParenthesizedExpression(e)||Re.isTSAsExpression(e)||Re.isTSSatisfiesExpression(e)||Re.isTSNonNullExpression(e)||Re.isTSTypeAssertion(e)?In(e.expression):Re.isExpression(e)?e:null}function $a(e){if(Re.isIdentifier(e))return[e.name];if((Re.isMemberExpression(e)||Re.isOptionalMemberExpression(e))&&!e.computed&&Re.isIdentifier(e.property)){let t=In(e.object),n=t?$a(t):null;return n?[...n,e.property.name]:null}return null}function kn(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?Zn.normalize(Zn.join(Zn.dirname(e),t)).replace(/\\/g,"/"):t}function tt(e,t){return Ei(e)===Ei(t)}function Ei(e){let t=Qn(e);return t.endsWith("/index")?t.slice(0,-6):t}function Qn(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function kf(e,t,n){let r=Nf(e,t);if(Pf(e,r),Af(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 vt(e,{JSXElement(s){Of(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:vi(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 Cf(e,t){let n=new Map,r=i=>{let s=qn(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 cv(i,n))o=r(s)||o}return[...n.values()]}function cv(e,t){let n=[],r=lv(e,t);for(let o of e.ast.program.body){if(V.isExportDefaultDeclaration(o)&&V.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=Kr(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(V.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=kn(e.file,o.source.value);for(let s of o.specifiers){if(V.isExportNamespaceSpecifier(s)){let l=nn(s.exported);for(let u of t.values())tt(u.file,i)&&n.push({file:e.file,namespace:Va(l,u.namespace),exportName:u.exportName});continue}if(!V.isExportSpecifier(s))continue;let a=nn(s.local),c=[...t.values()].filter(l=>tt(l.file,i)&&Cn(l.namespace,a));if(c.length>0){let l=nn(s.exported);for(let u of c){let f=Kr(u.namespace,a,l);f&&n.push({file:e.file,namespace:f,exportName:u.exportName})}continue}t.has(qn({file:i,exportName:a}))&&n.push({file:e.file,exportName:nn(s.exported)})}continue}if(V.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!V.isExportSpecifier(i))continue;let s=nn(i.local),a=r.get(s)??[];if(a.length>0){let c=nn(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=Kr(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(V.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=kn(e.file,o.source.value),s=o.exported;if(s){let a=nn(s);for(let c of t.values())tt(c.file,i)&&n.push({file:e.file,namespace:Va(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())tt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Va(e,t){return t?`${e}.${t}`:e}function Cn(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Kr(e,t,n){return!Cn(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function lv(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(!V.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=kn(e.file,i.source.value);for(let a of i.specifiers){if(V.isImportDefaultSpecifier(a)){let c=t.get(qn({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>tt(u.file,s)&&Cn(u.namespace,"default"));for(let u of l){let f=Kr(u.namespace,"default",a.local.name);f&&r(a.local.name,{...u,namespace:f})}continue}if(V.isImportSpecifier(a)){let c=nn(a.imported),l=[...t.values()].filter(f=>tt(f.file,s)&&Cn(f.namespace,c));for(let f of l)r(a.local.name,f);let u=t.get(qn({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(V.isImportNamespaceSpecifier(a))for(let c of t.values())tt(c.file,s)&&r(a.local.name,{...c,namespace:Va(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(V.isVariableDeclaration(i))for(let s of i.declarations){if(!V.isIdentifier(s.id)||!s.init)continue;let a=In(s.init);if(!a||!V.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],u=new Set(l.map(qn));for(let f of c){let m=Kr(f.namespace,a.name,s.id.name),d=m?{...f,namespace:m}:f,g=qn(d);u.has(g)||(r(s.id.name,d),u.add(g),o=!0)}}}return n}function qn(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Ei(e.file)}#${t}`}function nn(e){return V.isIdentifier(e)?e.name:e.value}function Rf(e,t){for(let n of e.program.body){if(V.isExportDefaultDeclaration(n)){let o=n.declaration;if((V.isFunctionDeclaration(o)||V.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(V.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!V.isExportNamedDeclaration(n))continue;let r=n.declaration;if((V.isFunctionDeclaration(r)||V.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(V.isVariableDeclaration(r)){for(let o of r.declarations)if(V.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!V.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:V.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Ka(e){let t=uv(e),n=[],r=Af(e.ast,t);return vt(e.ast,{JSXElement(o){tt(e.file,e.sourceFile)&&vi(o)===e.sourceComponent||Of(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function wf(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Nf(e,t){let n=wf();return vt(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function uv(e){let t=wf();return tt(e.file,e.sourceFile)&&dv(t,Nf(e.ast,e.sourceComponent)),vt(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=kn(e.file,o),s=e.componentIdentities.filter(a=>tt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(V.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),V.isImportDefaultSpecifier(a)){let l=s.filter(u=>Cn(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let f of l){let m=If(f,"default");m&&u.add(m)}t.namespaceMembers.set(c,u)}continue}if(V.isImportSpecifier(a)){let l=V.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(f=>Cn(f.namespace,l));if(u.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let m of u){let d=If(m,l);d&&f.add(d)}t.namespaceMembers.set(c,f);continue}s.some(f=>!f.namespace&&f.exportName===l)&&t.localBindings.add(c);continue}if(V.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,f=t.namespaceMembers.get(c)??new Set;f.add(u),t.namespaceMembers.set(c,f)}}}}}),Pf(e.ast,t),t}function dv(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 Pf(e,t){vt(e,{VariableDeclarator(n){if(!n.node.init)return;let r=In(n.node.init);if(r){if(V.isIdentifier(n.node.id)){let o=Rn(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Ua(t,i,o);return}if(V.isObjectPattern(n.node.id)){let o=Rn(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&_f(n.node.id,o.namespaceMembers,t,n)}}}})}function Af(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return vt(e,{ReferencedIdentifier(r){if(n){r.stop();return}fv(r)||!r.isIdentifier()||!Tf(r,t)||pv(r,t)||mv(r)||(n=!0,r.stop())}}),n}function fv(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 Tf(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)&&Rn(r.node,t,r)?r:null}function pv(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!vf(e,r))return!1;let o=Tf(e,t);if(!o)return!1;if(In(r.node)===o.node)return!!Rn(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&vf(e,a)&&!!Rn(a.node,t,a)}function mv(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function vf(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Rn(e,t,n){let r=In(e);if(!r)return null;if(V.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let c=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:c?{local:!1,namespaceMembers:new Set(c),unsupported:!1}:null}if(V.isObjectExpression(r))return gv(r,t,n);let o=$a(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?Ff(s,o.slice(1).join(".")):null}function gv(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!V.isObjectProperty(i))continue;let s=ja(i);if(!s||!V.isExpression(i.value)){V.isExpression(i.value)&&(o||=Rn(i.value,t,n)!==null);continue}let a=Rn(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let c of a.namespaceMembers)r.add(`${s}.${c}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function Ff(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 Ua(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 _f(e,t,n,r){for(let o of e.properties){if(V.isRestElement(o)){if(V.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Ua(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!V.isObjectProperty(o))continue;let i=ja(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Ff(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=V.isAssignmentPattern(o.value)?o.value.left:o.value;if(V.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Ua(n,c,s);continue}if(V.isObjectPattern(a)&&s.namespaceMembers.size>0){_f(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function If(e,t){if(!Cn(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 Of(e,t){let n=e.node.openingElement.name;if(V.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=Mf(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 Mf(e){if(V.isJSXIdentifier(e))return[e.name];if(V.isJSXMemberExpression(e)){let t=Mf(e.object);return t?[...t,e.property.name]:null}return null}function vi(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()&&V.isIdentifier(n.node.id))return n.node.id.name}return null}function Df(e,t){let n=Ue(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Ka({ast:n,file:t.file,sourceFile:t.file,sourceComponent:t.tag,componentIdentities:[{file:t.importedFrom,exportName:t.exportName}]});return r.hasUnsafeReference?Number.POSITIVE_INFINITY:r.callSites.length}function Se(e){return e.structuralPath.includes("#repeat:")||e.isRepeatItemRoot||e.isRepeatRegion?{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange}:{kind:"jsx-node",strategy:"structural-path",file:e.file,component:e.component,structuralPath:e.structuralPath,expectedRange:e.sourceRange}}function de(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function _t(e,t){let n=de(e);return!!(n&&nt(t,n))}function nt(e,t){return t.start>=e.start&&t.end<=e.end}function Ot(e,t){let n=ie(e,Se(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Ii(e,t)}function er(e,t){let n=de(t);return n?e.slice(n.start,n.end):""}function Lf(e,t){return e.start===t.start&&e.end===t.end}function Ii(e,t){let n=null;return vt(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 ki(e,t){return Ja(e,t).length>0}function Ci(e,t){let n=de(e.node),r=de(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()&&!hv(o,n,r)))return!0;o=o.parentPath}return!1}function hv(e,t,n){let r=de(e.node.consequent);if(r&&nt(r,t)&&!nt(r,n))return!1;let o=e.node.alternate?de(e.node.alternate):null;return!(o&&nt(o,t)&&!nt(o,n))}function Ja(e,t){let n=de(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=de(o.node.consequent),a=de(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()&&Xa(o.node.operator)){let s=de(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 Xa(e){return e==="&&"||e==="||"||e==="??"}function Bf(e,t){let n=de(e.consequent);if(n&&nt(n,t))return n;let r=de(e.alternate);return r&&nt(r,t)?r:null}function jf(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=>Qn(a.file)));if(!t.has(Qn(e.sourceFile))||!t.has(Qn(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(Qn(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=Rf(e.sourceAst,e.sourceComponent);if(!n)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without an exported source component identity"};let r=[];for(let a of e.knownSourceFiles){let c=Ue(a.content);if(!c)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because a loaded source file cannot be parsed"};r.push({file:a.file,ast:c})}let o=Cf(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Ka({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(c.hasUnsafeReference)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the component has unsupported value usages"};i.push(...c.callSites)}if(i.length!==1)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without a single project-wide component call site"};let[s]=i;return!tt(s.file,e.targetFile)||vi(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 vv}from"@vcp-dev/contracts";function Ri(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 Jr();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return Jr();let u=yv(a,l,o?.instanceCount);if(!u)return Jr();c=u}return{ok:!0,target:{kind:"value-binding",file:a.file,locator:c}}}return o?.instanceIndex!==void 0?n!=="selection"||!i?.ok?{ok:!1,code:"repeat-target-failed",reason:i&&!i.ok?i.reason:"No safe selected repeat property target is available"}:{ok:!0,target:{kind:"repeat-property",target:i}}:e.isRepeat&&n!=="template"||t.status==="direct"&&t.target?.kind!=="jsx-attribute"?Jr():{ok:!0,target:{kind:"jsx-attribute"}}}function Jr(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function yv(e,t,n){if(!e.locator||!Number.isInteger(t)||t<0)return null;let r=e.collectionPathMap?.length??e.collectionIndexMap?.length;if(r!==void 0&&(t>=r||n!==void 0&&n!==r))return null;let o=e.collectionPathMap?.[t];if(o)return{...e.locator,path:o};let i=e.locator.path??[],s=i.findLastIndex(c=>c.kind==="index");if(s<0)return null;let a=i.map((c,l)=>l===s&&c.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:c);return{...e.locator,path:a}}import*as Mt from"@babel/types";import{SiteEditSetPropsParamsSchema as xv}from"@vcp-dev/contracts";function $f(e){let t=e.changes??(e.change?[e.change]:[]);if(!xv.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return Xr("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return Xr("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=ke(e.source,"value");if(!o.ok)return Xr("invalid-target","Repeat property source could not be parsed");let i=[{type:"set-property-binding",order:0,file:e.target.templateFile,locator:e.target.targetElementLocator,name:r.name,object:e.target.callbackItemName,property:r.name}];for(let[s,a]of e.target.parentObjectLocators.entries()){let c=ie(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return Xr("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?bv(r):Sv(c.match.path.node,r.name);if(!l)return Xr("unsupported-property-value",`Repeat item ${s} has an unsupported value for '${r.name}'`);i.push({type:"upsert-object-property",order:i.length,file:e.target.sourceFile,locator:a,name:r.name,value:l})}return{ok:!0,steps:i}}function bv(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function Sv(e,t){let n=e.properties.filter(i=>Mt.isObjectProperty(i)&&Ev(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Mt.isExpression(r.value))return null;let o=At(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function Ev(e){return Mt.isIdentifier(e)?e.name:Mt.isStringLiteral(e)?e.value:Mt.isNumericLiteral(e)?String(e.value):null}function Xr(e,t){return{ok:!1,errorCode:e,reason:t}}function Vf(e){if(e.change.name!=="className"&&e.change.name!=="class")return zr("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return zr("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return zr("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return zr("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 zr("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 zr(e,t){return{ok:!1,errorCode:e,reason:t}}async function Kf(e){let t=vv.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return wn("invalid-change","Typed property changes are invalid");let n=[];for(let r of t.data.changes){let o=await Iv(e,r);if(o){if(!o.ok)return wn("owner-plan-failed",o.reason);Uf(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return wn("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return wn("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(Rv(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=Ri({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return wn(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){za(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=$f({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return wn("repeat-target-failed",l.reason);Uf(n,l.steps);continue}za(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:kv(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),Cv(n)?wn("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function Iv(e,t){return t.name!=="className"&&t.name!=="class"?null:Vf({node:e.node,change:t,classNameSource:e.classNameSource})}function kv(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 Cv(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 Uf(e,t){for(let n of t)za(e,{...n,order:e.length})}function za(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 Rv(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Ha(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Ha(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)=>Ha(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=>Ha(n[i],r[i]))}return!1}function wn(e,t){return{ok:!1,errorCode:e,reason:t}}import*as nr from"@babel/types";import*as X from"@babel/types";function Wa(e,t,n){let r=Ot(t,n);return r?Dt(e,r):null}function Dt(e,t){let n=t.findParent(h=>h.isArrowFunctionExpression()||h.isFunctionExpression());if(!n||!n.isArrowFunctionExpression()&&!n.isFunctionExpression())return null;let r=n,o=r.parentPath;if(!o||!o.isCallExpression()&&!o.isOptionalCallExpression())return null;let i=o;if(i.node.arguments.findIndex(h=>h===r.node)!==0)return null;let a=i.get("callee");if(!a.isMemberExpression()&&!a.isOptionalMemberExpression())return null;let c=a.node,l=c.property;if(!X.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),f=er(e,u.node),m=r.node.params.map(h=>er(e,h)),d=de(i.node),g=de(r.node);return!f||m.some(h=>h.length===0)||!d||!g?null:{callStart:d.start,callEnd:d.end,callbackStart:g.start,callbackEnd:g.end,collectionExpression:f,callbackParams:m,mapOperator:X.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:wi(u.node),callbackPath:r,collectionPath:u}}function Hr(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function wv(e,t){let n=de(e.node);return n?Nv(t).some(r=>{let o=de(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function Nv(e){let t=e.callbackPath.node.body;return X.isBlockStatement(t)?rn(t.body):on(t)}function rn(e){let t=[];for(let n of e){if(X.isReturnStatement(n)){n.argument&&t.push(...on(n.argument));continue}if(X.isBlockStatement(n)){t.push(...rn(n.body));continue}if(X.isIfStatement(n)){let r=X.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...rn(r)),n.alternate){let o=X.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...rn(o))}continue}if(X.isSwitchStatement(n)){for(let r of n.cases)t.push(...rn(r.consequent));continue}X.isTryStatement(n)&&(t.push(...rn(n.block.body)),n.handler&&t.push(...rn(n.handler.body.body)),n.finalizer&&t.push(...rn(n.finalizer.body)))}return t}function on(e){return X.isJSXElement(e)?Pv(e)?Jf(e.children):[e]:X.isJSXFragment(e)?Jf(e.children):X.isParenthesizedExpression(e)||X.isTSAsExpression(e)||X.isTSSatisfiesExpression(e)||X.isTSNonNullExpression(e)||X.isTSTypeAssertion(e)?on(e.expression):X.isConditionalExpression(e)?[...on(e.consequent),...on(e.alternate)]:X.isLogicalExpression(e)&&Xa(e.operator)?on(e.right):[]}function Jf(e){return e.flatMap(t=>X.isJSXElement(t)||X.isJSXFragment(t)?on(t):X.isJSXExpressionContainer(t)&&(X.isJSXElement(t.expression)||X.isJSXFragment(t.expression)||X.isConditionalExpression(t.expression)||X.isLogicalExpression(t.expression))?on(t.expression):[])}function Pv(e){let t=e.openingElement.name;return X.isJSXIdentifier(t)?t.name==="Fragment":X.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Xf(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function wi(e){return!(X.isIdentifier(e)||X.isThisExpression(e)||X.isMemberExpression(e)||X.isOptionalMemberExpression(e)||X.isCallExpression(e)||X.isOptionalCallExpression(e))}function zf(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(X.isMemberExpression(n)||X.isOptionalMemberExpression(n))&&X.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function tr(e,t){let n=Ue(e);if(!n)return t.isRepeatItemRoot===!0;let r=ie(n,Se(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Ii(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Dt(e,o);return i?wv(o,i):t.isRepeatItemRoot===!0}function Hf(e,t){let n=Ue(e);if(!n)return!1;let r=ie(n,Se(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Ii(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(X.isMemberExpression(s)||X.isOptionalMemberExpression(s))&&X.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as Ee from"@babel/types";function Ga(e){if(Ee.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(Ee.isJSXMemberExpression(e)){let t=e;for(;Ee.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function Av(e,t){let n=de(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||_t(a.path.node,n)||sn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Ga(i.node.name);s&&o(s,i)}}),[...r].sort()}function Ya(e,t,n){let r=Ue(e);if(!r)return{ok:!0};let o=ie(r,Se(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=ie(r,Se(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};if(ki(o.match.path,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let s=Av(o.match.path,i.match.path);return s.length>0?{ok:!1,bindingNames:s}:{ok:!0}}function Gf(e){let t=e;for(;Ee.isTSQualifiedName(t);)t=t.left;return Ee.isIdentifier(t)?t.name:null}function Wr(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Ni(e){let t=[],n=r=>{if(r){if(Ee.isIdentifier(r)){t.push(r.name);return}if(Ee.isObjectPattern(r)){for(let o of r.properties){if(Ee.isRestElement(o)){n(o.argument);continue}Ee.isObjectProperty(o)&&n(o.value)}return}if(Ee.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(Ee.isAssignmentPattern(r)){n(r.left);return}if(Ee.isRestElement(r)){n(r.argument);return}Ee.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Za(e,t){let n=de(e.node),r=de(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=Wf(e),i=Wf(t);if(!o||!i||!Lf(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=Bf(s.node,n);if(a&&!nt(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=de(s.node.right);if(a&&nt(a,n)&&!nt(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())&&zf(s)){let a=de(s.node.body)??de(s.node);if(a&&!nt(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 Wf(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?de(t.node.argument):null;if(t.isArrowFunctionExpression()&&(Ee.isJSXElement(t.node.body)||Ee.isJSXFragment(t.node.body)||Ee.isConditionalExpression(t.node.body)||Ee.isLogicalExpression(t.node.body)))return de(t.node.body);t=t.parentPath}return null}function sn(e,t,n){return n.scope.getBinding(t)===e}function Qa(e,t,n,r={}){if(!r.preserveConditionalBoundary&&ki(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=de(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>Ni(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);!u||_t(u.path.node,o)||i.has(u.path.node)||sn(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Ga(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function qa(e,t,n){let r=de(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Ni(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return Wr(e,s=>{let a=s.scope.getBinding(s.node.name);!a||_t(a.path.node,r)||o.has(a.path.node)||sn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function Yf(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Ni(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);!l||n.has(l.path.node)||sn(l,a,t)||r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(c){o(c.node.name,c)},TSTypeReference(c){let l=c.node.typeName;if(nr.isIdentifier(l))o(l.name,c);else{let u=Gf(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function ec(e,t){let n=de(e.node),r=new Set;return Wr(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&_t(i.path.node,n)||sn(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 Zf(e){let t=[];for(let n of e.callbackPath.node.params){if(nr.isIdentifier(n)){t.push(n.name);continue}if(nr.isRestElement(n)&&nr.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 Qf(e,t){return{...e,callbackParams:t}}function tc(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function rr(e){return{file:e.file,component:e.component}}function Tv(e){return e.target.kind==="node"?e.target.key:null}function Fv(e){return"kind"in e}function Pi(e){return!Fv(e)}function sc(e,t){let n=_i.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=_i.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function nc(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Nt(n,Se(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function cc(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 _v(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function Ov(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 rc(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function Mv(e){let t=kf(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Za(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=Dv({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=sp(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?wi(o):!0}}}function Dv(e){let t=de(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||_t(a.path.node,t))return;let c=jv(s,a,t);if(c){if(c.hasDefault){o="Cannot move prop-backed repeat child because the collection prop has a default value that cannot be preserved safely";return}let l=Vv(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=Lv(l.expression,c.remainingPath);if(!u){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let f=ec(l.expressionPath,e.targetParentPath);if(!f.ok){o=f.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${f.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:u});return}sn(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:Uv(e.source,t,[...n.values()])}}function Lv(e,t){if(t.length===0)return e;let n=sp(e);if(!n)return null;let r=wi(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=Bv(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function Bv(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function jv(e,t,n){let r=$v(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=Gn(t,o);if(!i)return null;let s=r?.range??de(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function $v(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!_t(n.node,t)||n.node.computed||!le.isIdentifier(n.node.property))return null;let r=de(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Vv(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(c=>c.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let o=r.find(c=>c.isJSXAttribute()&&le.isJSXIdentifier(c.node.name)&&c.node.name.name===t);if(!o?.isJSXAttribute())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not passed explicitly`};let i=o.get("value");if(!i.isJSXExpressionContainer())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not an expression`};let s=i.get("expression");if(!s.isExpression())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not a usable expression`};let a=er(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 Uv(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 sp(e){try{let n=ip.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=le.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&le.isExpression(r)?r:null}catch{return null}}function Kv(e){let t=de(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||_t(s.path.node,t))return;let a=qf(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=qf(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!Jv(u.importSpec,a.importSpec))&&r.add(a.localName);return}let l=n.get(a.moduleSpecifier)??[];l.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||l.push(a.importSpec),n.set(a.moduleSpecifier,l);return}r.add(i.node.name)};return Wr(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 Jv(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 qf(e,t,n){let r=Xv(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=kn(t,i),a=i.startsWith(".")?sc(n,s):i;if(r.isImportDefaultSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:c}}}if(r.isImportNamespaceSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:c}}}if(r.isImportSpecifier()){let c=le.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:c,local:l===c?void 0:l}}}return null}function Xv(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function ep(e,t,n,r){let o=Ja(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=er(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=zv(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${Wv(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function zv(e,t){return Hv(e.node)?t:`(${t})`}function Hv(e){return le.isIdentifier(e)||le.isThisExpression(e)||le.isSuper(e)||le.isMemberExpression(e)||le.isOptionalMemberExpression(e)||le.isCallExpression(e)||le.isOptionalCallExpression(e)||le.isBooleanLiteral(e)||le.isNumericLiteral(e)||le.isStringLiteral(e)||le.isNullLiteral(e)||le.isUnaryExpression(e)}function Wv(e){return e.trim().startsWith("<")?e:`(${e})`}var Gv={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 Ai(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=Gv[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 Yv(e,t){for(let n of e.program.body){if(!le.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>le.isImportDefaultSpecifier(o));if(r&&le.isImportDefaultSpecifier(r))return r.local.name}return null}function Zv(e,t,n){for(let r of e.program.body){if(!le.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>le.isImportSpecifier(i)&&(le.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&le.isImportSpecifier(o))return o.local.name}return null}function tp(e){let t=new Set;return vt(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function np(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function Qv(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=cc(e),o=Ue(t);if(n.exportName!=="default"){let a=o?Zv(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?np(r,tp(o)):r;return{localName:c,importStep:oc(e,c)}}if(!o)return{localName:r,importStep:oc(e,r)};let i=Yv(o,n.source);if(i)return{localName:i};let s=np(r,tp(o));return{localName:s,importStep:oc(e,s)}}function qv(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??cc(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 eI(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?tI(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function tI(e){return Object.fromEntries(Object.entries(e).filter(t=>ac(t[1])))}function ac(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(ac):typeof e=="object"?Object.values(e).every(ac):!1}function oc(e,t=cc(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 rp(e,t){if("kind"in e)return{parentNode:null,anchorNode:null,placement:e.relation};if("parentKey"in e)return{parentNode:t.getNode(e.parentKey),anchorNode:null,placement:e.relation};let n=t.getNode(e.anchorKey);return{parentNode:n?.parentKey?t.getNode(n.parentKey)??n:n,anchorNode:n,placement:e.relation}}function nI(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Gr(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function lc(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Yr(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:lc(e,t.slice(0,n)),index:r.index}}return null}function ic(e,t){return e.locator?e.collectionPathMap?.[t]?lc(e.locator,e.collectionPathMap[t]):Yr(e.locator)?oI(e.locator,iI(t,e.collectionIndexMap)):null:null}function rI(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:ap(o,t)}function ap(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=ap(r,t);return o===void 0?void 0:{[n.name]:o}}function Ti(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 oI(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},lc(e,i)}return null}function iI(e,t){return t?.[e]??e}function op(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 sI(e,t){return aI(e.root,t.root)&&lI(e.path??[],t.path??[])}function aI(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&&cI(e.sourceRange,t.sourceRange)}}function cI(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function lI(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 Fi=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:Gr(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:Gr(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:Gr(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:Gr(t.kind,t.params.kind)};let r=t;if(!Pi(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=rp(r.params.position,this.graph);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:Gr(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"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=Tv(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):uI(i)}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?Kf({node:t.node,scope:t.scope,changes:t.changes,selectionRef:t.selectionRef,getPropertyState:n,getRepeatPropertyTarget:this.graph.getRepeatPropertyTarget,getFileContent:r=>this.graph.getFileContent(r),getFileVersion:r=>this.graph.getFileVersion(r),classNameSource:this.graph.getClassNameSource?.(t.node.key)??void 0}):{ok:!1,errorCode:"missing-property-state",reason:"Typed property planning requires authoritative property provenance"}}async buildStyleDraftPropertySteps(t){let{initialOrder:n,node:r,props:o,selectionRef:i}=t,s=[],a=[];for(let[c,l]of Object.entries(o)){if(l===void 0)continue;let u=await this.graph.getElementPropertyWriteTarget?.(r.key,c),f=r.attributes?.find(d=>d.name===c);if((await this.graph.getPropertyState?.(r.key,c,i))?.status==="blocked"||!u&&f?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${c}'`};if(!(typeof f?.resolvedValue=="string"&&f.resolvedValue===l||f?.source===null&&f.value===l)){if(u?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${c}'`};if(u?.kind==="value-binding"&&u.locator){let d=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let g=ic(u,i.instanceIndex);if(!g)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};d=g}s.push({order:n+s.length,file:u.file,type:"update-value",locator:d,value:l});continue}a.push({operation:"set",name:c,value:l})}}return a.length>0&&s.push({order:n+s.length,file:r.file,type:"set-property-changes",locator:Se(r),scope:"selection",changes:a}),{ok:!0,steps:s}}buildTextRewriteSteps(t,n,r,o,i){if(o?.kind==="value-binding"&&o.locator){if(o.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let a=ic(o,i.instanceIndex);if(!a)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the selected repeat item"};let c=this.coerceTextValueForValueTarget(o.file,a,r);return c.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-array-item",locator:a,value:c.value}]}:c}let s=this.coerceTextValueForValueTarget(o.file,o.locator,r);return s.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-value",locator:o.locator,value:s.value}]}:s}return{ok:!0,steps:o?.kind==="external-entry"?[{order:0,file:`external:${o.sourceId}`,type:"invoke-external-adapter",sourceType:o.sourceType,sourceId:o.sourceId,adapterId:o.adapterId,capability:"write-text",value:r}]:[{order:0,file:t.file,type:"update-text",locator:Se(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Ue(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=ie(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!_v(a.match.path))return{ok:!0,value:r};let c=Ov(r);return c===null?{ok:!1,errorCode:"invalid-params",reason:`${o} value must be a valid number for numeric source`}:{ok:!0,value:c}}planUpdateArrayItem(t,n,r,o){if(!r.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update repeated text on this node"};if(o?.kind!=="value-binding"||o.sourceKind!=="repeat-template"||!o.locator)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item requires a writable repeat-template source"};let{index:i,value:s}=n.params,a=o.collectionPathMap?.length??o.collectionIndexMap?.length;if(a!==void 0&&i>=a)return{ok:!1,errorCode:"invalid-params",reason:`update-array-item index ${i} is outside the repeated source`};let c=ic(o,i);if(!c)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(o.file,c,s,"update-array-item");return l.ok?this.isValueTargetUnchanged(o.file,c,l.value)?{ok:!1,errorCode:"invalid-params",reason:"update-array-item value is unchanged"}:this.buildPlan(t,n,[{order:0,file:o.file,type:"update-array-item",locator:c,value:l.value}],r):l}isValueTargetUnchanged(t,n,r){let o=Ue(this.graph.getFileContent(t));if(!o)return!1;let i=ie(o,n);if(!i.ok)return!1;let s=i.match.path;if(s.isStringLiteral())return typeof r=="string"&&s.node.value===r;if(s.isNumericLiteral())return typeof r=="number"&&Object.is(s.node.value,r);if(s.isBooleanLiteral())return typeof r=="boolean"&&s.node.value===r;if(s.isNullLiteral())return r===null;if(s.isUnaryExpression({operator:"-"})){let a=s.get("argument");return typeof r=="number"&&!Array.isArray(a)&&a.isNumericLiteral()&&Object.is(-a.node.value,r)}return!1}planUpdateText(t,n,r,o,i){let s=this.graph.getTextProvenance?.(r.key,n.params.segmentIndex);if(s&&(s.editMode==="readonly"||s.editMode==="unsupported"))return{ok:!1,errorCode:"unsupported-operation",reason:"Text has no identity-preserving write target"};if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let a=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return a.ok?this.buildPlan(t,n,a.steps,o):a}async planRemoveNode(t,n,r,o){if(!o.canRemove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot remove this node"};let i=await this.graph.getTextWriteTarget(r.key,0);if(i?.kind==="external-entry")return this.buildPlan(t,n,[{order:0,file:`external:${i.sourceId}`,type:"invoke-external-adapter",sourceType:i.sourceType,sourceId:i.sourceId,adapterId:i.adapterId,capability:"remove-node",value:{operation:"remove-node"}}],o);if(r.isRepeatItemRoot){let f=i;if(f?.kind==="value-binding"&&f.locator){let m=Yr(f.locator);if(m)return this.buildPlan(t,n,[{order:0,file:f.file,type:"remove-bound-array-item",locator:m.locator,index:m.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=Ti(r,i,this.graph.getTextProvenance?.(r.key,0)??null);if(s)return{ok:!1,errorCode:"unsupported-operation",reason:s};let a=this.getRepeatBackedTemplateStructureReason(r);if(a)return{ok:!1,errorCode:"unsupported-operation",reason:a};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=[{order:0,file:r.file,type:"remove-node",locator:Se(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&l.push({...u,order:l.length}),this.buildPlan(t,n,l,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||Df(n,t)>1)return null;let r=sc(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(!Pi(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.node.kind==="component-call"&&!n.params.node.component)return{ok:!1,errorCode:"unsupported-operation",reason:"Materialized component insertion requires the materialization transaction planner"};if(!o.canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot insert child into this node"};let s=this.graph.getEditableTextSegmentIndex(r.key),a=s!==null?await this.graph.getTextWriteTarget(r.key,s):null,c=Ti(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let f=await this.planRepeatBackedInsertChild(t,n,r,o);if(f)return f;let m=this.getRepeatBackedTemplateStructureReason(r);if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let d=yf(this.graph.getFileContent(r.file),r);if(!d.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:d.reason??"Cannot insert child into this node"};let g=Ai(r,n.params.node);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let h=[],E=0,S=n.params.node.kind==="component-call"?Qv(n.params.node,this.graph.getFileContent(r.file)):void 0,v=S?.importStep;return v&&h.push({order:E++,file:r.file,type:"add-import",moduleSpecifier:v.moduleSpecifier,imports:v.imports}),h.push({order:E++,file:r.file,type:"insert-child",parentLocator:Se(r),node:{jsx:qv(n.params.node,S?.localName)},placement:n.params.position.relation,anchorLocator:i?Se(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Pi(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let a=s?.kind==="external-entry"?s:await this.findExternalInsertContext(r,i);if(!a)return null;let c=i?await this.graph.getTextWriteTarget(i.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${a.sourceId}`,type:"invoke-external-adapter",sourceType:a.sourceType,sourceId:a.sourceId,adapterId:a.adapterId,capability:"insert-child",value:{operation:"insert-child",relation:n.params.position.relation,parentKey:r.key,anchorSourceId:c?.kind==="external-entry"?c.sourceId:null,node:eI(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(!Pi(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(f=>f.isRepeatItemRoot&&f.tag?.toLowerCase()===i.tag.toLowerCase());if(!s)return null;let a=await this.graph.getTextWriteTarget(s.key,0);if(!a||a.kind!=="value-binding"||!a.locator)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires a writable value target"};let c=Yr(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=rI(a.locator,i.text);if(l===void 0)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child could not infer an item shape from the template"};let u=n.params.position.relation==="prepend"?op(0,a.collectionIndexMap):op(a.collectionIndexMap?.length??c.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:c.locator,index:u,value:l}],o)}async getUpstreamBackedDescendantReason(t){if(!this.graph.getChildNodes)return null;let n=[...this.graph.getChildNodes(t.key)];for(;n.length>0;){let r=n.shift();if(!r)continue;let o=this.graph.getEditableTextSegmentIndex(r.key),i=o!==null?await this.graph.getTextWriteTarget(r.key,o):null,s=Ti(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 tr(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:")||Hf(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&&tr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Ue(c);if(!l)return null;let u=Ot(l,r),f=Ot(l,o);if(!u||!f)return null;let m=Dt(c,u),d=Dt(c,f);if(!Hr(m,d))return null;if(a&&(s==="before"||s==="after")){let h=Ot(l,a),E=h?Dt(c,h):null;if(!Hr(m,E))return null}if(Ci(u,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=Ya(c,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Se(r),targetParentLocator:Se(o),placement:s,anchorLocator:a?Se(a):void 0,selectionContext:rr(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&&tr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Ue(c);if(!l)return null;let u=Ot(l,r),f=Ot(l,o);if(!u||!f)return null;let m=Dt(c,u);if(!m)return null;let d=Dt(c,f);if(Hr(m,d))return null;if(d&&!Xf(d,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let C=Wa(c,l,a);if(d&&!Hr(d,C)||!d&&C)return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"}}if(r.tag&&r.tag.toLowerCase()===r.tag){let C=Ai(o,{kind:"native-tag",tag:r.tag});if(C)return{ok:!1,errorCode:"unsupported-operation",reason:C}}let g=nc(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(Ci(u,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=ep(c,u,f,g);for(let C of h.conditionPaths){let N=qa(C,f,m);if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${N.bindingNames.join(", ")}`}}let E=Qa(u,f,m,{preserveConditionalBoundary:h.conditionPaths.length>0});if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${E.bindingNames.join(", ")}`};let S=Yf(m,f);if(!S.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${S.bindingNames.join(", ")}`};let v=m;if(r.component!==o.component){let C=Mv({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:f});if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:C.reason};v=C.context}else{let C=ec(m.collectionPath,f);if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:C.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${C.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:Se(r),targetParentLocator:Se(o),placement:s,anchorLocator:a?Se(a):void 0,repeatExpression:tc(v,h.sourceJsx),selectionContext:rr(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&tr(this.graph.getFileContent(r.file),r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),u=Ue(c),f=Ue(l);if(!u||!f)return null;let m=jf({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!m.ok)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason};let d=Ot(u,r),g=Ot(f,o);if(!d||!g)return null;let h=Za(m.callSitePath,g);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let E=Dt(c,d);if(!E)return null;if(Dt(l,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Wa(l,f,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 O=Ai(o,{kind:"native-tag",tag:r.tag});if(O)return{ok:!1,errorCode:"unsupported-operation",reason:O}}let v=nc(this.graph,r);if(!v)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Ci(d,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let C=ep(c,d,g,v);for(let O of C.conditionPaths){let L=qa(O,g,E);if(!L.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${L.bindingNames.join(", ")}`}}let N=Qa(d,g,E,{preserveConditionalBoundary:C.conditionPaths.length>0});if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:N.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${N.bindingNames.join(", ")}`};let A=Kv({sourceFile:r.file,targetFile:o.file,sourceContext:E,targetParentPath:g});if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason};let P=Zf(E);if(!P.ok)return{ok:!1,errorCode:"unsupported-operation",reason:P.reason};let k=Qf(E,P.callbackParams),T=[{order:0,file:r.file,type:"remove-node",locator:Se(r),removeWhitespace:!0}];for(let O of A.imports)T.push({order:T.length,file:o.file,type:"add-import",moduleSpecifier:O.moduleSpecifier,imports:O.imports});return T.push({order:T.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:Se(o),expression:tc(k,C.sourceJsx),placement:s,anchorLocator:a?Se(a):void 0,selectionContext:rr(o)}),this.buildPlan(t,n,T,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};let i=rp(n.params.target,this.graph),s=i.parentNode;if(!s)return{ok:!1,errorCode:"locator-miss",reason:`Target parent for request '${n.id}' not found in graph`};if(nI(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 a=await this.graph.getTextWriteTarget(r.key,0);if(a?.kind==="external-entry"){let S=n.params.target.relation,v=i.anchorNode&&(S==="before"||S==="after")?await this.graph.getTextWriteTarget(i.anchorNode.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:"move-node",value:{operation:"move-node",relation:S,anchorSourceId:v?.kind==="external-entry"?v.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let c=r.file!==s.file,l=n.params.target.relation,u=i.anchorNode,f=Ti(r,a,this.graph.getTextProvenance?.(r.key,0)??null);if(f&&!rc(f))return{ok:!1,errorCode:"unsupported-operation",reason:f};if(r.isRepeatItemRoot&&u?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===u.repeatOwnerKey&&(l==="before"||l==="after")){let S=a,v=await this.graph.getTextWriteTarget(u.key,0);if(S?.kind==="value-binding"&&v?.kind==="value-binding"&&S.locator&&v.locator){let C=Yr(S.locator),N=Yr(v.locator);if(C&&N&&S.file===v.file&&sI(C.locator,N.locator)){let A=C.index,P=N.index,k=l==="before"?P-(A<P?1:0):P+(A<P?0:1);return this.buildPlan(t,n,[{order:0,file:S.file,type:"move-array-item",locator:C.locator,fromIndex:A,toIndex:k}],o)}}}if(r.isRepeatItemRoot&&tr(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),d=rc(f)?f:m;if(d&&rc(d)){let S=this.planRepeatTemplateInternalMove(t,n,r,s,o,l,u);if(S)return S;let v=this.planRepeatTemplateHoistMove(t,n,r,s,o,l,u);if(v)return v;let C=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,l,u);return C||{ok:!1,errorCode:"unsupported-operation",reason:d}}if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let g=await this.getUpstreamBackedDescendantReason(r);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};if(r.tag&&r.tag.toLowerCase()===r.tag){let S=Ai(s,{kind:"native-tag",tag:r.tag});if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S}}if(c)return this.planCrossFileMove(t,n,r,s,o,l,u);let h=Ya(this.graph.getFileContent(r.file),r,s);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason??`Cannot move node because it depends on bindings outside the target scope: ${h.bindingNames.join(", ")}`};let E=[{order:0,file:r.file,type:"move-node",locator:Se(r),targetParentLocator:Se(s),placement:l,anchorLocator:u?Se(u):void 0,selectionContext:rr(s)}];return this.buildPlan(t,n,E,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),f=nc(this.graph,r)??`<${r.component} />`,m=xf(u,r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:Se(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,E={moduleSpecifier:sc(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:g}]:[{kind:"named",imported:r.exportName,local:g===r.exportName?void 0:g}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:E.moduleSpecifier,imports:E.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Se(o),node:{jsx:f},placement:s,anchorLocator:a?Se(a):void 0,selectionContext:rr(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Se(o),node:{jsx:f},placement:s,anchorLocator:a?Se(a):void 0,selectionContext:rr(o)});let d=this.buildRemoveComponentImportStep(r,u);return d&&c.push({...d,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:be(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 uI(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 mc from"@babel/generator";import{parse as CI}from"@babel/parser";import gc from"@babel/traverse";import*as R from"@babel/types";import*as Bt from"@babel/types";import uc from"@babel/generator";import*as he from"@babel/types";var dI=typeof uc=="function"?uc:uc.default,fI=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,pI=/^((?:https?:)?\/\/)[^/@\s]+@/i,mI=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function lp(e,t){let n=Lt(e.callee);if(!n)return null;if(n==="fetch")return dc(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(cp(r))return dc(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(cp(r))return dc(e.arguments[0],r,t,["ky client contract"])}return null}function dc(e,t,n,r){if(!e||he.isSpreadElement(e)||he.isJSXNamespacedName(e))return xI(t,n,r,"missing url argument");let o=Zr(e);return{sourceKind:yI(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 Zr(e){if(he.isStringLiteral(e))return Oi(e.value);if(he.isTemplateLiteral(e))return Oi(gI(e));if(he.isBinaryExpression(e)&&e.operator==="+"){let t=Zr(e.left),n=Zr(e.right);return!t&&!n?void 0:Oi(`${t??fc(e.left)}${n??fc(e.right)}`)}if(he.isMemberExpression(e)){let t=up(e);if(t)return`env:${t}`}if(!(he.isCallExpression(e)&&Lt(e.callee)==="new URL")){if(he.isNewExpression(e)&&he.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!he.isSpreadElement(t)?Zr(t):void 0,o=n&&!he.isSpreadElement(n)?Zr(n):void 0;return o&&r?Oi(`${o} + ${r}`):r??o}if(he.isIdentifier(e))return`:${e.name}`}}function gI(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+=fc(r))}return t}function fc(e){if(he.isIdentifier(e))return`:${e.name}`;if(he.isMemberExpression(e)){let t=up(e);if(t)return`env:${t}`}return`:${hI(e)}`}function hI(e){return dI(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Oi(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(pI,"$1<redacted>@").replace(mI,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?fI.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function yI(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 xI(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function cp(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function up(e){return!he.isMemberExpression(e.object)||!he.isIdentifier(e.object.object,{name:"process"})||!bI(e.object.property,"env")?null:he.isIdentifier(e.property)?e.property.name:he.isStringLiteral(e.property)?e.property.value:null}function bI(e,t){return he.isIdentifier(e)&&e.name===t}function Lt(e){if(he.isIdentifier(e))return e.name;if(he.isMemberExpression(e)){let t=Lt(e.object),n=he.isIdentifier(e.property)?e.property.name:he.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var SI=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),EI=new Set(["getConfig","submit"]);function dp(e,t){let n=vI(Lt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!SI.has(i))return null;let s=pc(e,0),a=i==="getByUrl"||i==="getByUrlStrict",c=a?void 0:s,l=a?s??"/:record-url":c?`/collections/${c}`:"/collections/:collection";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:i,...c?{collection:c}:{},endpointPattern:l,confidence:s?"exact":"partial",evidence:[{file:t.file,symbol:n,reason:"VCP CMS collection facade"}]}}let o="cms.forms.";if(n.startsWith(o)){let i=n.slice(o.length);if(!EI.has(i))return null;let s=pc(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=pc(e,0)??II(e,0,"path")??"/cms/:path",s=kI(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 vI(e,t){let n=e?.indexOf(".")??-1;if(!e||n<1)return e;let r=t.imports?.get(e.slice(0,n));return r?.importedName==="collections"&&/(?:^|\/)lib\/cms\/collections(?:\.js)?$/.test(r.source)?`cms.collections${e.slice(n)}`:e}function fp(e,t){let n=Lt(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 pp(e){let t=Lt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function pc(e,t){let n=e.arguments[t];return Bt.isStringLiteral(n)?n.value:null}function II(e,t,n){let r=e.arguments[t];if(!Bt.isObjectExpression(r))return null;for(let o of r.properties)if(Bt.isObjectProperty(o)&&!o.computed&&(Bt.isIdentifier(o.key)&&o.key.name===n||Bt.isStringLiteral(o.key)&&o.key.value===n)&&Bt.isStringLiteral(o.value))return o.value.value;return null}function kI(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}var yc=typeof gc=="function"?gc:gc.default,C_=typeof mc=="function"?mc:mc.default,RI={maxFunctionDepth:8,maxImportDepth:6},wI=new Set(["src","href","alt","poster","content","title","aria-label"]);async function bp(e){let t=e.fileCache??new Map,n=Sc(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...RI,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:_p(n,e.element.componentName)};await Sp(e.element.componentName,e.graph,r);let o=[];o.push(...await FI(e.element,e.graph,r),...await _I(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await OI(s,e.element,e.graph,r);a&&o.push(Li(a,"text","children"))}for(let s of e.element.attributes??[]){let a=TI(s,e.element);if(!a)continue;let c=await Ip(s.source,e.element,e.graph,r);c&&o.push(Li(c,a,s.name))}let i=GI(o).sort(Tp);return{hasDynamicData:i.length>0,bindings:i}}async function Sp(e,t,n){if(n.importDepth>=n.options.maxImportDepth)return;let r=n.analysis.functions.get(e)??n.analysis.functions.get("default"),o=r?.params[0];if(!r||!o)return;let i=n.analysis.functions.get("default")===r?"default":e,s=[];for(let l of t.elements.values()){if(l.sourceFile===n.file&&l.tag===e){s.push(l);continue}!l.importedFrom||!l.exportName||l.importedFrom===n.file&&l.exportName!==i||(l.importedFrom===n.file||await Ep(l.importedFrom,l.exportName,n.file,n))&&s.push(l)}if(s.length===0)return;let a=new Map;for(let l of s){let u=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let f=await vp(l.sourceFile,n);if(!f)continue;let m=ji(f,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=_p(f,l.componentName),await Sp(l.componentName,t,m);let d=await NI(l,m);for(let[g,h]of d){if(!h)continue;let E=a.get(g)??[];E.push(h),a.set(g,E)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let f=Pp(u);f.length===1&&c.set(l,f[0])}AI(o,c,n)}async function Ep(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 vp(e,r))?.imports.get(t);if(!s||!Tt(s.source))return!1;let a=await Dp(e,s.source,r.exists);return a?a===n?!0:Ep(a,s.importedName,n,r,o):!1}async function NI(e,t){let n=new Map;yc(t.analysis.ast,{JSXElement(o){if(PI(o.node,e.sourceRange)){for(let i of o.node.openingElement.attributes)!R.isJSXAttribute(i)||!R.isJSXIdentifier(i.name)||!R.isJSXExpressionContainer(i.value)||!R.isExpression(i.value.expression)||n.set(i.name.name,i.value.expression);o.stop()}}});let r=new Map;for(let[o,i]of n){let s=await De(i,t);s&&r.set(o,s)}return r}function PI(e,t){return e.loc?.start.line===t.startLine&&e.loc.start.column===t.startColumn&&e.loc.end.line===t.endLine&&e.loc.end.column===t.endColumn}async function vp(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 Sc(e,r,t.fileCache)}function AI(e,t,n){if(R.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,bc(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,Ke(o))}}function TI(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":wI.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function FI(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 Bi(i.collectionSource,n);s&&r.push(Li(Nn(s),"repeat-region",i.collectionExpression))}return r}async function _I(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 Bi(i.conditionSource,n);s&&r.push(Li(Nn(s),"conditional-region",i.conditionExpression))}return r}async function OI(e,t,n,r){return Ip(e.source,t,n,r)}async function Ip(e,t,n,r){let o=await MI(e,t,n,r);return o||Bi(e,r)}async function MI(e,t,n,r){if(!e)return null;let o=DI(e.base,t,n);if(!o)return null;let i=await Bi(o.collectionSource,r);return i?to(i,e.path,!0):null}function DI(e,t,n){let r=t.identity.key;for(;r;){for(let o of n.regions){if(o.kind!=="repeat-region"||!o.childKeys.includes(r))continue;let i=o.sourceCandidates?.find(s=>s.kind==="repeat-template"&&s.itemParamName===e);if(i)return i}r=n.elements.get(r)?.parentKey??null}return null}async function Bi(e,t){if(!e)return null;let n=await kp(e.base,t);return n?to(n,e.path,!1):null}async function kp(e,t){let n=t.paramSources.get(e);if(n)return Ke(n);if(t.variableCache.has(e))return YI(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await LI(e,t);if(r)return t.variableCache.set(e,Ke(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=await De(o,t);return t.variableCache.set(e,s?Ke(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await Op(i,t);if(s){let a=ji(s,t,{importDepth:t.importDepth+1}),c=Mp(i,s);if(c){let f=(await Pn(c,[],a)).returnSource;return t.variableCache.set(e,f?Ke(f):null),t.resolvingVariables.delete(e),f}let l=s.variables.get(i.importedName);if(l){let u=await De(l,a);return t.variableCache.set(e,u?Ke(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function LI(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];yc(t.analysis.ast,{CallExpression(o){if(R.isIdentifier(o.node.callee,{name:n})){let i=o.node.arguments[0];R.isExpression(i)&&r.push(i);return}o.node.arguments.some(i=>R.isIdentifier(i)&&i.name===n)&&r.push(o.node)}});for(let o of r){let i=await De(o,t);if(i)return i}return null}async function De(e,t){if(R.isIdentifier(e))return kp(e.name,t);if(R.isMemberExpression(e)||R.isOptionalMemberExpression(e)){let n=R.isMemberExpression(e)?fp(e,{file:t.file}):null;if(n)return Np(n);let r=await BI(e,t);if(!r)return null;let o=HI(e);return to(r,o,!1)}if(R.isAwaitExpression(e))return R.isExpression(e.argument)?De(e.argument,t):null;if(R.isCallExpression(e))return Cp(e,t);if(R.isObjectExpression(e)){let n=await Rp(e,t);return Object.keys(n).length>0?bc(n,t.file):null}if(R.isConditionalExpression(e)){let n=await De(e.consequent,t),r=await De(e.alternate,t);return eo(gp(n,r))}if(R.isLogicalExpression(e)){let n=await De(e.left,t),r=await De(e.right,t);return eo(gp(n,r))}return R.isTSAsExpression(e)||R.isTSSatisfiesExpression(e)||R.isTSNonNullExpression(e)||R.isTypeCastExpression(e)||R.isParenthesizedExpression(e)?De(e.expression,t):null}async function BI(e,t){let n=e;for(;R.isMemberExpression(n)||R.isOptionalMemberExpression(n);)n=n.object;return R.isExpression(n)?De(n,t):null}async function Cp(e,t){let n=dp(e,{file:t.file,imports:t.analysis.imports});if(n)return Np(n);if(pp(e)){let f=e.arguments[0];if(f&&R.isExpression(f))return eo(await De(f,t))}let r=await jI(e,t);if(r)return r;let o=lp(e,{file:t.file});if(o)return{sourceKind:o.sourceKind,sourceType:"api-field",endpointPattern:o.endpointPattern,valuePath:o.valuePath,confidence:o.confidence,readonly:!0,evidence:o.evidence};let i=await UI(e,t);if(i)return i;let s=await KI(e,t);if(s)return s;let a=await JI(e,t);if(a)return a;let c=await XI(e,t);if(c)return c;let l=[];for(let f of e.arguments)if(R.isExpression(f)){let m=await De(f,t);m&&l.push(m)}let u=Pp(l);return u.length===1?eo(u[0]):null}async function jI(e,t){let n=Lt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=VI(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(R.isIdentifier(s)){let a=await qr(s.name,t);if(a)return(await Pn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!R.isObjectExpression(r))return Mi(t.file,`${n} without static options`);let o=$I(r,"queryFn");if(!o)return Mi(t.file,`${n} without queryFn`);if(R.isIdentifier(o)){let i=await qr(o.name,t);return i?(await Pn(i.node,[],i.context)).returnSource:Mi(t.file,`${n} queryFn unresolved`)}return R.isArrowFunctionExpression(o)||R.isFunctionExpression(o)?(await Pn(o,[],t)).returnSource:R.isCallExpression(o)?Cp(o,t):null}function $I(e,t){for(let n of e.properties){if(!R.isObjectProperty(n)||!R.isExpression(n.value))continue;if(wp(n)===t)return n.value}return null}function VI(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 UI(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"].includes(n))return null;let r=R.isExpression(e.callee.object)?await De(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Nn(r);let o=e.arguments[0];if(R.isIdentifier(o)){let i=await qr(o.name,t);if(!i)return Nn(r);let s=await Pn(i.node,[r],i.context);return{...Nn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(R.isArrowFunctionExpression(o)||R.isFunctionExpression(o)){let i=await Pn(o,[r],t);return{...Nn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Nn(r)}async function KI(e,t){return!R.isMemberExpression(e.callee)||!R.isIdentifier(e.callee.property,{name:"json"})||!R.isExpression(e.callee.object)?null:De(e.callee.object,t)}async function JI(e,t){return!R.isMemberExpression(e.callee)||!R.isIdentifier(e.callee.property,{name:"then"})||!R.isExpression(e.callee.object)?null:eo(await De(e.callee.object,t))}async function XI(e,t){if(!R.isIdentifier(e.callee))return null;let n=await qr(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!R.isExpression(i)){r.push(Mi(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await De(i,t);r.push(s)}return(await Pn(n.node,r,n.context)).returnSource}async function qr(e,t){let n=t.analysis.functions.get(e);if(n)return{node:n,context:t};let r=t.analysis.imports.get(e);if(!r||t.importDepth>=t.options.maxImportDepth)return null;let o=await Op(r,t);if(!o)return null;let i=ji(o,t,{importDepth:t.importDepth+1}),s=Mp(r,o);return s?{node:s,context:i}:qr(r.importedName,i)}async function Pn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=ji(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let u=t[l];u&&hc(c,WI(u),r)});let o=zI(e),i=null,s,a=!1;for(let c of o){if(R.isObjectExpression(c)){s={...s??{},...await Rp(c,r)},i=i??bc(s,n.file);continue}let l=await De(c,r);if(l){if(!i){i=l;continue}let u=xc(i,l);if(!u){a=!0,i=null;continue}i=u}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function hc(e,t,n){if(R.isIdentifier(e)){n.paramSources.set(e.name,Ke(t));return}if(R.isAssignmentPattern(e)){hc(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=to(t,[{kind:"property",name:r.key.name}],!0),i=R.isAssignmentPattern(r.value)?r.value.left:r.value;hc(i,o,n)}}function zI(e){if(R.isArrowFunctionExpression(e)&&R.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!R.isBlockStatement(n))return t;let r=o=>{if(R.isFunction(o)&&o!==e)return;if(R.isReturnStatement(o)){o.argument&&R.isExpression(o.argument)&&t.push(o.argument);return}let i=R.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)R.isNode(c)&&r(c);else R.isNode(a)&&r(a)}};return r(n),t}async function Rp(e,t){let n={};for(let r of e.properties){if(!R.isObjectProperty(r))continue;let o=wp(r);if(!o||!R.isExpression(r.value))continue;let i=await De(r.value,t);i&&(n[o]=i)}return n}function wp(e){return R.isIdentifier(e.key)&&!e.computed?e.key.name:R.isStringLiteral(e.key)?e.key.value:null}function HI(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 to(e,t,n){if(t.length===0)return Ke(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return to(e.fieldMap[r.name],t.slice(1),n);let o=Ke(e);if(o.sourceType==="cms-field"){let i=t.filter(s=>s.kind==="property").map(s=>s.name);return i[0]==="data"&&i[1]==="items"?(o.valuePath=Qr(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=Qr(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=Qr(o.fieldPath,i.join(".")),o):(o.valuePath=Qr(o.valuePath,mp(t)),o)}return o.valuePath=Qr(o.valuePath,mp(t)),o}function mp(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Qr(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function Np(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 Nn(e){let t=Ke(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function WI(e){let t=Ke(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function eo(e){return e?{...Ke(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function gp(e,t){return e?t?xc(e,t):Ke(e):t?Ke(t):null}function xc(e,t){if(Di(e)!==Di(t))return null;let n=Fp(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=Di(n),o=t.get(r);t.set(r,o?xc(o,n):Ke(n))}return[...t.values()]}function Di(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Di(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 bc(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 Mi(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Li(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 Ap(e){let t=[...e].sort(Tp),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 GI(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 Tp(e,t){return hp(e.targetKind)-hp(t.targetKind)||Fp(e.confidence,t.confidence)||yp(e.sourceKind)-yp(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function hp(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function yp(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function Fp(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Sc(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=CI(t,{sourceType:"module",plugins:["jsx","typescript"]}),i={file:e,source:t,ast:o,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,functionVariables:new WeakMap};return yc(o,{ImportDeclaration(s){let a=s.node.source.value;for(let c of s.node.specifiers)R.isImportSpecifier(c)&&R.isIdentifier(c.local)?i.imports.set(c.local.name,{source:a,importedName:R.isIdentifier(c.imported)?c.imported.name:c.imported.value,localName:c.local.name,isDefault:!1}):R.isImportDefaultSpecifier(c)&&i.imports.set(c.local.name,{source:a,importedName:"default",localName:c.local.name,isDefault:!0})},FunctionDeclaration(s){s.node.id?.name&&i.functions.set(s.node.id.name,s.node)},VariableDeclarator(s){let a=s.getFunctionParent(),c=a&&(R.isFunctionDeclaration(a.node)||R.isFunctionExpression(a.node)||R.isArrowFunctionExpression(a.node))?a.node:null,l=c?i.functionVariables.get(c)??new Map:i.variables;c&&!i.functionVariables.has(c)&&i.functionVariables.set(c,l);for(let u of or(s.node.id))l.set(u,R.isExpression(s.node.init)?s.node.init:null);if(R.isArrayPattern(s.node.id)&&R.isCallExpression(s.node.init)&&Lt(s.node.init.callee)==="useState"){let[u,f]=s.node.id.elements;R.isIdentifier(u)&&R.isIdentifier(f)&&i.stateSetters.set(u.name,f.name)}R.isIdentifier(s.node.id)&&xp(s.node.init)&&i.functions.set(s.node.id.name,s.node.init)},ExportNamedDeclaration(s){let a=s.node.declaration,c=s.node.source?.value;if(c)for(let l of s.node.specifiers){if(!R.isExportSpecifier(l))continue;let u=R.isIdentifier(l.exported)?l.exported.name:l.exported.value,f=l.local.name;i.imports.set(u,{source:c,importedName:f,localName:u,isDefault:f==="default"})}if(R.isFunctionDeclaration(a)&&a.id?.name&&i.functions.set(a.id.name,a),R.isVariableDeclaration(a))for(let l of a.declarations)R.isIdentifier(l.id)&&xp(l.init)&&i.functions.set(l.id.name,l.init)},ExportDefaultDeclaration(s){let a=s.node.declaration;if((R.isFunctionDeclaration(a)||R.isFunctionExpression(a)||R.isArrowFunctionExpression(a))&&i.functions.set("default",a),R.isIdentifier(a)){let c=i.functions.get(a.name);c&&i.functions.set("default",c)}}}),n.set(e,i),i}function or(e){return!e||R.isVoidPattern(e)?[]:R.isIdentifier(e)?[e.name]:R.isObjectPattern(e)?e.properties.flatMap(t=>R.isObjectProperty(t)?or(t.value):or(t.argument)):R.isArrayPattern(e)?e.elements.flatMap(t=>t?or(R.isRestElement(t)?t.argument:t):[]):R.isAssignmentPattern(e)?or(e.left):R.isRestElement(e)?or(e.argument):[]}function xp(e){return R.isFunctionExpression(e)||R.isArrowFunctionExpression(e)}function _p(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function Op(e,t){let n=await Dp(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Sc(n,r,t.fileCache)}function Mp(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Dp(e,t,n){return Tt(t)?hn(e,t,n):null}function ji(e,t,n={}){return{file:e.file,analysis:e,readFile:t.readFile,exists:t.exists,fileCache:t.fileCache,options:t.options,variableCache:new Map,functionDepth:n.functionDepth??t.functionDepth,importDepth:n.importDepth??t.importDepth,paramSources:new Map(t.paramSources),resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0}}function YI(e){return e?Ke(e):null}function Ke(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,Ke(n)]))}:{}}}import*as vc from"@babel/parser";import Ec from"@babel/traverse";import*as z from"@babel/types";import{classifySiteEditPropertyName as ZI}from"@vcp-dev/contracts";var Ic=typeof Ec=="function"?Ec:Ec.default;function kc(e){let t=ZI(e.propertyName);if(t.owner!=="generic")return rt("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return rt("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return rt("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return rt("missing-instance-index","A repeat property target requires an instance index");let r;try{r=vc.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(E){return rt("repeat-not-found",`Unable to parse repeat source: ${E instanceof Error?E.message:String(E)}`)}let o=QI(r,e.element.sourceRange);if(!o)return rt("repeat-not-found","The selected element is not inside a supported map repeat");if(!z.isIdentifier(o.callback.params[0]))return rt("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=qI(r,o.collection,e.file,e.sources);if(!i)return rt("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],u=[];for(let[E,S]of s.elements.entries()){if(!S||!z.isObjectExpression(S)||!Up(S))return rt("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let v=[{kind:"index",index:E}];l.push(v),u.push({kind:"value",root:a.root,path:v})}let f=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==f)return rt("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${f}`);let m=n.instanceIndex;if(m>=f)return rt("index-out-of-range",`Selected repeat instance ${m} is outside the source collection`);let d=s.elements[m];if(!d||!z.isObjectExpression(d))return rt("unsafe-collection","Selected repeat item is not an object");let g=ik(e.element,e.propertyName),h=rk(d,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[m],sourceItemIndex:m,sourceItemPath:l[m],collectionIndexMap:Array.from({length:f},(E,S)=>S),callbackItemName:o.callback.params[0].name,targetElementLocator:{kind:"jsx-node",strategy:"structural-path",file:e.element.identity.file,component:e.element.identity.component,structuralPath:e.element.identity.structuralPath,expectedRange:e.element.sourceRange},propertyName:e.propertyName,propertyState:h,selectedResolution:ok(d,e.propertyName),...g?{property:g}:{},selectionRef:n}:rt("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function QI(e,t){let n=[];return Ic(e,{CallExpression(r){let o=Lp(r.node);o&&jp(o.callback,t)&&n.push({...o,span:Bp(r.node)})},OptionalCallExpression(r){let o=Lp(r.node);o&&jp(o.callback,t)&&n.push({...o,span:Bp(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function Lp(e){let t=e.callee;if(!z.isMemberExpression(t)&&!z.isOptionalMemberExpression(t)||t.computed||!z.isIdentifier(t.property)||t.property.name!=="map"||!z.isExpression(t.object))return null;let n=e.arguments[0];return!n||!z.isExpression(n)||!z.isArrowFunctionExpression(n)&&!z.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function qI(e,t,n,r){let o=no(t);if(o&&z.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:Jp(o)}},sourceFile:n};if(!z.isIdentifier(t))return null;let i=[];if(Ic(e,{VariableDeclarator(s){z.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=no(i[0].init);return!s||!z.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return ek(e,t.name,n,r)}function ek(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!z.isImportDeclaration(o))continue;let i=o.specifiers.find(m=>m.local.name===t);if(!i||!z.isStringLiteral(o.source)||!z.isImportSpecifier(i))continue;let s=nk(n,o.source.value,r);if(!s)return null;let a=z.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=vc.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=tk(l,a),f=u?no(u):null;return!f||!z.isArrayExpression(f)?null:{array:f,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function tk(e,t){let n=null;return Ic(e,{VariableDeclarator(r){n||!z.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!z.isExpression(r.node.init)||(n=r.node.init)}}),n}function nk(e,t,n){let r=Ir(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 no(e){return z.isParenthesizedExpression(e)?no(e.expression):z.isTSAsExpression(e)?Vp(e.typeAnnotation)?no(e.expression):null:z.isTSSatisfiesExpression(e)?null:e}function Vp(e){return z.isTSTypeReference(e)&&z.isIdentifier(e.typeName)&&e.typeName.name==="const"}function Up(e){return e.properties.every(t=>!z.isObjectProperty(t)||t.computed||!z.isExpression(t.value)?!1:$i(t.value))}function $i(e){if(z.isTSAsExpression(e)&&Vp(e.typeAnnotation))return $i(e.expression);if(z.isTSSatisfiesExpression(e))return!1;if(z.isArrayExpression(e))return e.elements.every(n=>!n||z.isSpreadElement(n)||!z.isExpression(n)?!1:$i(n));if(z.isObjectExpression(e))return Up(e);let t=At(e);return t.status==="resolved"||t.status==="undefined"}function rk(e,t){let n=e.properties.filter(o=>z.isObjectProperty(o)&&Kp(o.key)===t);if(n.length>1)return null;let r=n[0];return r?z.isExpression(r.value)?$i(r.value)?"static":z.isIdentifier(r.value)||z.isMemberExpression(r.value)?"binding":null:null:"missing"}function ok(e,t){let n=e.properties.filter(o=>z.isObjectProperty(o)&&Kp(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!z.isExpression(r.value)?{status:"undefined"}:At(r.value)}function ik(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function Kp(e){return z.isIdentifier(e)?e.name:z.isStringLiteral(e)?e.value:z.isNumericLiteral(e)?String(e.value):null}function Jp(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 Bp(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function jp(e,t){let n=Jp(e);return $p(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&$p(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function $p(e,t,n,r){return e===n?t-r:e-n}function rt(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as Xk}from"@vcp-dev/contracts";import*as H from"@babel/types";import so from"node:path";import*as pe from"@babel/types";import*as Gp from"@babel/parser";import Cc from"@babel/traverse";import*as q from"@babel/types";function Vi(e,t){let n=[],r=e;for(;q.isMemberExpression(r);){if(r.computed)if(q.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(q.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!q.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!q.isIdentifier(r)||r.name!==t?null:n}function Xp(e){if(q.isIdentifier(e))return{base:e.name,path:[]};if(!q.isMemberExpression(e))return null;let t=[],n=e;for(;q.isMemberExpression(n);){if(n.computed)if(q.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(q.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!q.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return q.isIdentifier(n)?{base:n.name,path:t}:null}function Qe(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}function zp(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,f){if(q.isStringLiteral(i)||q.isNumericLiteral(i)||q.isBooleanLiteral(i))return i.value;if(q.isNullLiteral(i))return null;if(q.isTemplateLiteral(i))return i.expressions.length===0&&i.quasis.length===1?i.quasis[0].value.cooked??i.quasis[0].value.raw:void 0;if(q.isTSAsExpression(i)||q.isTSSatisfiesExpression(i)||q.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,f);if(q.isIdentifier(i)){let m=s.getBinding(i.name);if(!m)return;let d=await t({currentFile:a,binding:m,readFile:c,exists:l,fileCache:u,visited:f});return d?.kind==="static"?d.value:void 0}if(q.isArrayExpression(i)){let m=[];for(let d of i.elements){if(!d||q.isSpreadElement(d))return;let g=await r(d,s,a,c,l,u,f);if(g===void 0)return;m.push(g)}return m}if(q.isObjectExpression(i)){let m={};for(let d of i.properties){if(!q.isObjectProperty(d)||d.computed)return;let g=null;if(q.isIdentifier(d.key)?g=d.key.name:q.isStringLiteral(d.key)&&(g=d.key.value),!g)return;if(d.shorthand){if(!q.isIdentifier(d.value))return;let E=await r(d.value,s,a,c,l,u,f);if(E===void 0)return;m[g]=E;continue}if(!q.isExpression(d.value))return;let h=await r(d.value,s,a,c,l,u,f);h!==void 0&&(m[g]=h)}return m}if(q.isMemberExpression(i)){let m=await o(i,s,a,c,l,u,f);if(!m)return;let d=s.getBinding(m.base);if(!d)return;let g=await t({currentFile:a,binding:d,readFile:c,exists:l,fileCache:u,visited:f});return!g||g.kind!=="static"?void 0:Qe(g.value,m.path)}}async function r(i,s,a,c,l,u,f){if(!q.isSpreadElement(i))return await n(i,s,a,c,l,u,f)}async function o(i,s,a,c,l,u,f){if(q.isIdentifier(i))return{base:i.name,path:[]};if(!q.isMemberExpression(i))return null;let m=[],d=i;for(;q.isMemberExpression(d);){if(d.computed){let g=d.property;if(q.isNumericLiteral(g))m.unshift({kind:"index",index:g.value});else if(q.isStringLiteral(g))m.unshift({kind:"property",name:g.value});else{let h=q.isExpression(g)?await n(g,s,a,c,l,u,f):void 0;if(typeof h=="string")m.unshift({kind:"property",name:h});else if(Number.isInteger(h))m.unshift({kind:"index",index:h});else return null}}else{if(!q.isIdentifier(d.property))return null;m.unshift({kind:"property",name:d.property.name})}d=d.object}return q.isIdentifier(d)?{base:d.name,path:m}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var Yp=typeof Cc=="function"?Cc:Cc.default,Hp=new WeakMap;function Zp(e){try{return Gp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Ui(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Zp(n);return e.set(t,{source:n,ast:o}),o}function Ki(e,t){let n=null,r=-1;for(let o of ro(e).expressions){let i=o.node.loc;if(!i||!wc(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function Qp(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of ro(e).expressions){if(!sk(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function Rc(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of ro(e).jsxElements){let i=o.node.loc;if(!i||!wc(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function ro(e){let t=Hp.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return Yp(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),Hp.set(e,n),n}function sk(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 wc(e,t){let n=Wp({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=Wp({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function Ji(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 Wp(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}function ir(e,t){if(t)return Nc(e,t);let n=Xp(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Nc(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function oo(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of ro(e).expressions){if(Nc(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function qp(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of ro(e).expressions){if(Nc(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!wc(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}function sr(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function io(e){let t=null;if(Yp(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function jt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Zp(o),s={source:o,ast:i};return n.set(e,s),s}function ak(e){return pe.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:pe.isMemberExpression(e.callee)&&pe.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function ck(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()||!pe.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 lk(e,t){let n=ck(e.path);if(!n)return null;let r=Gn(e,t);return r?{...n,...r}:null}function uk(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function Pc(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 Ac(e,t){for(let n of e.program.body){if(t==="default"&&pe.isExportDefaultDeclaration(n))return pe.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(pe.isFunctionDeclaration(n.declaration)||pe.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(pe.isExportNamedDeclaration(n)){if(n.declaration){if(pe.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(pe.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((pe.isFunctionDeclaration(n.declaration)||pe.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((pe.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&pe.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 em(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(d){let{currentFile:g,binding:h,readFile:E,exists:S,fileCache:v,visited:C}=d,N=`${g}::${h.kind}::${h.identifier.name}`;if(C.has(N))return null;C.add(N);try{let A=await a({currentFile:g,binding:h,readFile:E,exists:S,fileCache:v,visited:C});if(A)return A;if(h.path.isImportSpecifier()||h.path.isImportDefaultSpecifier())return await f({currentFile:g,binding:h,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,fileCache:v,visited:C});if(h.kind==="param")return null;if(h.path.isVariableDeclarator()){let P=h.path.node.init;if(!P||!pe.isExpression(P))return null;let k=h.path.get("init");if(k&&!Array.isArray(k)&&k.isExpression()){let O=await t({currentFile:g,expressionPath:k,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});if(O)return O;if(k.isCallExpression()){let L=await n({currentFile:g,callPath:k,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});if(L)return L}}let T=await r(P,h.path.scope,g,E,S,v,C);return T===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:T,sourceKind:"binding"}}if(h.path.isIdentifier()&&h.path.parentPath?.isExportDefaultDeclaration()){let P=h.path.parentPath.node.declaration;if(!pe.isExpression(P))return null;let k=await r(P,h.path.scope,g,E,S,v,C);return k===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:k,sourceKind:"binding"}}return null}finally{C.delete(N)}}async function a(d){let{currentFile:g,binding:h,readFile:E,exists:S,fileCache:v,visited:C}=d;if(!h.path.isVariableDeclarator()||!h.path.get("id").isArrayPattern())return null;let N=h.path,A=N.node.init;if(!A||!pe.isCallExpression(A))return null;let P=ak(A);if(!P||!pe.isArrayPattern(N.node.id)||N.node.id.elements.findIndex(G=>pe.isIdentifier(G)&&G.name===h.identifier.name)!==0)return null;let T=P==="useReducer"?1:0,O=A.arguments[T];if(!O||!pe.isExpression(O))return null;let L=await r(O,N.scope,g,E,S,v,C);return L===void 0?null:{kind:"static",file:g,root:{kind:"hook-state",name:h.identifier.name,hook:P},value:L,sourceKind:"binding"}}async function c(d){let g=lk(d.binding,d.sourceInfo);if(!g||!d.graph)return null;let h=[...d.graph.elements.values()].filter(P=>uk(P,d.currentFile,g.componentName,g.exportName));if(h.length!==1)return null;let E=h[0],S=E.attributes?.find(P=>P.name===g.propName);if(S&&!S.source){let P=await l({caller:E,propName:g.propName,remainingPath:g.remainingPath,readFile:d.readFile,fileCache:d.fileCache});if(P)return Pc(P,{componentName:g.componentName,propName:g.propName,file:E.sourceFile})}if(!S?.source){let P=await u({caller:E,propName:g.propName,remainingPath:g.remainingPath,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(P)return Pc(P,{componentName:g.componentName,propName:g.propName,file:E.sourceFile});let k=uf(d.binding,g.componentName,g.propName);if(!k||k.propName!==g.propName)return null;let T=await r(k.expressionPath.node,k.expressionPath.scope,d.currentFile,d.readFile,d.exists,d.fileCache,d.visited);if(T===void 0)return null;let O=g.remainingPath;return O.length>0&&Qe(T,O)===void 0?null:{kind:"value",file:d.currentFile,root:{kind:"binding",name:g.propName},path:O,sourceKind:"binding",semanticKind:"component-prop",displayExpression:k.displayPath,chainPrefix:[{kind:"component-prop",file:d.currentFile,displayName:k.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let v=await jt(E.sourceFile,d.readFile,d.fileCache);if(!v.ast)return null;let C=qp(v.ast,v.source,S.source.expression,S.sourceRange)??oo(v.ast,v.source,S.source.expression);if(!C)return null;let N={...S.source,expression:sr(S.source.expression,g.remainingPath),path:[...S.source.path,...g.remainingPath]},A=await o({currentFile:E.sourceFile,expressionPath:C,sourceInfo:N,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});return A?Pc(A.kind==="external"?A:{...A,displayExpression:N.expression},{componentName:g.componentName,propName:g.propName,file:E.sourceFile}):null}async function l(d){let g=await jt(d.caller.sourceFile,d.readFile,d.fileCache);if(!g.ast)return null;let h=Rc(g.ast,d.caller.sourceRange);if(!h)return null;let E=h.get("openingElement").get("attributes").find(N=>N.isJSXAttribute()&&N.node.name.type==="JSXIdentifier"&&N.node.name.name===d.propName);if(!E?.isJSXAttribute())return null;let S=E.get("value"),v=S.isStringLiteral()?S:S.isJSXExpressionContainer()?S.get("expression"):null;if(!v?.isExpression())return null;let C=Ji(v.node);return C?{kind:"value",file:d.caller.sourceFile,root:{kind:"expression",sourceRange:C},path:d.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:d.propName,editMode:"upstream",diagnostics:[]}:null}async function u(d){let g=await jt(d.caller.sourceFile,d.readFile,d.fileCache);if(!g.ast)return null;let h=Rc(g.ast,d.caller.sourceRange);if(!h)return null;let E=h.get("openingElement");for(let S of E.get("attributes")){if(!S.isJSXSpreadAttribute())continue;let v=S.get("argument");if(!v.isExpression())continue;let C=await i({expression:v.node,scope:v.scope,source:g.source,currentFile:d.caller.sourceFile,readFile:d.readFile,exists:d.exists,fileCache:d.fileCache,visited:d.visited});if(!C)continue;let N=[{kind:"property",name:d.propName},...d.remainingPath],A={...C,expression:sr(C.expression,N),path:[...C.path,...N]},P=await o({currentFile:d.caller.sourceFile,expressionPath:v,sourceInfo:A,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(P)return P.kind==="external"?P:{...P,displayExpression:A.expression}}return null}async function f(d){let{currentFile:g,binding:h,readFile:E,exists:S,fileCache:v,visited:C}=d,N=h.path.parentPath;if(!N||!N.isImportDeclaration())return null;let A=N.node.source.value;if(typeof A!="string")return null;let P=await hn(g,A,S);if(!P)return null;if(h.path.isImportDefaultSpecifier()){let ne=await jt(P,E,v),ve=ne.ast?Ac(ne.ast,"default"):null,Y=await m({file:P,exportName:"default",readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});return!Y||Y.kind!=="static"?null:{kind:"static",file:ve?.kind==="default-expression"?Y.file:P,root:ve?.kind==="default-expression"?Y.root:{kind:"default-export"},value:Y.value,sourceKind:"imported-binding"}}if(!h.path.isImportSpecifier())return null;let k=h.path.node.imported,T=pe.isIdentifier(k)?k.name:k.value,O=await jt(P,E,v),L=O.ast?Ac(O.ast,T):null,G=await m({file:P,exportName:T,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});return G?G.kind==="external"?G:{kind:"static",file:L?.kind==="re-export"?G.file:P,root:L?.kind==="re-export"?G.root:{kind:"named-export",name:T},value:G.value,sourceKind:"imported-binding"}:null}async function m(d){let{file:g,exportName:h,readFile:E,exists:S,fileCache:v,visited:C}=d,N=`export::${g}::${h}`;if(!C.has(N)){C.add(N);try{let A=await jt(g,E,v);if(!A.ast)return;let P=Ac(A.ast,h);if(!P)return;if(P.kind==="default-expression"){let L=P.expression;if(!L||!pe.isIdentifier(L))return;let G=io(A.ast).getBinding(L.name);return G?await s({currentFile:g,binding:G,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C})??void 0:void 0}if(P.kind==="re-export"){if(!P.source||!P.name)return;let L=await hn(g,P.source,S);return L?m({...d,file:L,exportName:P.name}):void 0}let k=P.name;if(!k)return;let T=io(A.ast).getBinding(k);return T?await s({currentFile:g,binding:T,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C})??void 0:void 0}finally{C.delete(N)}}}return{resolveExportValue:m,resolveComponentPropBinding:c,resolveBindingTarget:s}}import*as J from"@babel/types";function Fc(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=Et(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!dk(s,r)?null:{callPath:s,basePath:i}}function dk(e,t){let n=e.node.callee;return!J.isMemberExpression(n)||!J.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function rm(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:bi(r,t)}function tm(e,t){return e?J.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function nm(e,t,n,r,o){let i=J.isExpression(e.body)?e.body:e.body.body.find(a=>J.isReturnStatement(a))?.argument;if(!i||!J.isExpression(i))return;let s=Tc(i,t,n,r,o);return typeof s=="number"?s:void 0}function Tc(e,t,n,r,o){if(J.isNumericLiteral(e)||J.isStringLiteral(e)||J.isBooleanLiteral(e))return e.value;if(J.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(J.isMemberExpression(e)){let i=Vi(e,t);if(i)return Qe(r,i);let s=Vi(e,n);return s?Qe(o,s):void 0}if(J.isBinaryExpression(e)&&e.operator==="-"){let i=J.isExpression(e.left)?Tc(e.left,t,n,r,o):void 0,s=J.isExpression(e.right)?Tc(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function fk(e){if(J.isExpression(e.body))return e.body;for(let t of e.body.body)if(J.isReturnStatement(t)&&t.argument&&J.isExpression(t.argument))return t.argument;return null}function pk(e,t,n){let r=An(e,t,n);return typeof r=="boolean"?r:void 0}function An(e,t,n){if(J.isStringLiteral(e)||J.isNumericLiteral(e)||J.isBooleanLiteral(e))return e.value;if(J.isNullLiteral(e))return null;if(J.isIdentifier(e))return e.name===t?n:void 0;if(J.isMemberExpression(e)){let r=Vi(e,t);return r?Qe(n,r):void 0}if(J.isUnaryExpression(e)&&e.operator==="!"){let r=An(e.argument,t,n);return r===void 0?void 0:!r}if(J.isLogicalExpression(e)){let r=An(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&An(e.right,t,n);if(e.operator==="||")return r||An(e.right,t,n)}if(J.isBinaryExpression(e)){let r=J.isExpression(e.left)?An(e.left,t,n):void 0,o=J.isExpression(e.right)?An(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 om(e){let t=[],n=e;for(;J.isMemberExpression(n)||J.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(J.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(J.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(J.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(J.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return J.isIdentifier(n)?{base:n.name,segments:t}:null}function im(e){return e.some(t=>t.kind==="dynamic")}function mk(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function sm(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 gk(e,t){let n=[],r=[];for(let o of t){let i=Qe(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 am(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o}=e;async function i(d){let{currentFile:g,callPath:h,readFile:E,exists:S,fileCache:v,visited:C}=d,N=h.node.callee;if(!J.isMemberExpression(N)||!J.isIdentifier(N.property)||N.property.name!=="map")return null;let A=h.get("callee");if(!A.isMemberExpression())return null;let P=A.get("object");if(Array.isArray(P)||!P.isExpression())return null;let k=await s({currentFile:g,expressionPath:P,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});return!k||!Array.isArray(k.value)||k.value.length===0?null:k}async function s(d){let{currentFile:g,expressionPath:h,readFile:E,exists:S,fileCache:v,visited:C}=d;if(h.isIdentifier()){let N=h.scope.getBinding(h.node.name);if(!N)return null;let A=await t({currentFile:g,binding:N,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});return A?.kind==="static"?A:null}if(h.isCallExpression())return c({currentFile:g,callPath:h,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let N=h.get("expression");if(!Array.isArray(N)&&N.isExpression())return s({...d,expressionPath:N})}if(h.isArrayExpression()){let N=Ji(h.node);if(!N)return null;let A=await n(h.node,h.scope,g,E,S,v,C);return Array.isArray(A)?{kind:"static",file:g,root:{kind:"expression",sourceRange:N},value:A,sourceKind:"binding"}:null}if(h.isMemberExpression()){let N=await r({expression:h.node,scope:h.scope,currentFile:g,readFile:E,exists:S,fileCache:v,visited:C});if(!N)return null;let A=await o({currentFile:g,expressionPath:h,sourceInfo:N,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});if(!A||A.kind==="external")return null;let P=await a({currentFile:g,expressionPath:h,provenance:A,readFile:E,exists:S,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:v,visited:C});if(!P||P.kind!=="static")return null;if(A.collectionPathMap?.length){let T=gk(P.value,A.collectionPathMap);if(T)return{kind:"static",file:A.file,root:A.root,value:T.value,sourceKind:A.sourceKind,collectionPathMap:T.collectionPathMap}}let k=Qe(P.value,A.path);return Array.isArray(k)?{kind:"static",file:A.file,root:A.root,value:k,sourceKind:A.sourceKind,pathPrefix:A.path,collectionIndexMap:A.collectionIndexMap,collectionPathMap:A.collectionPathMap}:null}return null}async function a(d){let{provenance:g}=d;if(g.root.kind==="binding"){let v=d.expressionPath.scope.getBinding(g.root.name);if(!v&&g.file!==d.currentFile){let C=await jt(g.file,d.readFile,d.fileCache);v=C.ast?io(C.ast).getBinding(g.root.name):void 0}return v?await t({currentFile:g.file,binding:v,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited}):null}if(g.root.kind!=="expression")return null;let h=await jt(g.file,d.readFile,d.fileCache);if(!h.ast)return null;let E=Qp(h.ast,g.root.sourceRange);if(!E)return null;let S=await n(E.node,E.scope,g.file,d.readFile,d.exists,d.fileCache,d.visited);return S===void 0?null:{kind:"static",file:g.file,root:g.root,value:S,sourceKind:g.sourceKind}}async function c(d){return await l(d)??await u(d)??await f(d)}async function l(d){let{callPath:g}=d,h=g.node.callee;if(!J.isMemberExpression(h)||!J.isIdentifier(h.property)||h.property.name!=="filter")return null;let E=g.get("callee");if(!E.isMemberExpression())return null;let S=E.get("object");if(Array.isArray(S)||!S.isExpression())return null;let v=await s({currentFile:d.currentFile,expressionPath:S,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!v||!Array.isArray(v.value))return null;let[C]=g.node.arguments;if(!J.isArrowFunctionExpression(C)&&!J.isFunctionExpression(C))return null;let N=C.params[0];if(!J.isIdentifier(N))return null;let A=fk(C);if(!A)return null;let P=[],k=[],T=[];for(let[O,L]of v.value.entries()){let G=pk(A,N.name,L);if(typeof G!="boolean")return null;if(G){P.push(L),k.push(v.collectionIndexMap?.[O]??O);let ne=v.collectionPathMap?.[O];ne&&T.push(ne)}}return{...v,value:P,pathPrefix:v.pathPrefix,collectionIndexMap:k,...T.length>0?{collectionPathMap:T}:{}}}async function u(d){let{callPath:g}=d,h=g.node.callee;if(!J.isMemberExpression(h)||!J.isIdentifier(h.property)||h.property.name!=="slice")return null;let E=g.get("callee");if(!E.isMemberExpression())return null;let S=E.get("object");if(Array.isArray(S)||!S.isExpression())return null;let v=await s({currentFile:d.currentFile,expressionPath:S,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!v||!Array.isArray(v.value))return null;let[C,N]=g.node.arguments,A=tm(C,0),P=tm(N,v.value.length);if(A===null||P===null)return null;let k=Math.max(0,A<0?v.value.length+A:A),T=Math.max(0,P<0?v.value.length+P:P),O=v.value.map((G,ne)=>v.collectionIndexMap?.[ne]??ne).slice(k,T),L=v.collectionPathMap?.slice(k,T);return{...v,value:v.value.slice(k,T),pathPrefix:v.pathPrefix,collectionIndexMap:O,...L?{collectionPathMap:L}:{}}}async function f(d){let{callPath:g}=d,h=g.node.callee;if(!J.isMemberExpression(h)||!J.isIdentifier(h.property)||h.property.name!=="sort"&&h.property.name!=="toSorted")return null;let E=g.get("callee");if(!E.isMemberExpression())return null;let S=E.get("object");if(Array.isArray(S)||!S.isExpression())return null;let v=await s({currentFile:d.currentFile,expressionPath:S,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!v||!Array.isArray(v.value))return null;let[C]=g.node.arguments;if(!J.isArrowFunctionExpression(C)&&!J.isFunctionExpression(C))return null;let[N,A]=C.params;if(!J.isIdentifier(N)||!J.isIdentifier(A))return null;let P=v.value.map((T,O)=>({value:T,sourceIndex:v.collectionIndexMap?.[O]??O,originalIndex:O})),k=[...P];for(let T of P)for(let O of P)if(nm(C,N.name,A.name,T.value,O.value)===void 0)return null;return k.sort((T,O)=>{let L=nm(C,N.name,A.name,T.value,O.value)??0;return L===0?T.originalIndex-O.originalIndex:L}),{...v,value:k.map(T=>T.value),pathPrefix:v.pathPrefix,collectionIndexMap:k.map(T=>T.sourceIndex),...v.collectionPathMap?{collectionPathMap:k.map(T=>v.collectionPathMap?.[T.originalIndex]).filter(T=>!!T)}:{}}}async function m(d){let g=null,h,E=[];for(let v of d.segments){if(v.kind!=="dynamic")continue;let C=await r({expression:v.expression,scope:d.expressionPath.scope,source:d.fileCache.get(d.currentFile)?.source,currentFile:d.currentFile,readFile:d.readFile,exists:d.exists,fileCache:d.fileCache,visited:d.visited});if(!C)return null;let N=Fc(d.expressionPath,C.base);if(!N)return null;let A=await i({currentFile:d.currentFile,callPath:N.callPath,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!A||!Array.isArray(A.value))return null;let P=A.value.map((k,T)=>{let O=Qe(A.value,[{kind:"index",index:T},...N.basePath,...C.path]);return mk(O)});if(P.some(k=>k===null)||g!==null&&g!==P.length)return null;g=P.length,h??=A.collectionIndexMap,E.push(P)}if(g===null||g===0)return null;let S=[];for(let v=0;v<g;v+=1){let C=[...d.rootPath],N=0;for(let A of d.segments){if(A.kind==="dynamic"){let P=E[N]?.[v];if(!P)return null;C.push(P),N+=1;continue}C.push({...A})}S.push(C)}return{...h?{collectionIndexMap:h}:{},collectionPathMap:S}}return{resolveRepeatCollectionTarget:i,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:hk,evaluateStaticExpression:Xi}=zp({resolveBindingTarget:e=>Bc(e)}),{resolveRepeatCollectionTarget:yk,resolveCollectionCallTarget:xk,resolveDynamicMemberPathMap:bk}=am({resolveBindingTarget:e=>Bc(e),evaluateStaticExpression:Xi,buildExpressionSourceInfo:$t,resolveSourceInfoProvenance:ht}),{resolveExportValue:Sk,resolveComponentPropBinding:Ek,resolveBindingTarget:Bc}=em({resolveExternalExpression:$c,resolveCollectionCallTarget:xk,evaluateStaticExpression:Xi,resolveSourceInfoProvenance:ht,buildExpressionSourceInfo:$t});function gm(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}function cm(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 hm(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Ui(s,t,n);if(!a)return null;let c=Ki(a,r.sourceRange);if(!c)return null;let l=await $t({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await Jc({currentFile:t,expressionPath:c,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});return m?Mc(m,ir(c.node,n)):null}let u=new Set,f=await Kk({currentFile:t,expressionPath:c,segment:{...r,source:l},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:u});return f?Mc(f,l.expression):null}async function ar(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Ui(i,t,n);if(!s)return null;let a=e.sourceRange?Ki(s,e.sourceRange):e.expression!==void 0?oo(s,n,e.expression):null;if(!a)return null;let c=Xc(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await $t({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),f=u?await ht({currentFile:t,expressionPath:c,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l}):await Jk({currentFile:t,expressionPath:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l});return Mc(f,e.expression??ir(c.node,n))}async function jc(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Ui(i,t,n);if(!s)return ot("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?vk({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}):Ik({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function $t(e){if(H.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!H.isMemberExpression(e.expression))return null;let t=await hk(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:ir(e.expression,e.source),base:t.base,path:t.path}:null}function Mc(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 vk(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Ki(r,o.sourceRange),u=l?await $t({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null;if(!u){if(!l||l.isStringLiteral()||l.isTemplateLiteral()&&l.node.expressions.length===0)return lm(t,o.value);let m=await Jc({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return m?m.kind==="external"?mm(t,m):Lc(t,ir(l.node,n),m):kk({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return ot("unsupported-expression","Unable to locate text expression for provenance resolution");let f=await ht({currentFile:t,expressionPath:l,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!f){let m=Dc(l.node);if(m)return ot(m.code,m.message);let d=l.scope.getBinding(u.base);if(d?.path.isVariableDeclarator()){let g=Dc(d.path.node.init);if(g)return ot(g.code,g.message)}return d?.path.isVariableDeclarator()&&H.isCallExpression(d.path.node.init)?Ck("unsupported-expression",Em(d.path.node.init,e.functionCallContracts)):ot("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return f.kind==="external"?mm(t,f):Lc(t,u.expression,f)}async function Ik(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return ot("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=oo(r,n,o.conditionExpression);if(!l)return ot("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await ht({currentFile:t,expressionPath:l,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!u)return ot("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return ot("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=Lc(t,o.conditionExpression,u);return f.finalSource?{...f,finalSource:{...f.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...f.chain,{kind:"conditional-branch",file:u.file,displayName:o.conditionExpression,canEditHere:!0}]}:f}function lm(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 kk(e){let t=await xm(e);if(t.length===0)return ot("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(Rk(e.expression))return ym(t);if(Sm(e.expression))return ot("unsupported-expression","i18n helpers require a static message id string");if(H.isMemberExpression(e.expression)&&e.expression.computed&&!H.isNumericLiteral(e.expression.property)&&!H.isStringLiteral(e.expression.property))return ot("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return ot(n.code,n.message)}function ot(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function Ck(e,t){return ym([{code:e,message:t}])}function ym(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function Rk(e){return H.isCallExpression(e)||H.isConditionalExpression(e)||H.isLogicalExpression(e)||H.isBinaryExpression(e)}function ao(e){let t=new Set;return e.filter(n=>{let r=`${n.code}:${n.message}`;return t.has(r)?!1:(t.add(r),!0)})}async function xm(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Dc(t);if(l)return[l];if(H.isCallExpression(t))return[{code:"unsupported-expression",message:Em(t,c)}];if(H.isMemberExpression(t)&&t.computed){let u=t.property;if(!H.isNumericLiteral(u)&&!H.isStringLiteral(u)){if(!H.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let m=await Xi(u,n,r,o,i,s,a);if(typeof m!="string"&&!Number.isInteger(m))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return H.isBinaryExpression(t)?ao([...await _c(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):H.isLogicalExpression(t)?ao([...await _c(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"}]):H.isConditionalExpression(t)?ao([...await _c(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 Dc(e){return Sm(e)?um("i18n helpers require a static message id string"):Tk(e)?um("CMS helpers require static entry id and field path string arguments"):null}async function _c(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await xm({...t,expression:o}));return r}function wk(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:[Nk(e.sourceType)]}}async function $c(e){for(let n of Mk){if(!dm(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return pm(fm(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(!dm(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return pm(fm(r),e.externalAdapters)}return null}function Nk(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function Pk(e){return{code:"external-source-readonly",message:e}}function um(e){return{code:"unsupported-expression",message:e}}function Vc(e){return!e||!H.isCallExpression(e)?null:H.isIdentifier(e.callee)?e.callee.name:H.isMemberExpression(e.callee)&&!e.callee.computed&&H.isIdentifier(e.callee.object)&&H.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function dm(e,t){if(!t||t.length===0)return!0;let n=Vc(e.node);return n?t.includes(n):!1}function fm(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:ao(e.diagnostics??[])}:{match:e,diagnostics:[]}}function pm(e,t){let n=wk(e.match,t);return{kind:"external",file:e.match.file,sourceType:e.match.sourceType,sourceId:e.match.sourceId,adapterId:e.match.adapterId??n.adapterId,displayPath:e.match.displayPath,editMode:e.editMode==="readonly"?"readonly":n.editMode,diagnostics:ao([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function Ak(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!H.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!H.isStringLiteral(n)||!H.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 Tk(e){return!!e&&H.isCallExpression(e)&&H.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!H.isStringLiteral(e.arguments[0])||!H.isStringLiteral(e.arguments[1]))}function bm(e){if(!(!e||!H.isCallExpression(e))){if(H.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&H.isStringLiteral(t)?t.value:null}if(H.isMemberExpression(e.callee)&&!e.callee.computed&&H.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&H.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!H.isObjectExpression(t))return null;for(let n of t.properties)if(H.isObjectProperty(n)&&!n.computed&&(H.isIdentifier(n.key)&&n.key.name==="id"||H.isStringLiteral(n.key)&&n.key.value==="id")&&H.isStringLiteral(n.value))return n.value.value;return null}}}function Sm(e){return bm(e)===null}async function Fk(e,t,n){let r=new Set,o=so.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=so.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"]:[so.posix.join(i,"locales"),so.posix.join(i,"messages")];for(let a of s){let c=so.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function _k(e){let t=bm(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await Fk(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function Ok(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!H.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!H.isExpression(n))return null;let o=await Xi(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:[Pk("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var Mk=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>Ak(e)},{helperNames:["apiField"],resolve:e=>Ok(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>_k({currentFile:e,expressionPath:t,exists:n})}];function Uc(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function mm(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 Lc(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(l=>l.kind==="index"),i=Uk(n),s;n.semanticKind?s=n.semanticKind:i?s="config-entry":n.sourceKind==="repeat-template"?s="repeat-template":n.path.length===0?s=n.sourceKind==="imported-binding"?"imported-binding":"binding":s=o?"array-item":"object-field";let a=n.displayExpression??t,c=[...n.chainPrefix??[]];return n.sourceKind==="binding"?c.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:n.editMode!=="readonly"}):n.sourceKind==="imported-binding"?c.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:n.editMode!=="readonly"}):n.sourceKind==="repeat-template"&&c.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:n.editMode!=="readonly"}),n.path.length>0&&n.sourceKind!=="repeat-template"&&c.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:n.editMode!=="readonly"}),i&&c.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:n.editMode!=="readonly"}),{finalSource:{kind:s,file:n.file,locator:r,root:n.root,path:n.path,displayPath:a,externalSource:i?{sourceType:"config-entry",sourceId:i.sourceId}:void 0},chain:n.editMode==="readonly"?c.map(l=>({...l,canEditHere:!1})):c,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var Dk=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Kc(e,t){let n=[...Dk,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function Em(e,t){let n=e.callee;return H.isIdentifier(n)&&Kc(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 Jc(e){let t=await $c(e);if(t)return t;let n=await vm({...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 $t({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 ht({...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 $k(e)}async function vm(e){let t=await It({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=Xc(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:Uc(t.provenance)}async function It(e){let t=Xc(e.expressionPath),n=jk(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 $t({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 ht({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 $t({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 ht({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 It({...e,expressionPath:r,allowComposed:!0}),a=await It({...e,expressionPath:o,allowComposed:!1}),c=await It({...e,expressionPath:i,allowComposed:!1});return Oc(s,a,c)}if(t.isCallExpression())return Lk({...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 It({...e,expressionPath:r,allowComposed:!0}),s=await It({...e,expressionPath:o,allowComposed:!0});return Oc(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 It({...e,expressionPath:r,allowComposed:!0}),s=await It({...e,expressionPath:o,allowComposed:!0});return Oc(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:It({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Xc(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 Lk(e){let t=Vc(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:It({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(H.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:It({...e,expressionPath:o,allowComposed:!1})}}return null}function Oc(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!Bk(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function Bk(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 jk(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function $k(e){if(!e.expressionPath.isCallExpression())return null;let t=Vc(e.expressionPath.node);if(!t)return null;let n=Kc(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 Im({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?Uc(i):null}async function Im(e){let t=await $c({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 $t({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 ht({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 Jc({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 Vk(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!H.isCallExpression(t))return null;let n=t.callee;if(!H.isIdentifier(n))return null;let r=Kc(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 Im({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?Uc(a):null}function Uk(e){if(e.sourceKind!=="imported-binding")return null;let t=e.root.kind==="binding"||e.root.kind==="named-export"?e.root.name:e.root.kind==="default-export"?"default":null;if(!t)return null;let n=/(^|[\/.-])(config|settings)([\/.-]|$)/i.test(e.file),r=/config|settings/i.test(t);if(!n&&!r)return null;let o=sr(t,e.path);return{sourceId:o,displayPath:o}}async function Kk(e){let t=e.segment.source;return t?ht({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 ht(e){let t=e.sourceInfo,n=Fc(e.expressionPath,t.base);if(n){let l=await yk({currentFile:e.currentFile,callPath:n.callPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:e.fileCache,visited:e.visited});if(!l){let h=rm(n.callPath,[...n.basePath,...t.path]);return Ur(h)?cm(e.currentFile,h.sourceId,h.displayPath):null}let u=sm(l,[...n.basePath,...t.path]),f=l.collectionIndexMap?.[0]??0,m=[...l.pathPrefix??[],{kind:"index",index:f},...n.basePath,...t.path],d=[{kind:"index",index:0},...n.basePath,...t.path];return Qe(l.value,d)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??m,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],u=r.path.parentPath;if(!l||l.kind!=="property"||!u?.isImportDeclaration())return null;let f=await hn(e.currentFile,u.node.source.value,e.exists);if(!f)return null;let m=await Sk({file:f,exportName:l.name,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!m||m.kind==="external")return null;let d=t.path.slice(1);return Qe(m.value,d)===void 0?null:{kind:"value",file:m.file,root:m.root,path:d,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=cf(r);if(o){let l=o.expressionPath,u=await $t({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let f=await ht({...e,expressionPath:l,sourceInfo:{...u,expression:sr(u.expression,t.path),path:[...u.path,...t.path]}});if(f)return f}if(t.path.length===0){let f=await vm({currentFile:e.currentFile,expressionPath:l,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(f)return f}}if(r.kind==="param")return Ek({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 Vk({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=yi(r,t.path);if(Ur(s))return cm(e.currentFile,s.sourceId,s.displayPath);let a=await Bc({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:Qe(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 Jk(e){let t=om(e.expressionPath.node);if(!t||!im(t.segments))return null;let n=await ht({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 bk({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:ir(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function km(e){let t=Xk(e.propertyName);if(t.owner==="blocked")return an(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return an(t.owner,{code:"owner-delegated",message:`Property '${e.propertyName}' is owned by ${t.owner}`});let n=e.element.attributes?.filter(l=>l.name===e.propertyName)??[];if(n.length>1)return an("generic",{code:"duplicate-property-source",message:`Property '${e.propertyName}' has multiple explicit sources`});let r=n[0],o=[];r&&o.push({kind:"attribute",order:r.order??e.element.attributes.indexOf(r),attribute:r});let i=e.element.attributeSpreads??[];for(let l of i)o.push({kind:"spread",order:l.order,spread:l,target:await Hk(e,l)});o.sort((l,u)=>l.order-u.order);let s=o.at(-1);if(!s)return{status:"missing",owner:"generic"};if(o.filter(l=>l.kind==="spread"&&l.order>s.order).some(l=>!l.target))return an("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}:an("generic",{code:"ambiguous-property-source",message:`The final spread source for '${e.propertyName}' is not provably writable`});let c=o.filter(l=>l.kind==="spread"&&l.order<s.order);return e.operation==="remove"&&c.length>0?an("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):zk(e,s.attribute)}async function zk(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await ar({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}}:an("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 ar({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"?an("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 Hk(e,t){let n=t.source?.expression;if(!n)return;let r=await ar({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:Wk(r,e.propertyName)}}function Wk(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 an(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function Cm(e){let{key:t,element:n,graph:r,provenances:o}=e,i=Yk(t,n,r),s=i?.tag??(Tn(n.tag)?n.tag:n.componentName),a=i?.identity.key??Rm(n,r)??t,c=qk(i),l=eC(t,n,r,o,i),u=Gk(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:Qk(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:u,impactScope:tC(u),alternativeStrategies:nC(u)}}function Gk(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return zc(e,n)?"instance":!Tn(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function Rm(e,t){if(Tn(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&Zk(r,e.componentName));return n.length!==1?null:n[0].identity.key}function Yk(e,t,n){if(Tn(t.tag))return t;let r=zc(e,n);if(r)return r;let o=Rm(t,n);return o?n.elements.get(o)??null:null}function Zk(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function Qk(e,t){return Tn(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function qk(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 eC(e,t,n,r,o){let i=new Set,s=zc(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(u=>u.kind==="component-prop");if(!c)continue;let l=c.displayName.split(".").pop();l&&i.add(l)}return i.size===0&&Tn(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function zc(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Tn(r.tag))return r;n=r.parentKey}return null}function Tn(e){return/^[A-Z]/.test(e)}function tC(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function nC(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function Pm(e){let t=e.isRepeat??(e.graph?dC(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=uC(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>rC({attribute:u,element:e.element,isRepeat:t,selectionRef:e.selectionRef,provenance:n.get(u.name),repeatTarget:r.get(u.name)})),a=(e.element.attributeSpreads?.length??0)>0,c=(e.element.attributeSpreads??[]).slice().sort((u,f)=>u.order-f.order).map(u=>({raw:u.raw,sourceRange:fC(u.sourceRange,e.source),order:u.order,diagnostics:u.source?[]:[{code:"unsupported-spread-source",message:"The spread source cannot be resolved safely, so property ownership is conservative."}]})),l=t&&e.selectionRef?.instanceIndex!==void 0&&i;return{documentVersion:e.documentVersion,...e.selectionRef?{selectionRef:e.selectionRef}:{},items:s,spreads:c,creation:t?{selection:l?"materialize":"unsupported",template:"unsupported"}:{selection:a?"unsupported":"direct",template:a?"unsupported":"direct"}}}function rC(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=oC(t,n,e.isRepeat),s=["selection","template"].map(E=>({scope:E,result:Ri({state:n,scope:E,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:E})=>E.ok)?.result,c=a?.ok?a.target:void 0,l=c?.kind==="value-binding"&&o&&(JSON.stringify(c.locator.root)!==JSON.stringify(o.selectedParentObjectLocator.root)||JSON.stringify(c.locator.path??[])!==JSON.stringify([...o.selectedParentObjectLocator.path??[],{kind:"property",name:t.name}]))?null:o,u=iC(t,n,l,e.isRepeat),f=c?cC(c,e.element,t.name):void 0,m=s.filter(({result:E})=>E.ok).map(({scope:E})=>E),d=m.length>0?aC(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=lC(t,n,r);if(m.length===0&&h.length===0){let E=s.find(({result:S})=>!S.ok)?.result;E&&!E.ok&&h.push({code:E.code,message:E.reason})}return{name:t.name,source:i,resolution:u,editMode:d,sourceScope:g,allowedWriteScopes:m,...f?{effectiveWriteTarget:f}:{},diagnostics:h}}function oC(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 iC(e,t,n,r){return n?wm(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:wm(sC(e))}function sC(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 wm(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function aC(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 cC(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:Nm({...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:Nm(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function lC(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 uC(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function dC(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 Nm(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 fC(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 pC(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var mC=160;function Am(e,t,n,r={}){let o=Kn(e),i=[];for(let[s,a]of e.elements){let c=n.get(s),l={canUpdateText:r.canUpdateTextByKey?.get(s)??c?.canUpdateText??!1,canInsertChild:c?.canInsertChild??!1,canMove:c?.canMove??!1,canRemove:c?.canRemove??!1};i.push({key:s,tag:a.tag,label:a.tag===a.componentName?a.tag:`${a.tag} (${a.componentName})`,parentKey:a.parentKey,childKeys:[...a.childKeys],operationSummary:l,...r.dynamicDataSummaryByKey?.get(s)?{dynamicDataSummary:r.dynamicDataSummaryByKey.get(s)}:{}})}return{composition:o,routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:i}}function Tm(e,t,n,r,o,i,s,a,c,l,u){let f=Kn(t),m=t.elements.get(e),d=n.nodes.get(e),g=r.get(e);if(!m||!d||!g)throw new Error(`Node not found: ${e}`);let h=Dm(m.textSegments,s),E=Lm(e,t,m,g,h),S=h?yC(h):void 0,v=xC(i,h),C=m.textSegments.map(k=>({index:k.index,value:k.value,editable:Bm(k,g,s?.get(k.index)??null),source:o.get(k.index)??null})),N=Om(m,t),A=m.childKeys.map(k=>{let T=t.elements.get(k);return T?{key:k,tag:T.tag,label:T.tag}:null}).filter(k=>k!==null),P=[];if(m.parentKey){let k=t.elements.get(m.parentKey);if(k)for(let T of k.childKeys){if(T===e)continue;let O=t.elements.get(T);O&&P.push({key:T,tag:O.tag,label:O.tag})}}return{composition:f,key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:_m(m),label:m.tag,capabilities:E,writeTarget:i,effectiveWriteTarget:v,provenanceChain:S,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:C,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:N,children:A,siblings:P}}function Fm(e,t,n,r,o,i,s,a){let c=Kn(t),l=t.elements.get(e),u=n.nodes.get(e),f=r.get(e);if(!l||!u||!f)throw new Error(`Node not found: ${e}`);let m=Dm(l.textSegments,i);return{composition:c,key:e,tag:l.tag,componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:_m(l),label:l.tag,capabilities:Lm(e,t,l,f,m),provenanceChain:m?{editMode:m.editMode,diagnostics:m.diagnostics.map(d=>({code:d.code,message:d.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(d=>{let g=o.get(d.index);return{index:d.index,editable:Bm(d,f,i?.get(d.index)??null),source:g?{kind:g.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:Om(l,t)}}function _m(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:gC(e.sourceRange),structuralPath:e.identity.structuralPath,...hC(e.textSegments)}}function Om(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 gC(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function hC(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,mC)}:{}}function Mm(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 Dm(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function Lm(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(u=>u.kind==="repeat-region"&&u.childKeys.includes(e)),a=o?.diagnostics.find(u=>u.code==="missing-adapter"||u.code==="external-source-readonly")?.code,c=r.canUpdateText?{mode:o?.editMode??"direct",reasonCode:a??(o?.editMode==="upstream"?"component-prop":o?.finalSource?.kind==="repeat-template"?"repeat-item-data":void 0)}:{mode:"unsupported",reasonCode:"capability-denied"},l=r.canUpdateText&&jm(c.mode);return{...r,canUpdateText:l,editModes:{updateText:c,insertChild:r.canInsertChild?{mode:"direct",reasonCode:i||s?"repeat-template":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},move:r.canMove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},remove:r.canRemove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"}}}}function Bm(e,t,n){return!e.editable||!t.canUpdateText?!1:n?jm(n.editMode):!0}function jm(e){return e==="direct"||e==="proxy"||e==="upstream"}function yC(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 xC(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}:pC(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 Hc=["set-class-name-source","apply-style-draft"];function $m(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Hc,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:Hc,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Hc}}function Vm(e){let t=new Map;for(let[n,r]of e.elements){let o=/^[A-Z]/.test(r.tag),i={file:r.sourceFile,componentName:r.componentName,isProxy:o},s=r.boundaryKind,a=[];r.isOpaque&&a.push({kind:"opaque-region",reason:`Component '${r.tag}' is opaque: internal structure not editable`}),o&&!r.isOpaque&&a.push({kind:"component-boundary",reason:`Component '${r.tag}' boundary: editing requires source file access`});let c={key:n,writeTarget:i,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,c)}for(let n of e.regions){let r=n.kind==="repeat-region"?"repeat-region":n.kind==="conditional-region"?"conditional-region":n.kind==="opaque-region"?"opaque-region":"component-boundary",o=n.kind==="repeat-region"?"Node is inside a repeat region: operations affect the template, not individual instances":n.kind==="conditional-region"?"Node is inside a conditional region: visibility depends on runtime condition":`Node is inside a ${n.kind}`;for(let i of n.childKeys){let s=t.get(i);s&&s.constraints.push({kind:r,reason:o}),Um(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Um(e,t,n,r,o){let i=o.elements.get(e);if(i)for(let s of i.childKeys){let a=r.get(s);a&&!a.constraints.some(c=>c.kind===t)&&(a.constraints.push({kind:t,reason:n}),Um(s,t,n,r,o))}}import Km from"node:path";function Gc(){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 Xm(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=vC(i.path);if(!s.ok)return s;let a=s.path;if(o.has(a))return{ok:!1,code:"duplicate-target",path:a,reason:`Duplicate file target: ${a}`};if(o.add(a),i.kind==="create-only"){let c=t.has(a),l=n?await n(a):!1;if(c||l)return{ok:!1,code:"create-only-exists",path:a,reason:`Create-only file already exists: ${a}`}}r.push({...i,path:a})}return{ok:!0,plan:{operationId:e.operationId,intents:r}}}async function zi(e){let t=()=>bC(e);return e.mutex?e.mutex.runExclusive(t):t()}async function bC(e){let t=await Xm(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=SC(e.overlay,t.plan),r;try{r=await e.buildCandidate({overlay:n,plan:t.plan})}catch(l){return{ok:!1,stage:"build",reason:"Candidate build failed.",error:l,recoveryRequired:!1}}let o,i;try{o=await e.prepareHistory?.({candidate:r,plan:t.plan}),await e.reverify?.({candidate:r,plan:t.plan,history:o}),i=await e.writeCandidate({candidate:r,plan:t.plan}),await e.markCandidateWritten?.({candidate:r,plan:t.plan,history:o,receipt:i})}catch(l){return Wc({candidate:r,plan:t.plan,failedStage:"commit",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let s=r;try{let l=await e.validateCandidate({candidate:r,plan:t.plan,receipt:i});l!==void 0&&(s=l)}catch(l){return Wc({candidate:r,plan:t.plan,failedStage:"validate",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let a;try{a=await e.publishCandidate({candidate:s,plan:t.plan,history:o,receipt:i})}catch(l){return Wc({candidate:s,plan:t.plan,failedStage:"publish",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let c={candidate:s,plan:t.plan,history:o,receipt:i,published:a};try{await e.swapCandidate?.(c)}catch(l){return Jm("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return Jm("finalize",l,"Transaction finalization failed after live state swap.")}try{e.emitCommitted?.({candidate:s,plan:t.plan,published:a})}catch{}return{ok:!0,stage:"publish",published:a,plan:t.plan}}function SC(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 Wc(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:EC(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 Jm(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function EC(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 vC(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)||Km.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Km.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 IC=50,kC=8*1024*1024;function Gm(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??IC),s=Math.max(0,t.maxUndoBytes??kC);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:f};async function a(k){let T=[...k.steps].sort((Y,ue)=>Y.order-ue.order),O=T.filter(Y=>Y.type!=="invoke-external-adapter");if(O.length!==T.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let L=new Set(O.map(Y=>Y.file)),G=await v(L),ne=new Map(G.map(Y=>[Y.file,Y.exists===!1?"":Y.content])),ve;for(let Y of O){let ue=Wm(Y,ne.get(Y.file)??"");if(!ue.ok)return{ok:!1,errorCode:ue.errorCode,reason:ue.reason};ne.set(Y.file,ue.source),ve=ue.selectionRef??ve}return{ok:!0,filePlan:{operationId:k.operationId,kind:"source-edit",target:k.target,documentVersion:k.documentVersion,conflictPolicy:"compare-and-swap",edits:[...ne].map(([Y,ue])=>({operation:"upsert",file:Y,content:ue,baseContentHash:G.find(Ae=>Ae.file===Y)?.sha256??null}))},...ve?{selectionRef:ve}:{}}}async function c(k){let T=[...k.steps].sort((Ae,zt)=>Ae.order-zt.order),O=T.filter(Ae=>Ae.type!=="invoke-external-adapter"),L=T.filter(Ae=>Ae.type==="invoke-external-adapter"),G=new Set(O.map(Ae=>Ae.file));if(O.length>0&&L.length>0)return{ok:!1,operationId:k.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(O.length===0)return E(k,L);let ne=await v(G),ve=new Map;for(let Ae of ne)ve.set(Ae.file,Ae.exists===!1?"":Ae.content);let Y;for(let Ae of O){let zt=ve.get(Ae.file)??"",Ht=Wm(Ae,zt);if(!Ht.ok)return{ok:!1,operationId:k.operationId,errorCode:Ht.errorCode,reason:Ht.reason,rolledBack:!1};ve.set(Ae.file,Ht.source),Ht.selectionRef&&(Y=Ht.selectionRef)}let ue=await N([...ve].map(([Ae,zt])=>({file:Ae,content:zt,exists:!0,version:0,sha256:be(zt)})),ne);return ue.ok===!1?{ok:!1,operationId:k.operationId,errorCode:ue.rolledBack?"writeback-failed":"rollback-failed",reason:ue.reason,rolledBack:ue.rolledBack}:(n.push({operationId:k.operationId,preSnapshots:ne,postSnapshots:ue.snapshots,plan:k}),m(),r.length=0,{ok:!0,operationId:k.operationId,kind:k.kind,target:k.target,resultVersion:Math.max(...ue.snapshots.map(Ae=>Ae.version)),affectedFiles:[...G],...Y?{selectionRef:Y}:{}})}async function l(k){let T=new Set(k.edits.map(ue=>ue.file)),O=await v(T),L=S(k,O);if(L)return{ok:!1,operationId:k.operationId,errorCode:"stale-version",reason:L.reason,affectedFiles:[L.file],rolledBack:!1};let G=new Map(O.map(ue=>[ue.file,ue])),ne=k.edits.find(ue=>ue.operation==="create-only"&&G.get(ue.file)?.exists!==!1);if(ne)return{ok:!1,operationId:k.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${ne.file}`,affectedFiles:[ne.file],rolledBack:!1};let ve=k.edits.map(ue=>ue.operation==="delete"?{file:ue.file,content:"",exists:!1,version:0}:{file:ue.file,content:ue.content,exists:!0,version:0,sha256:be(ue.content)}),Y=await N(ve,O,new Set(k.edits.filter(ue=>ue.operation==="create-only").map(ue=>ue.file)));return Y.ok===!1?{ok:!1,operationId:k.operationId,errorCode:Y.rolledBack?"writeback-failed":"rollback-failed",reason:Y.reason,rolledBack:Y.rolledBack}:(n.push({operationId:k.operationId,preSnapshots:O,postSnapshots:Y.snapshots,plan:{operationId:k.operationId,kind:k.kind,target:k.target,documentVersion:k.documentVersion,steps:[],preSnapshots:O}}),m(),r.length=0,{ok:!0,operationId:k.operationId,kind:k.kind,target:k.target,resultVersion:Math.max(...Y.snapshots.map(ue=>ue.version)),affectedFiles:[...T]})}async function u(){let k=n.at(-1);if(!k)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let T=await N(k.preSnapshots,k.postSnapshots);return T.ok===!1?{ok:!1,operationId:k.operationId,errorCode:T.rolledBack?"writeback-failed":"rollback-failed",reason:T.reason,rolledBack:T.rolledBack}:(n.pop(),r.push(k),{ok:!0,operationId:k.operationId,kind:k.plan.kind,target:k.plan.target,resultVersion:Math.max(...T.snapshots.map(O=>O.version)),affectedFiles:k.preSnapshots.map(O=>O.file)})}async function f(){let k=r.at(-1);if(!k)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let T=await N(k.postSnapshots,k.preSnapshots);return T.ok===!1?{ok:!1,operationId:k.operationId,errorCode:T.rolledBack?"writeback-failed":"rollback-failed",reason:T.reason,rolledBack:T.rolledBack}:(r.pop(),n.push(k),m(),{ok:!0,operationId:k.operationId,kind:k.plan.kind,target:k.plan.target,resultVersion:Math.max(...T.snapshots.map(O=>O.version)),affectedFiles:k.postSnapshots.map(O=>O.file)})}function m(){for(;n.length>i;)n.shift();for(;n.length>0&&d()>s;)n.shift()}function d(){return n.reduce((k,T)=>k+g(T),0)}function g(k){return h(k.preSnapshots)+h(k.postSnapshots)}function h(k){return k.reduce((T,O)=>T+O.file.length+O.content.length,0)}async function E(k,T){let O=[];for(let L of T){let G=L.capability??"write-text",ne=o.find(Y=>Y.sourceType===L.sourceType&&(L.adapterId===void 0||Y.adapterId===L.adapterId)&&(Y.capabilities===void 0||Y.capabilities.includes(G)));if(!ne)return{ok:!1,operationId:k.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${L.sourceType}`,rolledBack:!1};let ve=await ne.execute(L);if(!ve.ok)return{ok:!1,operationId:k.operationId,errorCode:"writeback-failed",reason:ve.reason??`External adapter failed for ${L.sourceType}`,rolledBack:!1};O.push(L.file)}return{ok:!0,operationId:k.operationId,kind:k.kind,target:k.target,resultVersion:0,affectedFiles:O}}function S(k,T){if(k.conflictPolicy!=="compare-and-swap")return null;let O=new Map(T.map(L=>[L.file,L]));for(let L of k.edits){if(L.operation==="create-only")continue;if(L.baseContentHash===void 0)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};let G=O.get(L.file),ne=L.baseContentHash;if(ne===null){if(G?.exists!==!1)return{file:L.file,reason:`Source file ${L.file} was created or changed before save.`};continue}if(!ne)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};if(G?.exists===!1||G?.sha256!==ne)return{file:L.file,reason:`Source file ${L.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function v(k){let T=[];for(let O of k)T.push(await C(O));return T}async function C(k){if(!await e.exists(k))return{file:k,content:"",version:0,exists:!1};let O=Math.max(1,e.getVersion(k)),L=await e.readFile(k);return{file:k,content:L,version:O,exists:!0,sha256:be(L)}}async function N(k,T,O=new Set){let L=[];try{for(let G of k){if(O.has(G.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(G.file,G.content)}else await A(G);let ne=e.bumpVersion(G.file);L.push(G.file),G.version=ne}}catch(G){let ne=await P(T.filter(Y=>L.includes(Y.file)));if(ne.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${ne.failedFiles.join(", ")}: ${Hm(G)}`,rolledBack:!1,instanceConflict:zm(G)};let ve=zm(G);return{ok:!1,reason:`${ve?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Hm(G)}`,rolledBack:!0,instanceConflict:ve}}return{ok:!0,snapshots:k.map(CC)}}async function A(k){if(k.exists===!1){await e.deleteFile(k.file);return}await e.writeFile(k.file,k.content)}async function P(k){let T=[];for(let O of k)try{await A(O),e.bumpVersion(O.file)}catch{T.push(O.file)}return T.length===0?{ok:!0}:{ok:!1,failedFiles:T}}}function zm(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function CC(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:be(e.content)}:{}}}function Hm(e){return e instanceof Error?e.message:String(e)}function Wm(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 ze(Vn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return ze(Un({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return ze(Ln({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return ze(Bn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return ze(Do({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return ze(vr({source:t,locator:e.locator,next:e.value}));case"update-array-item":return ze(vr({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return ze(Uo({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return ze(Bo({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return ze(Ko({source:t,locator:e.locator,index:e.index}));case"move-array-item":return ze(Jo({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return ze(jn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return ze(jo({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 RC(e,t);case"set-property-changes":return ze($o({source:t,locator:e.locator,changes:e.changes}));case"set-property-binding":return ze(Vo({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return ze(zo({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function RC(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!Du(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!==be(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:Mu({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function ze(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 Hi,SiteEditCompositionContextSchema as wC,SiteEditCompositionSelectorSchema as NC}from"@vcp-dev/contracts";var He=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function Ym(e,t){throw new He("INVALID_COMPOSITION",e,{value:t})}function Wi(e){let t=wC.safeParse(e);return t.success?t.data:Ym("Invalid SiteEditCompositionContext.",e)}function Zm(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=Wi(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new He("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=Hi(u);if(n.has(f))throw new He("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:u});let m=r.get(l.entryFile);if(m)throw new He("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:m});let d={context:u,entryFile:l.entryFile,key:f};t.push(d),n.set(f,d),r.set(l.entryFile,f)}if(t.length===0)throw new He("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=Wi(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new He("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let f=Hi(u);if(!n.has(f))throw new He("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:f});if(o.has(f))throw new He("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:f});o.set(f,l.version)}function i(l){let u=NC.safeParse(l);if(!u.success)return Ym("Invalid SiteEditCompositionSelector.",l);let f=t.filter(({context:m})=>m.routeId===u.data.routeId&&(u.data.templateId===void 0?m.effectiveTemplateId===void 0:m.effectiveTemplateId===u.data.templateId));if(f.length===1)return f[0];throw f.length>1?new He("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new He("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=Wi(l),f=Hi(u),m=n.get(f);if(!m)throw new He("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:f});return m}function a(l){let u=Wi(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new He("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=Hi(u),m=n.get(f);if(m){if(m.entryFile===l.entryFile)return m;throw new He("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:u})}let d=[...n.values()].find(h=>h.entryFile===l.entryFile);if(d)throw new He("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:d.context});let g={context:u,entryFile:l.entryFile,key:f};return t.push(g),n.set(f,g),g}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let f=t.findIndex(m=>m.key===l);return f>=0&&t.splice(f,1),o.delete(l),u}return{entries:t,byKey:n,initialVersions:o,register:a,unregister:c,resolveSelector:i,resolveContext:s,getByKey:l=>n.get(l),routeIds:()=>[...new Set(t.map(({context:l})=>l.routeId))]}}import{composeSiteEditRepeatInstanceKey as PC,stripSiteEditRepeatInstanceKeys as Qm}from"@vcp-dev/contracts";function qm(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Qm(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 AC(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 Gi(e){return e?.map(t=>({...t}))}function Yc(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=Gi(e.collectionPathMap?.[t])??Gi(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:Gi(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Gi(o)??[])}}function eg(e,t,n){let r=new Set;for(let d of t.regions)if(d.kind==="repeat-region")for(let g of d.childKeys)r.add(g);if(r.size===0)return e;let o=new Map(e.entries.map(d=>[d.key,d])),i=[],s=new Map,a=(d,g)=>PC(d,g),c=(d,g,h)=>{let E=o.get(d);if(!E)return a(d,h);let S=a(d,h),v={...E,key:S,parentKey:g,childKeys:[]};return i.push(v),v.childKeys=E.childKeys.flatMap(C=>l(C,h,S)),S},l=(d,g,h)=>{if(!r.has(d))return[c(d,h,g)];let E=f(d,g),S=[];for(let v=0;v<E;v+=1)S.push(c(d,h,[...g,v]));return S},u=Array.from(new Set([...e.rootKeys,...e.entries.filter(d=>d.parentKey===null).map(d=>d.key)]));for(let d of u){if(!r.has(d)){c(d,null,[]);continue}let g=f(d,[]);for(let h=0;h<g;h+=1)c(d,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function f(d,g){let h=new Set;for(let E of m(d)){let S=n.get(E);if(S){for(let v of[...S.textTargets.values(),...S.elementPropertyTargets.values()])if(!(v?.kind!=="value-binding"||v.sourceKind!=="repeat-template"))for(let C of TC(v))C.length<=g.length||FC(C,g)&&h.add(C[g.length])}}return h.size>0?h.size:AC(n.get(d))}function m(d){let g=s.get(d);if(g)return g;let h=[d],E=o.get(d);for(let S of E?.childKeys??[])h.push(...m(S));return s.set(d,h),h}}function tg(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function ng(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((Qm(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function TC(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 FC(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 rg(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(u=>[u.key,u])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let u=o.get(a);if(!u)break;s.push({key:u.key,tag:u.tag,label:u.label}),a=u.parentKey}s.reverse();let c=i.childKeys.map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label})),l=i.parentKey===null?[]:(o.get(i.parentKey)?.childKeys??[]).filter(u=>u!==i.key).map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label}));return{...e,key:i.key,ancestors:s,children:c,siblings:l}}function og(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(c=>[c.key,c])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let c=o.get(a);if(!c)break;s.push({key:c.key,tag:c.tag,label:c.label}),a=c.parentKey}return s.reverse(),{...e,key:i.key,ancestors:s}}function ig(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function _C(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var co=class extends Error{constructor(t){let n=t.map(ig);super(_C(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function sg(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof co?{routeId:e,message:n,diagnostics:t.diagnostics.map(ig)}:{routeId:e,message:n}}function Zc(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Qc(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function cr(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function ag(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function qc(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 cg(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((l,u)=>l.preDigest===r[u]),i=t.files.every((l,u)=>l.postDigest===r[u]),s=t.historyTransition,a=n.digest===s.expectedIndexDigest,c=n.digest===s.publishedIndexDigest&&n.cursor===s.publishedCursor&&n.currentId===s.publishedCurrentId;return o&&a?"safely-uncommitted":i&&c?"durably-committed":"ambiguous"}var VC=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,UC=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],lg=32,ug=256;function KC(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var dg={maxEntries:50,maxBytes:8*1024*1024};function JC(){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 Wo(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}}}function XC(){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>dg.maxEntries||zC(e)>dg.maxBytes;)e.shift()}}function zC(e){return e.reduce((t,n)=>t+HC(n),0)}function HC(e){return fg(e.preSnapshots)+fg(e.postSnapshots)+WC(e.provenance)}function WC(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function fg(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function pg(e,t){return{key:MC(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document:null,pageComposition:null,pageCompositionProjection:null,documentIndex:null,pagePlacementByKey:null,pagePlacementUnitByKey:null,pageUnitByKey:null,pagePlacementsByUnitKey:null,dependencyFiles:new Set([t]),detailProjections:null,fileVersions:new Map,styleContext:null}}var Zi=class extends Error{constructor(t){super(t.reason),this.result=t}},Fn=class extends Error{constructor(t){super(Zc(t)),this.failedRoutes=t}};function mg(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=yt(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(yt(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function GC(e,t,n){if(!n)return;let r=yt(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 YC=/\.(?:[cm]?[jt]sx?)$/i,ZC=/\.json$/i,QC=/\.(?:css|scss|sass)$/i,qC=/\.mdx$/i,eR=/\.ya?ml$/i;function tR(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 nR(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function rR(e,t){let n=new Map;for(let r of t)n.set(r.path,r.operation==="delete"?{exists:!1}:{exists:!0,content:r.content});return{async readFile(r){let o=n.get(r);if(o){if(!o.exists)throw new Error(`Source file not found: ${r}`);return o.content}return e.readFile(r)},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(r){let o=n.get(r);return o?o.exists:e.exists(r)},async getFileInfo(r){let o=n.get(r);return o?o.exists?{path:r,sizeBytes:Buffer.byteLength(o.content,"utf8")}:null:e.getFileInfo?.(r)??null},async listFiles(r={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let o=bg(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(oR(a,r.roots??[])){if(!c.exists){i.delete(a);continue}i.set(a,{path:a,sizeBytes:Buffer.byteLength(c.content,"utf8")})}let s=[...i.values()].sort((a,c)=>a.path.localeCompare(c.path));return o.truncated?{files:s,truncated:o.truncated}:s},getVersion(r){return e.getVersion(r)},bumpVersion(r){return e.getVersion(r)}}}function oR(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function bg(e){return Array.isArray(e)?{files:e}:e}function iR(e){if(!LC(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!==jC||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=DC(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(YC.test(e.path)){let t=Rt({source:e.content,profile:pn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(ZC.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Ge(t)}`,details:{path:e.path}}}if(QC.test(e.path)){let t=gg({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(qC.test(e.path)){let t=gg({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(eR.test(e.path))try{$C(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Ge(t)}`,details:{path:e.path}}}return{ok:!0}}function gg({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let f=0;f<e.length;f+=1){let m=e[f]??"",d=e[f+1]??"";if(n==="mdx"&&l&&e.startsWith("```",f)){c=!c;let g=e.indexOf(`
8
8
  `,f);if(g===-1){l=!0;break}f=g,l=!0;continue}if(c){l=m===`
9
9
  `||m==="\r";continue}if(s){m==="*"&&d==="/"&&(s=!1,f+=1),l=m===`
10
10
  `||m==="\r";continue}if(a){m===`
11
11
  `||m==="\r"?(a=!1,l=!0):l=!1;continue}if(o){if(i)i=!1;else if(m==="\\")i=!0;else if(m===o)o=null;else if(n==="css"&&(m===`
12
12
  `||m==="\r"))return lr(t,`Unterminated string literal in ${t}.`);l=m===`
13
13
  `||m==="\r";continue}if(m==="/"&&d==="*"){s=!0,f+=1,l=!1;continue}if(n==="mdx"&&m==="/"&&d==="/"){a=!0,f+=1,l=!1;continue}if(m==="'"||m==='"'||n==="mdx"&&m==="`"){o=m,l=!1;continue}if(m==="{"||m==="("||m==="["){r.push({char:m,offset:f}),l=!1;continue}if(m==="}"||m===")"||m==="]"){let g=m==="}"?"{":m===")"?"(":"[",h=r.pop();if(!h||h.char!==g)return lr(t,`Unexpected closing token "${m}" in ${t}.`);l=!1;continue}l=m===`
14
- `||m==="\r"}if(s)return lr(t,`Unterminated block comment in ${t}.`);if(o)return lr(t,`Unterminated string literal in ${t}.`);if(c)return lr(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?lr(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function lr(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function uo(e){let t="idle",n=e.fileSystem??IC(),r=Nu(),o=Vm({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Xu(e.historyStore):kC()),u=jm(n,{externalAdapters:e.externalAdapters}),f=new Map,m=new Set,d=0,g=e.historyStore?.recoveryRequired??!1,h=Vc(),E=w();function S(p){return(Hi.isAbsolute(p)?Hi.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function v(p,y){let x=Hi.posix.dirname(p),I=y.replace(/\.(?:tsx?|jsx?)$/i,""),N=Hi.posix.relative(x,I);return N.startsWith(".")?N:`./${N}`}function C(p,y){return p.startLine===y.startLine&&p.startColumn===y.startColumn&&p.endLine===y.endLine&&p.endColumn===y.endColumn}async function w(){let p=e.historyStore;if(p)try{let y=await p.readTransactionJournal();if(!y)return;let x=await p.readIndex(),I=await Promise.all(y.files.map(async O=>await n.exists(O.path)?be(await n.readFile(O.path)):null));if(Qm({journal:y,index:x,observedFileDigests:I})!=="ambiguous"){await p.clearTransactionJournal(y.transactionId);let O=await p.readStatus();O.recoveryRequired||(await p.cleanupTmp(),O=await p.readStatus()),g=O.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${y.transactionId} at phase ${y.phase}`),g=!0}catch(y){g=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${Ge(y)}`).catch(()=>{})}}function A(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let y=rg(p.context,p.entryFile);i.set(p.key,y),P(y,y.dependencyFiles)}function P(p,y){let x=new Set(y);k(p),p.dependencyFiles=x;for(let I of p.dependencyFiles){let N=s.get(I);N||(N=new Set,s.set(I,N)),N.add(p.key)}}function k(p){for(let y of p.dependencyFiles){let x=s.get(y);x&&(x.delete(p.key),x.size===0&&s.delete(y))}p.dependencyFiles.clear()}function T(p){let y=new Set;for(let x of p)for(let I of s.get(x)??[])y.add(I);return y}function _(p){for(let y of p)if(!s.has(y))return!1;return!0}async function L(p,y,x,I,N){let O=new Map,M=im(N.values()),B=new Map,D=typeof n.exists=="function"?U=>n.exists(U):async()=>!1;for(let[U,W]of p.elements){let ye=y.nodes.get(U);if(!ye)continue;let ae=x.get(W.sourceFile)??I.get(W.sourceFile),Ie=new Map,we=new Map,Ne=new Map,Ce=[];for(let xe of W.textSegments){if(!ae){Ie.set(xe.index,null);continue}let fr=await sm({file:W.sourceFile,source:ae,segment:xe,readFile:et=>n.readFile(et),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:et,adapterId:un,capabilities:hs})=>({sourceType:et,adapterId:un,capabilities:hs})),functionCallContracts:e.functionCallContracts,fileCache:M}),We=await Tc({file:W.sourceFile,source:ae,target:{kind:"text-segment",segment:xe},readFile:et=>n.readFile(et),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:et,adapterId:un,capabilities:hs})=>({sourceType:et,adapterId:un,capabilities:hs})),functionCallContracts:e.functionCallContracts,fileCache:M}),ut=OC(fr);Ie.set(xe.index,ut),we.set(xe.index,fr),Ne.set(xe.index,We),Ce.push({editable:xe.editable,source:ut})}let F=new Map,K=new Map;if(ae)for(let xe of W.attributes??[]){let fr=await ar({file:W.sourceFile,source:ae,sourceRange:xe.sourceRange,expression:xe.source?.expression??xe.value,sourceInfo:xe.source,readFile:ut=>n.readFile(ut),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ut,adapterId:et,capabilities:un})=>({sourceType:ut,adapterId:et,capabilities:un})),functionCallContracts:e.functionCallContracts,fileCache:M}),We=await mm({element:W,file:W.sourceFile,source:ae,propertyName:xe.name,readFile:ut=>n.readFile(ut),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ut,adapterId:et,capabilities:un})=>({sourceType:ut,adapterId:et,capabilities:un})),functionCallContracts:e.functionCallContracts,fileCache:M});K.set(xe.name,We),F.set(xe.name,fr)}let ee=Cm(MC(ye.writeTarget),Ce),re=gm({key:U,element:W,graph:p,provenances:Ne}),Fe=Am(W),ct=ae?await lp({element:W,graph:p,file:W.sourceFile,source:ae,readFile:xe=>n.readFile(xe),exists:D,fileCache:B}):void 0,lt=p.regions.find(xe=>xe.kind==="conditional-region"&&xe.childKeys.includes(U)),dr,Je=lt?.sourceCandidates?.[0];if(ae&&lt&&Je?.kind==="conditional-branch"){let xe=await Tc({file:W.sourceFile,source:ae,target:{kind:"conditional-branch",candidate:Je},readFile:We=>n.readFile(We),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:We,adapterId:ut,capabilities:et})=>({sourceType:We,adapterId:ut,capabilities:et})),functionCallContracts:e.functionCallContracts,fileCache:M});dr={currentBranch:lt.childKeys.indexOf(U)<=0?"then":"else",availableBranches:lt.childKeys.length>1?["then","else"]:["then"],conditionExpression:Je.conditionExpression,provenance:{finalSource:xe.finalSource?{kind:xe.finalSource.kind,file:xe.finalSource.file,displayPath:xe.finalSource.displayPath}:null,chain:xe.chain.map(We=>({kind:We.kind,file:We.file,displayName:We.displayName,canEditHere:We.canEditHere})),confidence:xe.confidence,editMode:xe.editMode,diagnostics:xe.diagnostics.map(We=>({code:We.code,message:We.message}))}}}O.set(U,{textSources:Ie,textTargets:we,elementPropertyTargets:F,propertyProvenances:K,isRepeat:YC(U,p),provenances:Ne,writeTarget:ee,componentSemantic:re,styleSource:Fe,conditional:dr,dynamicData:ct})}return O}function G(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function ne(p,y){let x=o.initialVersions.get(p.key)??0;for(let I of y.values())x=Math.max(x,I);return Math.max(x,p.graph?.version??0)}function ve(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function Y(p){try{return ve(o.resolveSelector(p.composition).key)}catch{return 0}}async function ue(p,y,x={}){let I=i.get(p);if(!I)return null;let N=x.sourceCache??Jc(f,[]),O=await Ae(I.entryFile),{graph:M,allSources:B,diagnostics:D,parsedModules:U,entryModule:W}=await ju(I.entryFile,y,Je=>n.readFile(Je),typeof n.exists=="function"?Je=>n.exists(Je):async()=>!1,{additionalEntries:O,version:I.graph?.version??1});if(D.length>0)throw new co(D);let ye=new Map;for(let Je of B.keys())ye.set(Je,G(Je));let ae=Math.max(ne(I,ye),x.minimumVersion??0);x.changed&&ae<=(I.graph?.version??0)&&(ae=(I.graph?.version??0)+1),M.version=ae;for(let[Je,xe]of B)Xc(N,Je,xe,eg);let Ie=await zt(I.composition,I.entryFile,B,N);M.routeId=I.routeId,M.composition=I.composition;let we=Tm(M),Ne=Iu(we,M),Ce=await L(M,we,B,N,U),F=Ug(M,Ne,Ce),K=Vg(Ce),ee=Jm(Sm(M,we,Ne,{canUpdateTextByKey:F,dynamicDataSummaryByKey:K}),M,Ce),re=Nd({route:I.routeId,composition:I.composition,entryFile:I.entryFile,version:ae,source:y,ast:W?.ast}),Fe=Pd(re);re.ok&&$C(ee,M,re.projection);let ct={...ee,composition:I.composition,...Ie?{styleContext:Ie}:{},pageComposition:Fe},lt=new Set([I.entryFile,...B.keys()]);if(Ie){lt.add(Ie.entryCss.path);for(let Je of Ie.stylesheets)lt.add(Je.path)}let dr={...I,dependencyFiles:lt,graph:M,topology:we,capabilities:Ne,document:ct,pageComposition:Fe,pageCompositionProjection:re.projection,pagePlacementByKey:re.ok?re.projection.placementByKey:null,pagePlacementUnitByKey:re.ok?re.projection.placementUnitByKey:null,pageUnitByKey:re.ok?re.projection.unitByKey:null,pagePlacementsByUnitKey:re.ok?re.projection.placementsByUnitKey:null,documentIndex:Km(ct),detailProjections:Ce,fileVersions:ye,styleContext:Ie};if(x.publish===!1)return dr;cr(f,N);for(let Je of N.keys())m.delete(Je);return P(I,lt),Object.assign(I,dr),I}async function Ae(p){let y=[];for(let x of JC(p))typeof n.exists=="function"&&await n.exists(x)&&y.push({file:x,source:await n.readFile(x)});return y}async function zt(p,y,x,I){let N=[];for(let[U,W]of x){if(Hc(U)){N.push(U);continue}for(let ye of zC(W)){let ae=cg(U,ye);ae&&N.push(ae)}}if(!N.length){for(let U of XC(y))if(await kl(U)){N.push(U);break}}let O=new Map,M=GC(N).slice(0,qm);for(;M.length>0&&O.size<qm;){let U=M.shift();if(O.has(U)||!Hc(U))continue;let W=await Ht(U,I);if(W!==null){O.set(U,{path:U,content:W});for(let ye of HC(W)){let ae=cg(U,ye);ae&&!O.has(ae)&&!M.includes(ae)&&M.push(ae)}}}let B=[...O.values()].map(U=>({...U,hash:be(U.content)})),D=B[0];return D?{composition:p,revision:be(JSON.stringify(B.map(({path:U,hash:W})=>({path:U,hash:W})))),entryCss:D,stylesheets:B.slice(1)}:null}async function Ht(p,y){let x=y.get(p);if(x!==void 0)return x;if(!await kl(p))return null;let I=await n.readFile(p);return Xc(y,p,I,eg),I}async function kl(p){return typeof n.exists=="function"?n.exists(p):!1}function Vg(p){let y=new Map;for(let[x,I]of p)I.dynamicData?.bindings.length&&y.set(x,Sp(I.dynamicData.bindings));return y}function Ug(p,y,x){let I=new Map;for(let[N,O]of p.elements){if(!y.get(N)?.canUpdateText){I.set(N,!1);continue}let B=x.get(N),D=O.textSegments.some(U=>{if(!U.editable)return!1;let W=B?.provenances.get(U.index)??null;return!W||Kg(W)});I.set(N,D)}return I}function Kg(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function So(p,y={}){let x=[...new Set(p)],I=y.affectedCompositionKeys!==void 0,N=I?new Set(y.affectedCompositionKeys):T(x);if(!I&&(N.size===0||!_(x)))for(let D of i.values())Cl(D,x)&&N.add(D.key);let O=!I&&N.size===0&&x.some(ag),M=y.publish===!1?Jc(f,x):void 0,B={rebuiltRoutes:[],failedRoutes:[],...y.publish===!1?{candidateRouteStates:[],candidateSourceCache:M}:{}};for(let D of i.values())if(!(y.excludedCompositionKeys?.has(D.key)||!(N.has(D.key)||O)))try{let W=!!D.graph,ye=await n.readFile(D.entryFile),ae=await ue(D.key,ye,{...y,...M?{sourceCache:M}:{}});ae?.graph&&(B.rebuiltRoutes.push({documentChanged:W,composition:D.composition,routeId:D.routeId,version:ae.graph.version}),B.candidateRouteStates?.push({composition:D.composition,key:D.key,routeId:D.routeId,state:ae}))}catch(W){B.failedRoutes.push({...Ym(D.routeId,W),composition:D.composition})}return B}function On(p){let y=[...new Set(p)],x=T(y);if(x.size>0&&_(y))return[...x];for(let I of i.values())Cl(I,y)&&x.add(I.key);return[...x]}function Jg(p){let y=new Set(On(p));return o.entries.filter(x=>y.has(x.key)).map(x=>x.context)}function Xg(p){return[...new Set(On(p))].sort((x,I)=>x<I?-1:x>I?1:0).map(x=>o.getByKey(x)?.context).filter(x=>x!==void 0)}function zg(p,y){let x=new Set(On(y)),I=p.provenance?.affectedCompositions??[];if(I.length===0)return x;if([...new Set(I.map(O=>o.resolveContext(O).key))].some(O=>!x.has(O)))throw new Error("History provenance does not match the affected composition index.");return x}function Hg(p,y){let x=p.composition??p.provenance?.initiatingComposition;if(x){let O=o.resolveContext(x);return{context:O.context,key:O.key}}let I=[...new Set(On(y))];if(I.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${I.length}).`);let N=o.getByKey(I[0]);if(!N)throw new Error("Legacy history entry references an unknown affected composition.");return{context:N.context,key:N.key}}function us(p,y){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:x,version:I}of y.rebuiltRoutes)r.emit({type:"document-changed",composition:x,version:I});for(let{composition:x,message:I}of y.failedRoutes)r.emit({type:"graph-error",composition:x,message:I})}function Cl(p,y){return y.some(x=>p.dependencyFiles.has(x)||p.entryFile===x||p.graph?.fileIndex.has(x))}function Rl(p){for(let y of p)a.add(y);c||A()||(c=(async()=>{t="building";let y=!1;try{for(;a.size>0;){if(A())return;await Wg();let x=[...a];a.clear();let I=await wl(x);if(I.length===0)continue;let N=On(I);for(let B of N){let D=i.get(B)?.composition;D&&r.emit({type:"graph-invalidated",composition:D})}let{rebuiltRoutes:O,failedRoutes:M}=await So(I,{changed:!0});for(let{documentChanged:B,composition:D,version:U}of O)r.emit({type:"graph-ready",composition:D,version:U}),B&&r.emit({type:"document-changed",composition:D,version:U});for(let{composition:B,message:D}of M)y=!0,r.emit({type:"graph-error",composition:B,message:D})}}finally{c=null,t!=="disposed"&&(t=!y&&[...i.values()].some(x=>x.graph)?"ready":"idle"),a.size>0&&Rl([])}})())}async function Wg(){for(;d>0;)await new Promise(p=>setTimeout(p,0))}async function wl(p){let y=[];for(let x of new Set(p)){let I=f.get(x);if(I===void 0){if(m.has(x)&&!await n.exists(x))continue;m.delete(x),y.push(x);continue}try{await n.readFile(x)!==I&&(m.delete(x),y.push(x))}catch(N){if(!jC(N))try{if(await n.exists(x))continue}catch{continue}m.add(x),y.push(x)}}return y}function Nl(p){Zm(f,p);for(let y of p)y.exists===!1?m.add(y.file):m.delete(y.file)}function Pl(p){m.clear();for(let y of p)m.add(y)}async function Al(p){let y=await wl(p);if(y.length===0)return;let x=On(y);for(let O of x){let M=i.get(O)?.composition;M&&r.emit({type:"graph-invalidated",composition:M})}let{rebuiltRoutes:I,failedRoutes:N}=await So(y,{changed:!0});for(let{documentChanged:O,composition:M,version:B}of I)r.emit({type:"graph-ready",composition:M,version:B}),O&&r.emit({type:"document-changed",composition:M,version:B});for(let{composition:O,message:M}of N)r.emit({type:"graph-error",composition:O,message:M})}async function Gg(p,y){let x=ur(p,y);if(!x?.graph)return;let I=yt(p)??p,N=x.graph.elements.get(I);N&&await Al([N.sourceFile])}async function Tl(p){let y=new Set;if(p.target.kind==="node"){let x=ur(p.target.key,p.composition),I=yt(p.target.key)??p.target.key,N=x?.graph?.elements.get(I);N&&y.add(N.sourceFile)}else if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&y.add(x.entryFile)}else if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&y.add(x.entryFile)}else if(p.target.kind==="source-file")y.add(p.target.path);else if(p.target.kind==="source-batch")for(let x of p.target.paths)y.add(x);await Al(y)}async function Yg(p){if(p.params.kind!=="source-edit")return ds(p,"invalid-params","source-edit requires source-edit params");for(let y of p.params.edits){let x=BC(y);if(!x.ok)return ds(p,x.errorCode,x.message,x.details)}d+=1;try{let y=await th(p.params.edits);if(!y.ok)return ds(p,y.errorCode,y.message,y.details);await Tl(p);let x={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(I=>I.operation==="delete"?{operation:"delete",file:I.path,baseContentHash:I.baseContentHash??null}:{operation:"upsert",file:I.path,baseContentHash:I.baseContentHash??null,content:I.content})};return await Dn({request:p,filePlan:x})}catch(y){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Y(p),error:{code:j.INTERNAL_ERROR,message:Ge(y)}}}finally{d-=1}}async function Zg(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return se(p,j.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");d+=1;try{let y=await Ws({files:[...p.params.artifact.components.flatMap(I=>I.materialization.files.map(N=>({path:N.pathTemplate,content:N.content}))),...p.params.artifact.pages.flatMap(I=>I.materialization.files.map(N=>({path:N.pathTemplate,content:N.content})))],exists:I=>n.exists(I),readFile:I=>n.readFile(I)});if(!y.ok)return se(p,j.MATERIALIZATION_REJECTED,y.message);let x=await ea({artifact:p.params.artifact,exists:I=>n.exists(I)});return x.ok?await Dn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"overwrite",edits:x.files},output:{kind:"insert-page-resource",package_instance_id:x.packageInstanceId,pages:x.pages},historyPolicy:"none"}):se(p,x.code==="MATERIALIZATION_CONFLICT"?j.MATERIALIZATION_CONFLICT:j.MATERIALIZATION_REJECTED,x.message,x.path?{path:x.path}:void 0)}catch(y){return se(p,j.INTERNAL_ERROR,Ge(y))}finally{d-=1}}async function Qg(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return se(p,j.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return se(p,j.PLAN_FAILED,"Complete project file listing is required for page deletion.");d+=1;try{let y=lg(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(y.truncated)return se(p,j.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:y.truncated.reasons});let x=y.files.filter(({path:M})=>/\.(?:tsx?|jsx?)$/.test(M)),I=Object.fromEntries(await Promise.all(x.map(async({path:M})=>[M,await n.readFile(M)]))),N=Yd({expectedUrlPath:p.params.expectedUrlPath,files:I});if(!N.ok)return se(p,N.code==="HOME_PAGE_LOCKED"?j.HOME_PAGE_LOCKED:N.code==="ROUTE_NOT_FOUND"?j.ROUTE_NOT_FOUND:j.PLAN_FAILED,N.message);let O=await Promise.all(N.edits.map(async M=>({...M,baseContentHash:be(await n.readFile(M.file))})));return Dn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:O},output:{kind:"delete-page-source",deleted_files:N.deletedFiles,updated_files:N.updatedFiles,preserved_shared_files:N.preservedSharedFiles,warnings:N.warnings},historyPolicy:"none"})}catch(y){return se(p,j.INTERNAL_ERROR,Ge(y))}finally{d-=1}}async function qg(p,y){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return se(p,j.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(p.params.kind!=="insert-child"&&p.params.kind!=="replace-node"||p.kind!==p.params.kind)return se(p,j.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(p.params.kind==="insert-child"){if(!("kind"in p.params.position)||p.params.position.kind!=="page-composition")return se(p,j.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return se(p,j.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let x=y.document,I=y.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return se(p,j.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return se(p,j.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let N=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!N)return se(p,j.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let O=p.params.kind==="insert-child"?p.params.position:null,M=await Ws({files:N.files.map(D=>({path:D.pathTemplate,content:D.content})),exists:D=>n.exists(D),readFile:D=>n.readFile(D)});if(!M.ok)return se(p,j.MATERIALIZATION_REJECTED,M.message);let B=await fd({manifest:N,generatedRoot:"components/site/generated",controlledFiles:N.files.map(D=>({pathTemplate:D.pathTemplate})),exists:D=>n.exists(D),commit:async D=>{let U=await n.readFile(y.entryFile),W=y.document,ye=y.pageCompositionProjection;if(!W||W.pageComposition?.status!=="supported"||W.version!==p.documentVersion||!ye||ye.status!=="supported"||ye.documentVersion!==W.version)return{ok:!0,data:se(p,j.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let ae=D.entry.path,Ie=ch(D.instanceName),we,Ne=[];if(p.params.kind==="insert-child"){if(!O||!("kind"in O)||O.kind!=="page-composition")return{ok:!0,data:se(p,j.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let ee=aa({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:W.version,expectedDocumentVersion:p.documentVersion,source:U,projection:ye,placementKey:O.placementKey,component:{source:ae,exportName:D.entry.export.kind==="default"?"default":D.entry.export.name,localName:Ie}});if(!ee.ok)return{ok:!0,data:se(p,gs(ee.error.code),ee.error.message,{diagnostics:ee.error.diagnostics})};let re=ee.plan.rewriteStep,Fe;switch(re.kind){case"insert-root-expression":Fe=si({source:U,locator:re.locator,expectedSourceHash:re.sourceHash,action:{kind:"insert",jsx:re.node.jsx,placement:re.placement,replaceOriginal:re.replaceOriginal}});break;case"insert-child":Fe=Bn({source:U,locator:re.parentLocator,node:re.node,placement:re.placement,...re.anchorLocator?{anchorLocator:re.anchorLocator}:{}});break;default:Fe={ok:!1,source:U,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(re)}`}}}if(!Fe.ok)return{ok:!0,data:se(p,j.AST_PARSE_ERROR,Fe.diagnostic.message)};we=Fe.source}else{let ee=ca({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:W.version,expectedDocumentVersion:p.documentVersion,source:U,projection:ye,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!ee.ok)return{ok:!0,data:se(p,gs(ee.error.code),ee.error.message,{diagnostics:ee.error.diagnostics})};let re=ee.plan.rewriteStep,Fe;switch(re.kind){case"replace-root-expression":Fe=si({source:U,locator:re.locator,expectedSourceHash:re.sourceHash,action:{kind:"replace",jsx:`<${Ie} />`}});break;case"replace-node":Fe=_o({source:U,locator:re.locator,node:{jsx:`<${Ie} />`}});break;default:Fe={ok:!1,source:U,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${re.kind}`}}}if(!Fe.ok)return{ok:!0,data:se(p,j.AST_PARSE_ERROR,Fe.diagnostic.message)};let ct=await Fl({routeState:y,placementUnitKey:p.target.placementUnitKey,source:U,mutatedSource:Fe.source});we=ct.source,Ne=await Promise.all(ct.files.map(async lt=>({operation:"delete",file:lt,baseContentHash:be(await n.readFile(lt))})))}let Ce=Vn({source:we,moduleSpecifier:v(y.entryFile,ae),imports:D.entry.export.kind==="default"?[{kind:"default",local:Ie}]:[{kind:"named",imported:D.entry.export.name,local:Ie}]});if(!Ce.ok)return{ok:!0,data:se(p,j.AST_PARSE_ERROR,Ce.diagnostic.message)};let F=D.files.map(ee=>({operation:"create-only",file:ee.path,content:ee.content})),K=[{operation:"upsert",file:y.entryFile,content:Ce.source,baseContentHash:be(U)},...F,...Ne];d+=1;try{let ee=await Dn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:K}});return!ee.ok&&ee.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:ee.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:ee}}finally{d-=1}}});return B.ok?B.data:se(p,j.VERSION_STALE,B.error.message,{materializationCode:B.error.code})}async function eh(p,y){if(p.kind!=="move-node"&&p.kind!=="remove-node")return se(p,j.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let x=y.document,I=y.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return se(p,j.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return se(p,j.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let N=await n.readFile(y.entryFile),O=ca({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:x.version,expectedDocumentVersion:p.documentVersion,source:N,projection:I,placementUnitKey:p.target.placementUnitKey,operation:p.kind,targetPlacement:p.kind==="move-node"&&p.params.kind==="move-node"&&"kind"in p.params.target&&p.params.target.kind==="page-composition"?p.params.target:void 0});if(!O.ok)return se(p,gs(O.error.code),O.error.message,{diagnostics:O.error.diagnostics});let M=O.plan.rewriteStep,B;switch(M.kind){case"move-node":B=jn({source:N,locator:M.locator,targetParentLocator:M.targetParentLocator,placement:M.placement,...M.anchorLocator?{anchorLocator:M.anchorLocator}:{}});break;case"remove-node":B=Ln({source:N,locator:M.locator});break;case"remove-root-expression":B=si({source:N,locator:M.locator,expectedSourceHash:M.sourceHash,action:{kind:"remove"}});break;default:B={ok:!1,source:N,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${M.kind}`}}}if(!B.ok)return se(p,j.AST_PARSE_ERROR,B.diagnostic.message);let D=B.source,U=[];if(p.kind==="remove-node"){let ye=await Fl({routeState:y,placementUnitKey:p.target.placementUnitKey,source:N,mutatedSource:D});D=ye.source,U=await Promise.all(ye.files.map(async ae=>({operation:"delete",file:ae,baseContentHash:be(await n.readFile(ae))})))}let W=[{operation:"upsert",file:y.entryFile,content:D,baseContentHash:be(N)},...U];d+=1;try{return await Dn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:W}})}finally{d-=1}}async function Fl(p){let y={source:p.mutatedSource,files:[]},x=p.routeState.graph,I=p.routeState.pageCompositionProjection;if(!x||!I||I.status!=="supported"||!n.listFiles)return y;let O=I.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!O)return y;let M=[...x.elements.values()].find(F=>F.sourceFile===p.routeState.entryFile&&F.importedFrom&&C(F.sourceRange,O));if(!M?.importedFrom||!M.exportName)return y;let B=S(M.importedFrom),D="components/site/generated/";if(!B.startsWith(D))return y;let U=B.slice(D.length).split("/")[0];if(!U||!/-[0-9a-f]{8}$/i.test(U))return y;let W=`${D}${U}`;if([...x.elements.values()].filter(F=>F.sourceFile===p.routeState.entryFile&&S(F.importedFrom??"")===B).length!==1)return y;let ae=await n.listFiles({maxFiles:5e3,maxDepth:32}),Ie=Array.isArray(ae)?ae:ae.files;if(!Array.isArray(ae)&&ae.truncated)return y;let we=Ie.map(({path:F})=>F).filter(F=>F===W||F.startsWith(`${W}/`));if(we.length===0||!we.includes(B))return y;for(let{path:F}of Ie)if(!(F===p.routeState.entryFile||F===W||F.startsWith(`${W}/`)))try{if((await n.readFile(F)).includes(U))return y}catch{return y}let Ne=v(p.routeState.entryFile,B),Ce=Un({source:p.mutatedSource,moduleSpecifier:Ne,imports:M.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:M.exportName}]});return Ce.ok?{source:Ce.source,files:we.sort((F,K)=>F.localeCompare(K))}:y}async function th(p){if(n.getFileInfo){for(let N of p)if(await n.exists(N.path)&&await n.getFileInfo(N.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${N.path}`,details:{path:N.path}}}let y=nh(p);if(y.length===0)return{ok:!0};let x=DC(n,p),I=uo({projectRoot:e.projectRoot,fileSystem:x,compositions:[...i.values()].map(N=>({context:N.composition,entryFile:N.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let N of y){let O=i.get(N)?.composition;if(!O)continue;let M={routeId:O.routeId,...O.effectiveTemplateId!==void 0?{templateId:O.effectiveTemplateId}:{}};await I.initializeComposition(M),I.getDocument(M)}}catch(N){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Ge(N)}`,details:{compositionKeys:y}}}finally{I.dispose()}return{ok:!0}}function nh(p){return p.map(x=>x.path).some(ag)?[...i.keys()]:[]}function ds(p,y,x,I){let N=lo(y);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Y(p),error:{code:N,message:x,...I?{details:I}:{}}}}async function fs(p){let y=[];for(let x of new Set(p))y.push(await rh(x));return y}async function rh(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,G(p)),exists:!1};let x=await n.readFile(p);return{file:p,content:x,version:Math.max(1,G(p)),exists:!0,sha256:be(x)}}async function _l(p,y,x,I){if(!e.historyStore)return null;let N=new Map(y.map(B=>[B.file,B])),O=new Map(x.map(B=>[B.file,B])),M=[...new Set([...N.keys(),...O.keys()])].sort().map(B=>{let D=N.get(B),U=O.get(B);return{path:B,preDigest:D?.exists===!1||!D?null:be(D.content),postDigest:U?.exists===!1||!U?null:be(U.content)}});return{schemaVersion:2,transactionId:`${p}:${I.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:I,files:M}}async function Ol(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Mn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function ps(p,y){let x=[];try{for(let I of p)await Ml(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),x.push(I.file)}catch(I){let N=await oh(y.filter(O=>x.includes(O.file)));return N.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Ge(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${N.failedFiles.join(", ")}: ${Ge(I)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(ih)}}async function Ml(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function oh(p){let y=[];for(let x of p)try{await Ml(x),typeof n.bumpVersion=="function"&&n.bumpVersion(x.file)}catch{y.push(x.file)}return y.length===0?{ok:!0}:{ok:!1,failedFiles:y}}function ih(p){let y=p.exists!==!1;return{file:p.file,content:y?p.content:"",version:p.version,exists:y,...y?{sha256:be(p.content)}:{}}}async function Dn(p){return h.runExclusive(()=>sh(p))}async function sh(p){let y=p.filePlan.edits.map(F=>F.file),x=o.resolveSelector(p.request.composition),I=x.context,N=p.historyPolicy==="none"?void 0:{initiatingComposition:I,affectedCompositions:Xg(y)},O=await fs(y),M=new Map(O.filter(F=>F.exists!==!1).map(F=>[F.file,F.content])),B=Ll(),D=new Map(f),U=new Set(m),W=new Set([...i.values()].filter(F=>p.filePlan.edits.some(K=>K.operation==="delete"&&K.file===F.entryFile)).map(F=>F.key)),ye=p.filePlan.edits.map(F=>F.operation==="delete"?{file:F.file,content:"",version:0,exists:!1}:{file:F.file,content:F.content,version:0,exists:!0,sha256:be(F.content)}),ae={operationId:p.filePlan.operationId,intents:p.filePlan.edits.map(F=>F.operation==="delete"?{kind:"delete",path:F.file}:{kind:F.operation==="create-only"?"create-only":"upsert",path:F.file,content:F.content})},Ie=null,we=!1,Ne=await Ki({overlay:M,exists:F=>n.exists(F),plan:ae,buildCandidate:async({plan:F})=>({plan:F}),prepareHistory:async()=>{let F=p.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(p.request.composition).context,operationId:p.request.id,kind:p.request.kind,target:p.request.target,preSnapshots:O,postSnapshots:ye,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...N?{provenance:N}:{}}),K=F?.historyTransition?F.historyTransition:e.historyStore?vC(await e.historyStore.readIndex()):null;if(e.historyStore&&!K)throw new Error("Durable history did not provide an exact index transition.");return Ie=await _l(p.request.id,O,ye,K),Ie=await Ol(Ie),{history:F,historyTransition:K}},reverify:async()=>{},writeCandidate:async()=>{let F=await u.executeFilePlan(p.filePlan);if(!F.ok)throw new Wi(F);return{postSnapshots:await fs(F.affectedFiles),affectedFiles:F.affectedFiles,internalResultVersion:F.resultVersion}},validateCandidate:async({candidate:F,receipt:K})=>{let ee=await So(K.affectedFiles,{changed:!0,minimumVersion:K.internalResultVersion,publish:!1,excludedCompositionKeys:W});if(ee.failedRoutes.length>0)throw new Fn(ee.failedRoutes);let re=jl(B,ee.candidateRouteStates??[]),Fe=Bl(re,x.key);return{...F,rebuild:ee,routeSnapshots:re,resultVersion:Fe,...og(p.selectionRef,re.map(ct=>ct.state.document))?{selectionRef:og(p.selectionRef,re.map(ct=>ct.state.document))}:{}}},publishCandidate:async({candidate:F,history:K,receipt:ee})=>{K?.history&&(await l.publishPrepared(K.history),we=!0);let re=F.resultVersion??ee.internalResultVersion;return{composition:I,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:re,affectedFiles:ee.affectedFiles,...p.output?{output:p.output}:{},...F.selectionRef?{selectionRef:F.selectionRef}:{}}},swapCandidate:({candidate:F,receipt:K})=>{F.routeSnapshots&&Eo(F.routeSnapshots),F.rebuild?.candidateSourceCache&&cr(f,F.rebuild.candidateSourceCache),Nl(K.postSnapshots)},finalizeCandidate:async()=>{await Mn(Ie);for(let F of W)i.delete(F)},emitCommitted:({candidate:F,published:K})=>{us(K,F.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:F,receipt:K})=>{if(we)throw new Error("history was published before transaction finalization failed");if(K){let ee=await ps(O,K.postSnapshots);if(!ee.ok)throw new Error(ee.reason)}Eo(B),cr(f,D),Pl(U),F?.history&&await l.discardPrepared?.(F.history),await Mn(Ie)}});if(Ne.ok)return Ne.published;if(Ne.stage==="precheck"||Ne.stage==="build")try{await Mn(Ie)}catch(F){let K=await vo(Ge(F));return se(p.request,K,"Unable to clear an uncommitted transaction journal.")}if(Ne.recoveryRequired){let F=await vo(Ne.reason);return se(p.request,F===j.RECOVERY_PERSIST_FAILED?F:j.ROLLBACK_FAILED,Ne.reason)}let Ce=Ne.error;return Ce instanceof Wi?{...se(p.request,lo(Ce.result.errorCode),Ce.result.reason),...Ce.result.affectedFiles?{affectedFiles:Ce.result.affectedFiles}:{}}:Ce instanceof Fn?se(p.request,j.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Kc(Ce.failedRoutes)}`,{failedRoutes:Ce.failedRoutes}):se(p.request,Vl(Ne.stage),Ge(Ce))}async function Dl(p){return h.runExclusive(async()=>{let y=p==="undo"?await l.prepareUndo():await l.prepareRedo();return y?ah(p,y):{composition:o.entries[0].context,requestId:p,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:j.INTERNAL_ERROR,message:p==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function ah(p,y){let x=y.entry,I=p==="undo"?x.preSnapshots:x.postSnapshots,N=p==="undo"?x.postSnapshots:x.preSnapshots,O=I.map(K=>K.file),{context:M,key:B}=Hg(x,O),D=await fs(O),U=new Map(D.filter(K=>K.exists!==!1).map(K=>[K.file,K.content])),W=ve(B),ye=Ll(),ae=new Map(f),Ie=new Set(m),we=null,Ne=!1,Ce,F=await Ki({overlay:U,plan:{operationId:`${p}:${x.operationId}`,intents:I.map(K=>K.exists===!1?{kind:"delete",path:K.file}:{kind:"upsert",path:K.file,content:K.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(we=await _l(`${p}:${x.operationId}`,D,I,y.historyTransition),we=await Ol(we),y),reverify:async()=>{},writeCandidate:async()=>{let K=await ps(I,N);if(!K.ok)throw new Error(K.reason);return{snapshots:K.snapshots}},validateCandidate:async({candidate:K})=>{Ce=zg(x,O);let ee=await So(O,{changed:!0,minimumVersion:W+1,publish:!1,affectedCompositionKeys:Ce});if(ee.failedRoutes.length>0)throw new Fn(ee.failedRoutes);let re=jl(ye,ee.candidateRouteStates??[]),Fe=Bl(re,B);return{...K,rebuild:ee,routeSnapshots:re,resultVersion:Fe}},publishCandidate:async({candidate:K,history:ee})=>{if(!ee)throw new Error("history cursor intent is missing");await l.publishPrepared(ee),Ne=!0;let re=K.resultVersion??W+1;return{composition:M,requestId:p,kind:x.kind,target:x.target,ok:!0,resultVersion:re,affectedFiles:O,...x.output?{output:x.output}:{}}},swapCandidate:({candidate:K,receipt:ee})=>{K.routeSnapshots&&Eo(K.routeSnapshots),K.rebuild?.candidateSourceCache&&cr(f,K.rebuild.candidateSourceCache),Nl(ee.snapshots)},finalizeCandidate:async()=>{await Mn(we)},emitCommitted:({candidate:K,published:ee})=>us(ee,K.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:K,receipt:ee})=>{if(Ne)throw new Error("history cursor was published before transaction finalization failed");if(ee){let re=await ps(N,ee.snapshots);if(!re.ok)throw new Error(re.reason)}Eo(ye),cr(f,ae),Pl(Ie),K&&await l.discardPrepared?.(K),await Mn(we)}});if(F.ok)return F.published;if(F.stage==="precheck"||F.stage==="build")try{await Mn(we)}catch(K){let ee=await vo(Ge(K));return{composition:M,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:W,error:{code:ee,message:"Unable to clear an uncommitted transaction journal."}}}if(F.recoveryRequired){let K=await vo(F.reason);return{composition:M,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:W,affectedFiles:O,error:{code:K===j.RECOVERY_PERSIST_FAILED?K:j.ROLLBACK_FAILED,message:F.reason}}}return{composition:M,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:W,affectedFiles:O,error:{code:F.error instanceof Fn?j.ROUTE_REBUILD_FAILED:Vl(F.stage),message:Ge(F.error),...F.error instanceof Fn?{details:{failedRoutes:F.error.failedRoutes}}:{}}}}function Ll(){return[...i.values()].map(p=>({composition:p.composition,key:p.key,routeId:p.routeId,state:{...p,dependencyFiles:new Set(p.dependencyFiles),fileVersions:new Map(p.fileVersions)}}))}function Bl(p,y){return p.find(I=>I.key===y)?.state.graph?.version??o.initialVersions.get(y)??0}function jl(p,y){let x=new Map(p.map(I=>[I.key,I]));for(let I of y)x.set(I.key,I);return[...x.values()]}function Eo(p){for(let y of i.values())k(y);for(let y of p){let x={...y.state,dependencyFiles:new Set(y.state.dependencyFiles),fileVersions:new Map(y.state.fileVersions)};i.set(y.key,x),P(x,x.dependencyFiles)}}async function ms(p){let y=i.get(p);if(!y)throw new Error(`Composition not found: ${p}`);if(y.graph)return;let x=await n.readFile(y.entryFile);await ue(p,x)}function ur(p,y){let x=i.get(o.resolveSelector(y).key)??null;return!x||!$l(x,p)?null:x}function $l(p,y){if(p.documentIndex?.entriesByKey.has(y)||p.graph?.elements.has(y))return!0;let x=yt(y);return x&&x!==y?p.graph?.elements.has(x)===!0:!1}function se(p,y,x,I){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Y(p),error:{code:y,message:x,...I?{details:I}:{}}}}function Vl(p){return p==="validate"?j.ROUTE_REBUILD_FAILED:p==="publish"?j.HISTORY_COMMIT_FAILED:j.WRITE_IO_ERROR}async function vo(p){if(g=!0,!l.markRecoveryRequired)return j.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),j.RECOVERY_REQUIRED}catch{return j.RECOVERY_PERSIST_FAILED}}function ch(p){let x=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return x?`Prefab${x}`:"GeneratedPrefab"}function gs(p){return p==="VERSION_STALE"?j.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?j.CROSS_PAGE_MOVE_UNSUPPORTED:j.UNSUPPORTED_OPERATION}async function Ul(p){if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await ms(x.key),x):se(p,j.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await ms(x.key),x):se(p,j.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return se(p,j.UNSUPPORTED_OPERATION,`${p.kind} source target execution is not implemented yet.`);let y=i.get(o.resolveSelector(p.composition).key)??null;return y?(y.graph||await ms(y.key),$l(y,p.target.key)?y:se(p,j.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):se(p,j.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),f.clear(),m.clear()},registerComposition(p,y){let x=o.register({context:p,entryFile:y}),I=i.get(x.key);if(I?.entryFile===y)return;I&&k(I);let N=rg(x.context,y);i.set(x.key,N),P(N,N.dependencyFiles),r.emit({type:"graph-invalidated",composition:x.context})},unregisterComposition(p){let y=o.resolveSelector(p),x=i.get(y.key);x&&(k(x),i.delete(y.key),o.unregister(y.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:y.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let y=o.resolveSelector(p),x=i.get(y.key);if(!x)throw new Error(`Composition not registered: ${y.key}`);if(x.graph)t="ready";else{t="building";try{let I=await n.readFile(x.entryFile);await ue(y.key,I),t="ready",r.emit({type:"graph-ready",composition:y.context,version:i.get(y.key)?.graph?.version??0})}catch(I){throw t="idle",r.emit({type:"graph-error",composition:y.context,message:Ge(I)}),I}}},getDocument(p){let y=o.resolveSelector(p),x=i.get(y.key);if(!x)throw new Error(`Composition not registered: ${y.key}`);if(!x.document)throw new Error(`Composition not built: ${y.key}`);return x.document},async getHistoryStatus(){await E;let p=await l.getStatus?.();return p?{...p,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(p,y,x){let I=ur(p,y),N=yt(p)??p;if(I?.graph&&I.topology&&I.capabilities&&I.detailProjections){let O=I.detailProjections.get(N);if(O){let M=I.graph.elements.get(N);if(!M)throw new Error(`Key not found: ${p}`);let B=NC(p,N,x),D=new Map;if(O.isRepeat&&B?.instanceIndex!==void 0)for(let ye of M.attributes??[])D.set(ye.name,hc({file:M.sourceFile,source:f.get(M.sourceFile)??"",element:M,propertyName:ye.name,selectionRef:B,graph:I.graph,sources:f}));let U=bm({element:M,graph:I.graph,source:f.get(M.sourceFile),documentVersion:I.graph.version,selectionRef:x,isRepeat:O.isRepeat,propertyProvenance:O.propertyProvenances,repeatTargets:D}),W=vm(N,I.graph,I.topology,I.capabilities,O.textSources,O.provenances,O.dynamicData,U);return p===N?W:Wm(W,p,I.document??null,I.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,y){let x=ur(p,y),I=yt(p)??p;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let N=x.detailProjections.get(I);if(N){let O=Em(I,x.graph,x.topology,x.capabilities,N.textSources,N.writeTarget,N.provenances,N.conditional,N.componentSemantic,N.styleSource,N.dynamicData);return p===I?O:Hm(O,p,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,y){let x=ur(p,y),I=yt(p)??p;if(!x?.graph)throw new Error(`Key not found: ${p}`);let N=x.graph.elements.get(I);if(!N)throw new Error(`Key not found: ${p}`);let O=f.get(N.sourceFile);if(O===void 0)throw new Error(`Source not loaded: ${N.sourceFile}`);return Os({key:I,route:{composition:x.composition,routeId:x.routeId,graph:x.graph,source:O}})},refreshSourceForKey:Gg,async execute(p){if(await E,g)return se(p,j.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return Yg(p);if(p.kind==="insert-page-resource")return Zg(p);if(p.kind==="delete-page-source")return Qg(p);let y=await Ul(p);if("ok"in y)return y;await Tl(p);let x=await Ul(p);if("ok"in x)return x;let I=x;if(p.target.kind==="page-unit"){let B=p;return p.kind==="insert-child"||p.kind==="replace-node"?qg(B,I):p.kind==="move-node"||p.kind==="remove-node"?eh(B,I):se(p,j.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}if(!I.graph||!I.topology||!I.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Y(p),error:{code:p.target.kind==="route"?j.ROUTE_NOT_FOUND:j.NODE_NOT_FOUND,message:p.target.kind==="route"?"Composition not ready for route target.":p.target.kind==="node"?`Target key not found: ${p.target.key}`:`${p.kind} source target execution is not implemented yet.`}};let N=UC(I,I.graph,I.capabilities,f,i),O=await new Pi(N).plan(p);if(!O.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Y(p),error:{code:lo(O.errorCode),message:O.reason}};let M=O.plan;if(M.steps.length===0)return p.kind==="set-props"?{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Y(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Y(p),error:{code:j.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};d+=1;try{if(M.steps.some(D=>D.type==="invoke-external-adapter")){let D=await u.execute(M);if(!D.ok)return se(p,lo(D.errorCode),D.reason);let U={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(Y(p),D.resultVersion),affectedFiles:D.affectedFiles,...D.selectionRef?{selectionRef:D.selectionRef}:{}};return us(U,{rebuiltRoutes:[],failedRoutes:[]}),U}let B=await u.prepareRewritePlan(M);return B.ok?await Dn({request:p,filePlan:B.filePlan,...B.selectionRef?{selectionRef:B.selectionRef}:{}}):se(p,lo(B.errorCode),B.reason)}catch(B){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Y(p),error:{code:j.INTERNAL_ERROR,message:Ge(B)}}}finally{d-=1}},async undo(p){if(await E,g)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:ve(o.entries[0].key),error:{code:j.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};d+=1;try{return await Dl("undo")}finally{d-=1}},async redo(p){if(await E,g)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:ve(o.entries[0].key),error:{code:j.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};d+=1;try{return await Dl("redo")}finally{d-=1}},notifyFileChanged(p){Rl([p])},getAffectedCompositions(p){return Jg(p)},subscribe(p){return r.subscribe(p)}}}function jC(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function $C(e,t,n){let r=new Map,o=new Map,i=(u,f,m)=>{let d=u.get(f)??new Set,g=d.size;return d.add(m),u.set(f,d),d.size!==g},s=(u,f)=>{if(!u.importedFrom)return!1;if(u.exportName==="default")return i(o,u.importedFrom,f);let m=i(r,`${u.importedFrom}#${u.tag}`,f);return u.exportName&&u.exportName!==u.tag&&(m=i(r,`${u.importedFrom}#${u.exportName}`,f)||m),m},a=u=>r.get(`${u.sourceFile}#${u.componentName}`)??o.get(u.sourceFile);for(let u of t.elements.values()){if(u.sourceFile!==n.entryFile||!u.importedFrom||!/^[A-Z]/.test(u.tag))continue;let f=n.placements.find(d=>d.members.some(g=>g.sourceRange!==null&&zc(u.sourceRange,g.sourceRange)));if(!f)continue;let m=f.placementUnitKey;s(u,m)}let c=!0;for(;c;){c=!1;for(let u of t.elements.values()){if(u.sourceFile===n.entryFile||!u.importedFrom||!/^[A-Z]/.test(u.tag))continue;let f=a(u);if(f)for(let m of f)c=s(u,m)||c}}let l=n.placements.find(u=>u.placementKey===n.container.placementKey&&u.relation==="append");for(let u of e.entries){let f=yt(u.key)??u.key,m=t.elements.get(u.key)??t.elements.get(f);if(!m)continue;if(m.sourceFile===n.entryFile){if(n.container.sourceRange&&zc(m.sourceRange,n.container.sourceRange)&&l){u.pageCompositionUnitKey=l.placementUnitKey;continue}let h=n.placements.find(E=>E.members.some(S=>S.sourceRange!==null&&(zc(m.sourceRange,S.sourceRange)||VC(S.sourceRange,m.sourceRange))));if(h){u.pageCompositionUnitKey=h.placementUnitKey;continue}}let d=r.get(`${m.sourceFile}#${m.componentName}`);if(d){d.size===1&&(u.pageCompositionUnitKey=d.values().next().value);continue}let g=o.get(m.sourceFile);g?.size===1&&(u.pageCompositionUnitKey=g.values().next().value)}}function zc(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function VC(e,t){return sg(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&sg(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function sg(e,t,n,r){return e!==n?e-n:t-r}function UC(e,t,n,r,o){let i=new Map,s=new Map,a=(u,f)=>{if(s.has(u))return;s.set(u,f);let m=t.elements.get(u);for(let d of m?.childKeys??[])a(d,f)};for(let u of t.regions)if(u.kind==="repeat-region")for(let f of u.childKeys)i.set(f,u.ownerKey),a(f,u.ownerKey);return{getNode(u){let f=c(u),m=t.elements.get(f.baseKey);return m?l(u,m):null},getChildNodes(u){let f=c(u),d=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(d)return d.map(h=>{let E=yt(h)??h,S=t.elements.get(E);return S?l(h,S):null}).filter(h=>h!==null);let g=t.elements.get(f.baseKey);return g?g.childKeys.map(h=>{let E=t.elements.get(h);return E?l(h,E):null}).filter(h=>h!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,f])=>({file:u,content:f}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let f=c(u),m=n.get(f.baseKey);return m?{...m,key:u,constraints:m.constraints.map(d=>({...d})),...m.editModes?{editModes:{...m.editModes}}:{}}:{composition:e.composition,key:u,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(u){return r.get(u)??""},getFileVersion(u){return Math.max(e.fileVersions.get(u)??0,t.version)},getRouteEntryFile(u){return e.routeId===u?e.entryFile:null},getComponentSemantic(u){let f=c(u);return e.detailProjections?.get(f.baseKey)?.componentSemantic??null},getClassNameSource(u){let f=c(u),m=t.elements.get(f.baseKey),d=m?r.get(m.sourceFile):void 0;return!m||d===void 0?null:Os({key:f.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:d}})},getEditableTextSegmentIndex(u){let f=c(u),d=e.detailProjections?.get(f.baseKey)?.textTargets.keys()?.next();return d&&!d.done?d.value:null},async getTextWriteTarget(u,f){let m=c(u);return Uc(e.detailProjections?.get(m.baseKey)?.textTargets.get(f)??null,m.repeatIndex)},async getElementPropertyWriteTarget(u,f){let m=c(u);return Uc(e.detailProjections?.get(m.baseKey)?.elementPropertyTargets.get(f)??null,m.repeatIndex)},getPropertyState(u,f,m){let d=c(u),g=t.elements.get(d.baseKey);if(!g)return null;let E=e.detailProjections?.get(d.baseKey)?.propertyProvenances.get(f);if(E)return E;let S=g.attributes?.find(v=>v.name===f);return S?S.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${f}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:S,target:{kind:"jsx-attribute",file:g.sourceFile,sourceRange:S.sourceRange}}:(g.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${f}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(u,f,m){let d=c(u),g=t.elements.get(d.baseKey);if(!g)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let h=m?{...m,key:d.baseKey}:d.repeatIndex!==null?{key:d.baseKey,instanceIndex:d.repeatIndex}:void 0;return hc({file:g.sourceFile,source:r.get(g.sourceFile)??"",element:g,propertyName:f,selectionRef:h,graph:t,sources:r})},getTextProvenance(u,f){let m=c(u);return e.detailProjections?.get(m.baseKey)?.provenances.get(f)??null}};function c(u){let f=yC(u);return f?{baseKey:f.baseKey,repeatIndex:zm(e.document??null,u,f.baseKey,e.documentIndex)??Xm(f)}:{baseKey:u,repeatIndex:null}}function l(u,f){let m=yt(u)??u,d=e.documentIndex?.entriesByKey.get(u);return{key:u,file:f.sourceFile,component:f.componentName,tag:f.tag,structuralPath:f.identity.structuralPath,sourceRange:f.sourceRange,parentKey:d?.parentKey??f.parentKey??void 0,isRepeatRegion:f.boundaryKind==="repeat-region"||s.has(m),isBoundary:!1,importedFrom:f.importedFrom,exportName:f.exportName,isRepeatItemRoot:i.has(m),repeatOwnerKey:i.get(m)??s.get(m),attributes:f.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(h=>({...h}))}:null,resolvedValue:g.resolvedValue}))}}}var KC={"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 lo(e){return KC[e]}function Ge(e){return e instanceof Error&&e.message?e.message:String(e)}function ag(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function JC(e){let t=_n(e);if(!SC.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=>EC.map(a=>`${s}/${a}`))}function XC(e){let n=_n(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function zC(e){return ug(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function HC(e){return ug(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function ug(e,t){let n=[];for(let r of e.matchAll(t)){let o=dg(r[1]??"");o&&n.push(o)}return n}function cg(e,t){let n=dg(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?_n(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?_n(`${WC(e)}/${n}`):n.startsWith("/")?_n(n.slice(1)):Hc(n)?_n(n):null}function dg(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Hc(e){return/\.css$/i.test(e)}function WC(e){let t=_n(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function GC(e){return Array.from(new Set(e))}function _n(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 YC(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}import Qc from"node:path";import{TextDecoder as ZC}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as pg,SITE_EDIT_SOURCE_ALLOWED_DIRS as mg,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as gg,SiteEditCompositionContextSchema as QC,SiteEditSourceFileResponseSchema as Wc,SiteEditSourceLocationSchema as qC,SiteEditSourcePathSchema as Gi,SiteEditSourceTreeResponseSchema as eR,isSiteEditTextSourcePath as tR}from"@vcp-dev/contracts";var nR=[...gg,...pg,...mg];function qc(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return QC.parse(e.composition)}var Gc=2e3,Yc=12,Zc=24*1024*1024,fg=512*1024,rR=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),oR={".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"},iR={".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"},sR=new ZC("utf-8",{fatal:!0});async function Yi(e,t={}){let n=qc(t),{files:r,truncated:o}=await mR(e,t),i=yR(r.map(s=>s.metadata));return eR.parse({composition:n,nodes:i,defaultPath:xR(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Zi(e,t,n={}){let r=qc(n),o=Gi.parse(t.path),i=await lR(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(el(o)){let a=xg(o),c=await dR(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Wc.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await aR(e,o);return s.ok?Wc.parse({composition:r,path:o,kind:"text",language:bg(o),sizeBytes:s.sizeBytes,contentHash:be(s.content),readonly:!1,content:s.content}):Wc.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function aR(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=cR(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 cR(e){if(e.includes(0))return null;try{return sR.decode(e)}catch{return null}}async function lR(e,t,n){if(!fR(t,n))return null;let r=await uR(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function uR(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=hg(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(el(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function dR(e,t){if(!rR.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>fg)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>fg?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function fR(e,t){return gg.some(n=>n===e)||pg.some(n=>n===e)||mg.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Gi.safeParse(n);return r.success&&r.data===e})}function Qi(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return qC.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 hg(e){return Array.isArray(e)?{files:e}:e}function pR(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function mR(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=hg(await e.listFiles({roots:gR(t),maxFiles:Gc+1,maxDepth:Yc,maxTotalBytes:Zc+1})),r=new Map,o=new Set(n.truncated?.reasons),i=0;for(let a of[...n.files].sort((c,l)=>c.path.localeCompare(l.path))){let c=Gi.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Yc){o.add("max-depth");continue}if(r.size>=Gc){o.add("max-files");break}if(i+a.sizeBytes>Zc){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:hR(l,a.sizeBytes,qc(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:pR([...o]),maxFiles:Gc,maxDepth:Yc,maxTotalBytes:Zc}}:{}}}function gR(e){let t=new Set(nR);for(let n of e.routeEntryFiles??[]){let r=Gi.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function hR(e,t,n){return el(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:xg(e),readonly:!0}:{composition:n,path:e,kind:"text",language:bg(e),sizeBytes:t,readonly:!1}}function yR(e){let t=[];for(let n of e){let r=n.path.split("/"),o=t,i="";for(let[s,a]of r.entries()){i=i?`${i}/${a}`:a;let c=s===r.length-1,l=o.find(u=>u.name===a);if(l||(l=c?{kind:"file",name:a,path:i,file:n}:{kind:"directory",name:a,path:i,children:[]},o.push(l)),c){if(l.kind!=="file")throw new Error(`Source tree path collision: ${n.path}`);l.file=n}else{if(l.kind!=="directory")throw new Error(`Source tree path collision: ${n.path}`);o=l.children}}}return yg(t)}function yg(e){return e.map(t=>t.kind==="directory"?{...t,children:yg(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function xR(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 el(e){return!tR(e)}function xg(e){let t=Qc.posix.extname(e).toLowerCase();return!t&&Qc.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":oR[t]??"application/octet-stream"}function bg(e){let t=Qc.posix.extname(e).toLowerCase();return iR[t]??"plaintext"}var qi=class{constructor(t){this.options=t,this.fileSystem=new pr(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return ko(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 Co(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Yi(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Zi(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Qi(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=SR.safeParse(t);if(!n.success)return{result:Io(t,n.error.issues.map(i=>i.message))};let r=new pr(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:dn(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=ER.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>vR(l,t.kind==="source-edit")),changedCompositions:o.getAffectedCompositions(a.map(l=>l.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:c.patches.map(l=>l.path),composition:i.composition,at:new Date().toISOString()}),{result:s,patchPlan:c}}finally{o.dispose()}}dispose(){this.engine.dispose()}createEngine(t,n={}){let r=n.emitEvents??!0;return uo({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Ro(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}:{}})}};function vR(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:be(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:be(e.before)},fullContent:e.after}}function IR(e){return new qi(e)}import{SiteEditOperationRequestSchema as RR}from"@vcp-dev/contracts";import kt from"node:fs/promises";import Ye from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as kR,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as CR}from"@vcp-dev/contracts";var es=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=uo({...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 Yi(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Zi(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Qi(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 kt.readFile(Ye.join(n,r),"utf8")},async readFileBytes(r){return kt.readFile(Ye.join(n,r))},async getFileInfo(r){let o=Ye.join(n,...r.split("/"));try{let i=await kt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await Jo(Ye.join(n,r),o)},async createExclusive(r,o){let i=Ye.join(n,r);await kt.mkdir(Ye.dirname(i),{recursive:!0});let s=await kt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await kt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await kt.rm(Ye.join(n,r),{force:!0});let o=r.replace(/\\/g,"/"),i=["components/site/generated","src/components/site/generated"].find(c=>o.startsWith(`${c}/`));if(!i)return;let s=Ye.join(n,i),a=Ye.dirname(Ye.join(n,o));for(;a!==s&&a.startsWith(`${s}${Ye.sep}`);){try{await kt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Ye.dirname(a);continue}break}a=Ye.dirname(a)}},async exists(r){try{return await kt.access(Ye.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...CR,...kR],i=[],s=new Set,a=new Set,c=0;for(let f of o)await u(f,i,1);let l=i.sort((f,m)=>f.path.localeCompare(m.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(f,m,d){if(r.maxDepth!==void 0&&d>r.maxDepth){a.add("max-depth");return}let g=Ye.join(n,...f.split("/")),h;try{h=await kt.lstat(g)}catch{return}if(h.isSymbolicLink())return;if(h.isFile()){let S=h.ino>0?`${String(h.dev)}:${String(h.ino)}`:null;if(S&&s.has(S))return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+h.size>r.maxTotalBytes){a.add("max-total-bytes");return}S&&s.add(S),m.push({path:f,sizeBytes:h.size}),c+=h.size;return}if(!h.isDirectory())return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}let E=await kt.readdir(g,{withFileTypes:!0});for(let S of E)S.isSymbolicLink()||await u(`${f}/${S.name}`,m,d+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function tl(e){return new es(e)}var ts=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=tl({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Ro(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:ko(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:Co(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=RR.safeParse(r);if(!o.success)return Io(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},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:dn(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:dn(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:dn(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 wR(e){return new ts(e)}import{createHash as NR,randomUUID as pl}from"node:crypto";import Pe from"node:fs/promises";import Te from"node:path";var xt=1,rl=1,PR=2,AR="index.json",TR="recovery.json",FR="transaction-journal.json",_R="document-version.json",rs={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},Q={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"},te=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};async function Pg(e,t={}){let n=HR(e),r=YR(t.limits),o=nl(n),i=WR(n),s=await qe(i),a=await qe(o)||s;a||(await jR(n),await $R(n)),a||await ZR(n);let c=await it(n),l=new Set(a?(await cs(n)).map(f=>f.stageId):[]);a||await fo(n,c.entryIds);let u=async()=>{if(await qe(o)||s)throw new te(Q.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return wg(n)},async writeDocumentVersion(f){if(await u(),!Number.isInteger(f)||f<0)throw new te(Q.INVALID_SCHEMA,"document version must be a non-negative integer");let m=await wg(n);await po(Dg(n),{schemaVersion:1,version:Math.max(m,f)})},async stageAppend(f,m={}){await u();let d=await Eg(f,r),g={schemaVersion:rl,stageId:pl(),entryId:d.entryId,blobIds:d.blobs.map(h=>h.digest)};try{await vg(n,d),await DR(n,g,m.durableManifest!==!1)}catch(h){try{await kg(n,g)}catch(E){throw new te(Q.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:E})}throw h}return{stageId:g.stageId,entryId:g.entryId,blobIds:g.blobIds}},async discardStage(f){await u(),al(f);let m=await il(n,f);m&&await kg(n,m)},async previewStagedAppend(f,m){return await u(),(await Sg(n,r,f,m)).transition},async previewCursor(f,m){await u();let d=await it(n);return cl(d,m),ol(f,d.entryIds.length),Ag(d,d.entryIds,f)},async publishStagedAppend(f,m,d){if(await u(),os(f,"entryId"),d){al(d);let h=await il(n,d);if(!h||h.entryId!==f)throw new te(Q.INVALID_SCHEMA,"history stage does not match the published entry")}let g=await Sg(n,r,f,m);return Rg({rootDir:n,previousDigest:g.current.digest,entryIds:g.entryIds,cursor:g.cursor,afterWrite:async()=>{d?await is(n,d):await BR(n,f),await fo(n,g.entryIds)}})},async append(f){await u();let m=await it(n),d=await Eg(f,r),g=[...m.entryIds];m.cursor<g.length-1&&g.splice(m.cursor+1),g.push(d.entryId);try{await vg(n,d);let h=await Tg(n,g,r);return await gl(n,h.entryIds,h.cursor),await fo(n,h.entryIds),it(n)}catch(h){throw await fo(n,m.entryIds),h}},async readEntry(f){return os(f,"entryId"),go(n,f)},async readBlob(f){os(f,"blobId");let m=await Il(n,f),d=await cn(m,Q.NOT_FOUND,"blob");return hl(d,f,m),d},async readIndex(){return it(n)},async readStatus(){let f=await it(n);return{canUndo:f.undoIds.length>0,canRedo:f.redoIds.length>0,undoDepth:f.undoIds.length,redoDepth:f.redoIds.length,cursor:f.cursor,recoveryRequired:await qe(o)||await qe(i)}},async readUndoRedoIds(){let f=await it(n);return{undoIds:f.undoIds,redoIds:f.redoIds,currentId:f.currentId}},async setCursor(f,m){await u();let d=await it(n);return cl(d,m),ol(f,d.entryIds.length),Rg({rootDir:n,previousDigest:d.digest,entryIds:d.entryIds,cursor:f})},async markRecoveryRequired(f){await qe(o)||await po(nl(n),{schemaVersion:xt,reason:GR(f),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Pe.rm(nl(n),{force:!0})},async readTransactionJournal(){return await qe(i)?ns(i):null},async writeTransactionJournal(f){await u(),Lg(f);try{await po(i,f)}catch(d){let g=await ns(i).catch(()=>null);if(g&&Buffer.from(st(g)).equals(Buffer.from(st(f))))return;throw g?new te(Q.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:d}):d}let m=await ns(i);if(!Buffer.from(st(m)).equals(Buffer.from(st(f))))throw new te(Q.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(f){let m=await qe(i)?await ns(i):null;if(m&&m.transactionId!==f)throw new te(Q.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Pe.rm(i,{force:!0})}catch(d){if(!await qe(i))return;throw d}if(await qe(i))throw new te(Q.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await u();for(let m of l)await is(n,m),l.delete(m);await VR(n);let f=await it(n);await fo(n,f.entryIds)}}}async function Sg(e,t,n,r){os(n,"entryId");let o=await it(e);cl(o,r);let i=await go(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await Tg(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:Ag(o,a.entryIds,a.cursor)}}function Ag(e,t,n){return ol(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:OR(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function OR(e,t){return ln(st({schemaVersion:xt,entryIds:e,cursor:t}))}function ol(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new te(Q.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function MR(e){if(!Ct(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!at(e.expectedIndexDigest)||!at(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!at(n)?!1:t===-1?n===null:at(n)}async function Eg(e,t){if(!e.kind.trim())throw new te(Q.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new te(Q.INVALID_JSON,"history blob name must not be empty");let l=zR(c.data),u=ln(l);n.push({name:c.name,bytes:l,digest:u,sizeBytes:l.byteLength}),r.push({name:c.name,digest:u,sizeBytes:l.byteLength})}let o={schemaVersion:xt,kind:e.kind,manifest:e.manifest,blobs:r},i=st({...o}),s=ln(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new te(Q.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function vg(e,t){let n=bl(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Ig(Sl(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},vl(e,a.digest))),Ig(n,st(r),{kind:"entry",digest:t.entryId},El(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Ig(e,t,n,r){let o=await dl(e)??(r?await dl(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new te(n.kind==="blob"?Q.BLOB_CORRUPT:Q.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Og(e,t)}async function Tg(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await _g(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new te(Q.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function DR(e,t,n){ml(t);let r=xl(e,t.stageId);if(n){await po(r,t);return}await XR(r,t)}async function il(e,t){let n=await dl(xl(e,t));if(n===null)return null;let r=ho(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=ml(r);if(o.stageId!==t)throw new te(Q.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function cs(e){let t=[];for(let n of await as(yl(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);al(r);let o=await il(e,r);o&&t.push(o)}return t}async function kg(e,t){ml(t);let n=await it(e),r=(await cs(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await go(e,s);for(let c of a.blobs)i.add(c.digest)}for(let s of r){o.add(s.entryId);for(let a of s.blobIds)i.add(a)}o.has(t.entryId)||await Cg(bl(e,t.entryId),El(e,t.entryId));for(let s of t.blobIds)i.has(s)||await Cg(Sl(e,s),vl(e,s));await is(e,t.stageId),await fl(yo(e)),await fl(xo(e))}async function is(e,t){await sl(xl(e,t)),await LR(e)}async function LR(e){try{await Pe.rmdir(yl(e))}catch(t){if(bo(t)||Ct(t)&&t.code==="ENOTEMPTY")return;throw t}}async function BR(e,t){for(let n of await cs(e))n.entryId===t&&await is(e,n.stageId)}async function sl(e){if(await Pe.rm(e,{force:!0}),await qe(e))throw new te(Q.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Cg(e,t){await sl(e),await sl(t)}function ml(e){if(!Ct(e)||e.schemaVersion!==rl||typeof e.stageId!="string"||!Fg(e.stageId)||!at(e.entryId))throw new te(Q.INVALID_SCHEMA,"history stage schema is invalid");let t=Mg(e.blobIds,"history stage blobIds");return{schemaVersion:rl,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function al(e){if(!Fg(e))throw new te(Q.INVALID_PATH,"history stageId must be a UUID")}function Fg(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 fo(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await go(e,c);for(let u of l.blobs)r.add(u.digest)}for(let c of await cs(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=yo(e),i=await as(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=Ng(c.slice(0,-5));l&&!n.has(l)&&await ss(Te.join(o,c))}let s=xo(e),a=await as(s);for(let c of a){let l=Ng(c);l&&!r.has(l)&&await ss(Te.join(s,c))}}async function it(e){let t=ls(e),n=await cn(t,Q.NOT_FOUND,"index"),r=ho(Buffer.from(n).toString("utf8"),"index"),o=UR(r),i=[...o.entryIds],{totalBytes:s}=await _g(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:xt,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function _g(e,t){let n=0,r=new Set,o=ls(e),i=await cn(o,Q.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await go(e,s),c=await Bg(e,s),l=await cn(c,Q.NOT_FOUND,"entry");n+=l.byteLength;for(let u of a.blobs){if(r.has(u.digest))continue;r.add(u.digest);let f=await Il(e,u.digest),m=await cn(f,Q.NOT_FOUND,"blob");hl(m,u.digest,f),n+=m.byteLength}}return{totalBytes:n}}async function go(e,t){let n=await Bg(e,t),r=await cn(n,Q.NOT_FOUND,"entry"),o=ho(Buffer.from(r).toString("utf8"),`entry ${t}`),i=KR(o);if(i.id!==t)throw new te(Q.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(ln(st({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new te(Q.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=await Il(e,a.digest),l=await cn(c,Q.NOT_FOUND,"blob");hl(l,a.digest,c)}return i}async function gl(e,t,n){let r={schemaVersion:xt,digest:ln(st({schemaVersion:xt,entryIds:t,cursor:n})),entryIds:t,cursor:n};await po(ls(e),r)}function cl(e,t){if(t!==void 0&&e.digest!==t)throw new te(Q.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Rg(e){let t=ln(st({schemaVersion:xt,entryIds:e.entryIds,cursor:e.cursor}));try{return await gl(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await it(e.rootDir)}catch(n){let r=await it(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new te(Q.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function jR(e){await Pe.mkdir(e,{recursive:!0}),await Pe.mkdir(yo(e),{recursive:!0}),await Pe.mkdir(xo(e),{recursive:!0}),await Pe.mkdir(mo(e),{recursive:!0})}async function $R(e){await Pe.rm(mo(e),{recursive:!0,force:!0}),await Pe.mkdir(mo(e),{recursive:!0})}async function VR(e){let t=mo(e);await Pe.mkdir(t,{recursive:!0});for(let n of await as(t))n!=="stages"&&await Pe.rm(Te.join(t,n),{recursive:!0,force:!0})}function UR(e){if(!Ct(e))throw new te(Q.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==xt)throw new te(Q.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Mg(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new te(Q.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!at(o))throw new te(Q.INDEX_CORRUPT,"index digest is invalid");let i=ln(st({schemaVersion:xt,entryIds:t,cursor:r}));if(o!==i)throw new te(Q.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:xt,digest:o,entryIds:t,cursor:r}}function KR(e){if(!Ct(e))throw new te(Q.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==xt)throw new te(Q.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!at(t))throw new te(Q.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new te(Q.ENTRY_CORRUPT,"entry kind is invalid");let r=ul(e.manifest,"entry.manifest"),o=JR(e.blobs);return{id:t,schemaVersion:xt,kind:n,manifest:r,blobs:o}}function JR(e){if(!Array.isArray(e))throw new te(Q.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!Ct(t))throw new te(Q.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new te(Q.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!at(o))throw new te(Q.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new te(Q.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function po(e,t){await Og(e,st(t))}async function XR(e,t){let n=Te.dirname(e),r=Te.basename(e),o=Te.join(n,`.${r}.${process.pid}.${pl()}.tmp`);await Pe.mkdir(n,{recursive:!0});try{await Pe.writeFile(o,st(t),{flag:"wx"}),await Pe.rename(o,e)}finally{await ss(o)}}async function Og(e,t){let n=Te.dirname(e),r=Te.basename(e),o=Te.join(n,`.${r}.${process.pid}.${pl()}.tmp`);await Pe.mkdir(n,{recursive:!0});try{let i=await Pe.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await Pe.rename(o,e),await fl(n)}finally{await ss(o)}}function st(e){return Buffer.from(JSON.stringify(ll(e)),"utf8")}function ll(e){if(Array.isArray(e))return e.map(t=>ll(t));if(Ct(e)){let t={};for(let n of Object.keys(e).sort())t[n]=ll(e[n]);return t}return e}function ho(e,t){try{return JSON.parse(e)}catch(n){throw new te(Q.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function ul(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=>ul(n,t));if(Ct(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=ul(o,t);return n}break}throw new te(Q.INVALID_JSON,`${t} must be JSON-serializable`)}function Mg(e,t){if(!Array.isArray(e))throw new te(Q.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!at(n))throw new te(Q.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function os(e,t){if(!at(e))throw new te(Q.INVALID_PATH,`${t} must be a sha256 digest`)}function at(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function ln(e){return`sha256:${NR("sha256").update(e).digest("hex")}`}function zR(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function cn(e,t,n){try{return await Pe.readFile(e)}catch(r){throw new te(t,`${n} not found: ${e}`,{cause:r})}}async function dl(e){try{return await Pe.readFile(e)}catch(t){if(bo(t))return null;throw t}}function hl(e,t,n){if(ln(e)!==t)throw new te(Q.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function qe(e){try{return await Pe.access(e),!0}catch(t){if(bo(t))return!1;throw t}}async function ss(e){try{await Pe.rm(e,{force:!0,recursive:!0})}catch{}}async function fl(e){try{let t=await Pe.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function as(e){try{return await Pe.readdir(e)}catch(t){if(bo(t))return[];throw t}}function HR(e){if(typeof e!="string"||e.trim().length===0)throw new te(Q.INVALID_ROOT,"history store rootDir must be a non-empty string");return Te.resolve(e)}function ls(e){return Te.join(e,AR)}function nl(e){return Te.join(e,TR)}function WR(e){return Te.join(e,FR)}function Dg(e){return Te.join(e,_R)}async function wg(e){try{let t=await Pe.readFile(Dg(e),"utf8"),n=ho(t,"document version");if(!Ct(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new te(Q.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(bo(t))return 0;throw t}}async function ns(e){let t=await cn(e,Q.RECOVERY_PENDING,"transaction journal"),n=ho(Buffer.from(t).toString("utf8"),"transaction journal");return Lg(n),n}function Lg(e){if(!Ct(e)||e.schemaVersion!==PR||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!MR(e.historyTransition)||!Array.isArray(e.files))throw new te(Q.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!Ct(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!at(t.preDigest)||t.postDigest!==null&&!at(t.postDigest))throw new te(Q.INVALID_SCHEMA,"transaction journal file digest is invalid")}function GR(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function yo(e){return Te.join(e,"entries")}function xo(e){return Te.join(e,"blobs")}function mo(e){return Te.join(e,"tmp")}function yl(e){return Te.join(mo(e),"stages")}function xl(e,t){return Te.join(yl(e),`${t}.json`)}function bl(e,t){return Te.join(yo(e),`${$g(t)}.json`)}function Sl(e,t){return Te.join(xo(e),$g(t))}function El(e,t){return Te.join(yo(e),`${t}.json`)}function vl(e,t){return Te.join(xo(e),t)}async function Bg(e,t){return jg(bl(e,t),El(e,t))}async function Il(e,t){return jg(Sl(e,t),vl(e,t))}async function jg(e,t){return await qe(e)?e:await qe(t)?t:e}function $g(e){return e.slice(7)}function Ng(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return at(t)?t:null}function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bo(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function YR(e){return{maxEntries:e?.maxEntries??rs.maxEntries,maxSessionBytes:e?.maxSessionBytes??rs.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??rs.maxEntryBytes}}async function ZR(e){let t=ls(e);await qe(t)||await gl(e,[],-1)}export{te as FileHistoryStoreError,Or as PageTemplateManagedSourceError,ts as PreviewFileSystemSiteEditEngineRuntime,Zu as SITE_EDIT_RAW_COLOR_LITERAL_RE,qi as SnapshotSiteEditEngineRuntime,jd as computeManagedPageTemplatePaths,wR as createPreviewSiteEditEngineRuntime,IR as createSiteEditEngineRuntime,Bd as decodePageTemplateKey,Sa as encodePageTemplateId,$d as isManagedPageTemplateSourcePath,Pg as openFileHistoryStore,rE as resolveManagedPageTemplateComposition,ui as scanManagedPageTemplateCandidates,Ud as scanSiteEditCompositionsFromFiles,Nr as scanSiteEditThemeStyleViolations};
14
+ `||m==="\r"}if(s)return lr(t,`Unterminated block comment in ${t}.`);if(o)return lr(t,`Unterminated string literal in ${t}.`);if(c)return lr(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?lr(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function lr(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function uo(e){let t="idle",n=e.fileSystem??JC(),r=Lu(),o=Zm({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?ed(e.historyStore):XC()),u=Gm(n,{externalAdapters:e.externalAdapters}),f=new Map,m=new Set,d=0,g=e.historyStore?.recoveryRequired??!1,h=Gc(),E=N();function S(p){return(Yi.isAbsolute(p)?Yi.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function v(p,y){let x=Yi.posix.dirname(p),I=y.replace(/\.(?:tsx?|jsx?)$/i,""),w=Yi.posix.relative(x,I);return w.startsWith(".")?w:`./${w}`}function C(p,y){return p.startLine===y.startLine&&p.startColumn===y.startColumn&&p.endLine===y.endLine&&p.endColumn===y.endColumn}async function N(){let p=e.historyStore;if(p)try{let y=await p.readTransactionJournal();if(!y)return;let x=await p.readIndex(),I=await Promise.all(y.files.map(async _=>await n.exists(_.path)?be(await n.readFile(_.path)):null));if(cg({journal:y,index:x,observedFileDigests:I})!=="ambiguous"){await p.clearTransactionJournal(y.transactionId);let _=await p.readStatus();_.recoveryRequired||(await p.cleanupTmp(),_=await p.readStatus()),g=_.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${y.transactionId} at phase ${y.phase}`),g=!0}catch(y){g=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${Ge(y)}`).catch(()=>{})}}function A(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let y=pg(p.context,p.entryFile);i.set(p.key,y),P(y,y.dependencyFiles)}function P(p,y){let x=new Set(y);k(p),p.dependencyFiles=x;for(let I of p.dependencyFiles){let w=s.get(I);w||(w=new Set,s.set(I,w)),w.add(p.key)}}function k(p){for(let y of p.dependencyFiles){let x=s.get(y);x&&(x.delete(p.key),x.size===0&&s.delete(y))}p.dependencyFiles.clear()}function T(p){let y=new Set;for(let x of p)for(let I of s.get(x)??[])y.add(I);return y}function O(p){for(let y of p)if(!s.has(y))return!1;return!0}async function L(p,y,x,I,w){let _=new Map,M=gm(w.values()),B=new Map,D=typeof n.exists=="function"?U=>n.exists(U):async()=>!1;for(let[U,W]of p.elements){let ye=y.nodes.get(U);if(!ye)continue;let ae=x.get(W.sourceFile)??I.get(W.sourceFile),Ie=new Map,we=new Map,Ne=new Map,Ce=[];for(let xe of W.textSegments){if(!ae){Ie.set(xe.index,null);continue}let fr=await hm({file:W.sourceFile,source:ae,segment:xe,readFile:et=>n.readFile(et),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:et,adapterId:un,capabilities:gs})=>({sourceType:et,adapterId:un,capabilities:gs})),functionCallContracts:e.functionCallContracts,fileCache:M}),We=await jc({file:W.sourceFile,source:ae,target:{kind:"text-segment",segment:xe},readFile:et=>n.readFile(et),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:et,adapterId:un,capabilities:gs})=>({sourceType:et,adapterId:un,capabilities:gs})),functionCallContracts:e.functionCallContracts,fileCache:M}),ut=tR(fr);Ie.set(xe.index,ut),we.set(xe.index,fr),Ne.set(xe.index,We),Ce.push({editable:xe.editable,source:ut})}let F=new Map,K=new Map;if(ae)for(let xe of W.attributes??[]){let fr=await ar({file:W.sourceFile,source:ae,sourceRange:xe.sourceRange,expression:xe.source?.expression??xe.value,sourceInfo:xe.source,readFile:ut=>n.readFile(ut),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ut,adapterId:et,capabilities:un})=>({sourceType:ut,adapterId:et,capabilities:un})),functionCallContracts:e.functionCallContracts,fileCache:M}),We=await km({element:W,file:W.sourceFile,source:ae,propertyName:xe.name,readFile:ut=>n.readFile(ut),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ut,adapterId:et,capabilities:un})=>({sourceType:ut,adapterId:et,capabilities:un})),functionCallContracts:e.functionCallContracts,fileCache:M});K.set(xe.name,We),F.set(xe.name,fr)}let ee=Mm(nR(ye.writeTarget),Ce),re=Cm({key:U,element:W,graph:p,provenances:Ne}),Fe=$m(W),ct=ae?await bp({element:W,graph:p,file:W.sourceFile,source:ae,readFile:xe=>n.readFile(xe),exists:D,fileCache:B}):void 0,lt=p.regions.find(xe=>xe.kind==="conditional-region"&&xe.childKeys.includes(U)),dr,Je=lt?.sourceCandidates?.[0];if(ae&&lt&&Je?.kind==="conditional-branch"){let xe=await jc({file:W.sourceFile,source:ae,target:{kind:"conditional-branch",candidate:Je},readFile:We=>n.readFile(We),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:We,adapterId:ut,capabilities:et})=>({sourceType:We,adapterId:ut,capabilities:et})),functionCallContracts:e.functionCallContracts,fileCache:M});dr={currentBranch:lt.childKeys.indexOf(U)<=0?"then":"else",availableBranches:lt.childKeys.length>1?["then","else"]:["then"],conditionExpression:Je.conditionExpression,provenance:{finalSource:xe.finalSource?{kind:xe.finalSource.kind,file:xe.finalSource.file,displayPath:xe.finalSource.displayPath}:null,chain:xe.chain.map(We=>({kind:We.kind,file:We.file,displayName:We.displayName,canEditHere:We.canEditHere})),confidence:xe.confidence,editMode:xe.editMode,diagnostics:xe.diagnostics.map(We=>({code:We.code,message:We.message}))}}}_.set(U,{textSources:Ie,textTargets:we,elementPropertyTargets:F,propertyProvenances:K,isRepeat:yR(U,p),provenances:Ne,writeTarget:ee,componentSemantic:re,styleSource:Fe,conditional:dr,dynamicData:ct})}return _}function G(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function ne(p,y){let x=o.initialVersions.get(p.key)??0;for(let I of y.values())x=Math.max(x,I);return Math.max(x,p.graph?.version??0)}function ve(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function Y(p){try{return ve(o.resolveSelector(p.composition).key)}catch{return 0}}async function ue(p,y,x={}){let I=i.get(p);if(!I)return null;let w=x.sourceCache??Qc(f,[]),_=await Ae(I.entryFile),{graph:M,allSources:B,diagnostics:D,parsedModules:U,entryModule:W}=await Wu(I.entryFile,y,Je=>n.readFile(Je),typeof n.exists=="function"?Je=>n.exists(Je):async()=>!1,{additionalEntries:_,version:I.graph?.version??1});if(D.length>0)throw new co(D);let ye=new Map;for(let Je of B.keys())ye.set(Je,G(Je));let ae=Math.max(ne(I,ye),x.minimumVersion??0);x.changed&&ae<=(I.graph?.version??0)&&(ae=(I.graph?.version??0)+1),M.version=ae;for(let[Je,xe]of B)qc(w,Je,xe,ug);let Ie=await zt(I.composition,I.entryFile,B,w);M.routeId=I.routeId,M.composition=I.composition;let we=Vm(M),Ne=Fu(we,M),Ce=await L(M,we,B,w,U),F=Jg(M,Ne,Ce),K=Kg(Ce),ee=eg(Am(M,we,Ne,{canUpdateTextByKey:F,dynamicDataSummaryByKey:K}),M,Ce),re=Ld({route:I.routeId,composition:I.composition,entryFile:I.entryFile,version:ae,source:y,ast:W?.ast}),Fe=Bd(re);re.ok&&aR(ee,M,re.projection);let ct={...ee,composition:I.composition,...Ie?{styleContext:Ie}:{},pageComposition:Fe},lt=new Set([I.entryFile,...B.keys()]);if(Ie){lt.add(Ie.entryCss.path);for(let Je of Ie.stylesheets)lt.add(Je.path)}let dr={...I,dependencyFiles:lt,graph:M,topology:we,capabilities:Ne,document:ct,pageComposition:Fe,pageCompositionProjection:re.projection,pagePlacementByKey:re.ok?re.projection.placementByKey:null,pagePlacementUnitByKey:re.ok?re.projection.placementUnitByKey:null,pageUnitByKey:re.ok?re.projection.unitByKey:null,pagePlacementsByUnitKey:re.ok?re.projection.placementsByUnitKey:null,documentIndex:qm(ct),detailProjections:Ce,fileVersions:ye,styleContext:Ie};if(x.publish===!1)return dr;cr(f,w);for(let Je of w.keys())m.delete(Je);return P(I,lt),Object.assign(I,dr),I}async function Ae(p){let y=[];for(let x of dR(p))typeof n.exists=="function"&&await n.exists(x)&&y.push({file:x,source:await n.readFile(x)});return y}async function zt(p,y,x,I){let w=[];for(let[U,W]of x){if(tl(U)){w.push(U);continue}for(let ye of pR(W)){let ae=xg(U,ye);ae&&w.push(ae)}}if(!w.length){for(let U of fR(y))if(await Cl(U)){w.push(U);break}}let _=new Map,M=hR(w).slice(0,lg);for(;M.length>0&&_.size<lg;){let U=M.shift();if(_.has(U)||!tl(U))continue;let W=await Ht(U,I);if(W!==null){_.set(U,{path:U,content:W});for(let ye of mR(W)){let ae=xg(U,ye);ae&&!_.has(ae)&&!M.includes(ae)&&M.push(ae)}}}let B=[..._.values()].map(U=>({...U,hash:be(U.content)})),D=B[0];return D?{composition:p,revision:be(JSON.stringify(B.map(({path:U,hash:W})=>({path:U,hash:W})))),entryCss:D,stylesheets:B.slice(1)}:null}async function Ht(p,y){let x=y.get(p);if(x!==void 0)return x;if(!await Cl(p))return null;let I=await n.readFile(p);return qc(y,p,I,ug),I}async function Cl(p){return typeof n.exists=="function"?n.exists(p):!1}function Kg(p){let y=new Map;for(let[x,I]of p)I.dynamicData?.bindings.length&&y.set(x,Ap(I.dynamicData.bindings));return y}function Jg(p,y,x){let I=new Map;for(let[w,_]of p.elements){if(!y.get(w)?.canUpdateText){I.set(w,!1);continue}let B=x.get(w),D=_.textSegments.some(U=>{if(!U.editable)return!1;let W=B?.provenances.get(U.index)??null;return!W||Xg(W)});I.set(w,D)}return I}function Xg(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function So(p,y={}){let x=[...new Set(p)],I=y.affectedCompositionKeys!==void 0,w=I?new Set(y.affectedCompositionKeys):T(x);if(!I&&(w.size===0||!O(x)))for(let D of i.values())Rl(D,x)&&w.add(D.key);let _=!I&&w.size===0&&x.some(yg),M=y.publish===!1?Qc(f,x):void 0,B={rebuiltRoutes:[],failedRoutes:[],...y.publish===!1?{candidateRouteStates:[],candidateSourceCache:M}:{}};for(let D of i.values())if(!(y.excludedCompositionKeys?.has(D.key)||!(w.has(D.key)||_)))try{let W=!!D.graph,ye=await n.readFile(D.entryFile),ae=await ue(D.key,ye,{...y,...M?{sourceCache:M}:{}});ae?.graph&&(B.rebuiltRoutes.push({documentChanged:W,composition:D.composition,routeId:D.routeId,version:ae.graph.version}),B.candidateRouteStates?.push({composition:D.composition,key:D.key,routeId:D.routeId,state:ae}))}catch(W){B.failedRoutes.push({...sg(D.routeId,W),composition:D.composition})}return B}function On(p){let y=[...new Set(p)],x=T(y);if(x.size>0&&O(y))return[...x];for(let I of i.values())Rl(I,y)&&x.add(I.key);return[...x]}function zg(p){let y=new Set(On(p));return o.entries.filter(x=>y.has(x.key)).map(x=>x.context)}function Hg(p){return[...new Set(On(p))].sort((x,I)=>x<I?-1:x>I?1:0).map(x=>o.getByKey(x)?.context).filter(x=>x!==void 0)}function Wg(p,y){let x=new Set(On(y)),I=p.provenance?.affectedCompositions??[];if(I.length===0)return x;if([...new Set(I.map(_=>o.resolveContext(_).key))].some(_=>!x.has(_)))throw new Error("History provenance does not match the affected composition index.");return x}function Gg(p,y){let x=p.composition??p.provenance?.initiatingComposition;if(x){let _=o.resolveContext(x);return{context:_.context,key:_.key}}let I=[...new Set(On(y))];if(I.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${I.length}).`);let w=o.getByKey(I[0]);if(!w)throw new Error("Legacy history entry references an unknown affected composition.");return{context:w.context,key:w.key}}function ls(p,y){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:x,version:I}of y.rebuiltRoutes)r.emit({type:"document-changed",composition:x,version:I});for(let{composition:x,message:I}of y.failedRoutes)r.emit({type:"graph-error",composition:x,message:I})}function Rl(p,y){return y.some(x=>p.dependencyFiles.has(x)||p.entryFile===x||p.graph?.fileIndex.has(x))}function wl(p){for(let y of p)a.add(y);c||A()||(c=(async()=>{t="building";let y=!1;try{for(;a.size>0;){if(A())return;await Yg();let x=[...a];a.clear();let I=await Nl(x);if(I.length===0)continue;let w=On(I);for(let B of w){let D=i.get(B)?.composition;D&&r.emit({type:"graph-invalidated",composition:D})}let{rebuiltRoutes:_,failedRoutes:M}=await So(I,{changed:!0});for(let{documentChanged:B,composition:D,version:U}of _)r.emit({type:"graph-ready",composition:D,version:U}),B&&r.emit({type:"document-changed",composition:D,version:U});for(let{composition:B,message:D}of M)y=!0,r.emit({type:"graph-error",composition:B,message:D})}}finally{c=null,t!=="disposed"&&(t=!y&&[...i.values()].some(x=>x.graph)?"ready":"idle"),a.size>0&&wl([])}})())}async function Yg(){for(;d>0;)await new Promise(p=>setTimeout(p,0))}async function Nl(p){let y=[];for(let x of new Set(p)){let I=f.get(x);if(I===void 0){if(m.has(x)&&!await n.exists(x))continue;m.delete(x),y.push(x);continue}try{await n.readFile(x)!==I&&(m.delete(x),y.push(x))}catch(w){if(!sR(w))try{if(await n.exists(x))continue}catch{continue}m.add(x),y.push(x)}}return y}function Pl(p){ag(f,p);for(let y of p)y.exists===!1?m.add(y.file):m.delete(y.file)}function Al(p){m.clear();for(let y of p)m.add(y)}async function Tl(p){let y=await Nl(p);if(y.length===0)return;let x=On(y);for(let _ of x){let M=i.get(_)?.composition;M&&r.emit({type:"graph-invalidated",composition:M})}let{rebuiltRoutes:I,failedRoutes:w}=await So(y,{changed:!0});for(let{documentChanged:_,composition:M,version:B}of I)r.emit({type:"graph-ready",composition:M,version:B}),_&&r.emit({type:"document-changed",composition:M,version:B});for(let{composition:_,message:M}of w)r.emit({type:"graph-error",composition:_,message:M})}async function Zg(p,y){let x=ur(p,y);if(!x?.graph)return;let I=yt(p)??p,w=x.graph.elements.get(I);w&&await Tl([w.sourceFile])}async function Fl(p){let y=new Set;if(p.target.kind==="node"){let x=ur(p.target.key,p.composition),I=yt(p.target.key)??p.target.key,w=x?.graph?.elements.get(I);w&&y.add(w.sourceFile)}else if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&y.add(x.entryFile)}else if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&y.add(x.entryFile)}else if(p.target.kind==="source-file")y.add(p.target.path);else if(p.target.kind==="source-batch")for(let x of p.target.paths)y.add(x);await Tl(y)}async function Qg(p){if(p.params.kind!=="source-edit")return us(p,"invalid-params","source-edit requires source-edit params");for(let y of p.params.edits){let x=iR(y);if(!x.ok)return us(p,x.errorCode,x.message,x.details)}d+=1;try{let y=await rh(p.params.edits);if(!y.ok)return us(p,y.errorCode,y.message,y.details);await Fl(p);let x={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(I=>I.operation==="delete"?{operation:"delete",file:I.path,baseContentHash:I.baseContentHash??null}:{operation:"upsert",file:I.path,baseContentHash:I.baseContentHash??null,content:I.content})};return await Dn({request:p,filePlan:x})}catch(y){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Y(p),error:{code:j.INTERNAL_ERROR,message:Ge(y)}}}finally{d-=1}}async function qg(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return se(p,j.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");d+=1;try{let y=await ta({files:[...p.params.artifact.components.flatMap(I=>I.materialization.files.map(w=>({path:w.pathTemplate,content:w.content}))),...p.params.artifact.pages.flatMap(I=>I.materialization.files.map(w=>({path:w.pathTemplate,content:w.content})))],exists:I=>n.exists(I),readFile:I=>n.readFile(I)});if(!y.ok)return se(p,j.MATERIALIZATION_REJECTED,y.message);let x=await aa({artifact:p.params.artifact,exists:I=>n.exists(I)});return x.ok?await Dn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"overwrite",edits:x.files},output:{kind:"insert-page-resource",package_instance_id:x.packageInstanceId,pages:x.pages},historyPolicy:"none"}):se(p,x.code==="MATERIALIZATION_CONFLICT"?j.MATERIALIZATION_CONFLICT:j.MATERIALIZATION_REJECTED,x.message,x.path?{path:x.path}:void 0)}catch(y){return se(p,j.INTERNAL_ERROR,Ge(y))}finally{d-=1}}async function eh(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return se(p,j.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return se(p,j.PLAN_FAILED,"Complete project file listing is required for page deletion.");d+=1;try{let y=bg(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(y.truncated)return se(p,j.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:y.truncated.reasons});let x=y.files.filter(({path:M})=>/\.(?:tsx?|jsx?)$/.test(M)),I=Object.fromEntries(await Promise.all(x.map(async({path:M})=>[M,await n.readFile(M)]))),w=af({expectedUrlPath:p.params.expectedUrlPath,files:I});if(!w.ok)return se(p,w.code==="HOME_PAGE_LOCKED"?j.HOME_PAGE_LOCKED:w.code==="ROUTE_NOT_FOUND"?j.ROUTE_NOT_FOUND:j.PLAN_FAILED,w.message);let _=await Promise.all(w.edits.map(async M=>({...M,baseContentHash:be(await n.readFile(M.file))})));return Dn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:_},output:{kind:"delete-page-source",deleted_files:w.deletedFiles,updated_files:w.updatedFiles,preserved_shared_files:w.preservedSharedFiles,warnings:w.warnings},historyPolicy:"none"})}catch(y){return se(p,j.INTERNAL_ERROR,Ge(y))}finally{d-=1}}async function th(p,y){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return se(p,j.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(p.params.kind!=="insert-child"&&p.params.kind!=="replace-node"||p.kind!==p.params.kind)return se(p,j.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(p.params.kind==="insert-child"){if(!("kind"in p.params.position)||p.params.position.kind!=="page-composition")return se(p,j.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return se(p,j.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let x=y.document,I=y.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return se(p,j.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return se(p,j.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let w=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!w)return se(p,j.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let _=p.params.kind==="insert-child"?p.params.position:null,M=await ta({files:w.files.map(D=>({path:D.pathTemplate,content:D.content})),exists:D=>n.exists(D),readFile:D=>n.readFile(D)});if(!M.ok)return se(p,j.MATERIALIZATION_REJECTED,M.message);let B=await Ed({manifest:w,generatedRoot:"components/site/generated",controlledFiles:w.files.map(D=>({pathTemplate:D.pathTemplate})),exists:D=>n.exists(D),commit:async D=>{let U=await n.readFile(y.entryFile),W=y.document,ye=y.pageCompositionProjection;if(!W||W.pageComposition?.status!=="supported"||W.version!==p.documentVersion||!ye||ye.status!=="supported"||ye.documentVersion!==W.version)return{ok:!0,data:se(p,j.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let ae=D.entry.path,Ie=uh(D.instanceName),we,Ne=[];if(p.params.kind==="insert-child"){if(!_||!("kind"in _)||_.kind!=="page-composition")return{ok:!0,data:se(p,j.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let ee=ma({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:W.version,expectedDocumentVersion:p.documentVersion,source:U,projection:ye,placementKey:_.placementKey,component:{source:ae,exportName:D.entry.export.kind==="default"?"default":D.entry.export.name,localName:Ie}});if(!ee.ok)return{ok:!0,data:se(p,ms(ee.error.code),ee.error.message,{diagnostics:ee.error.diagnostics})};let re=ee.plan.rewriteStep,Fe;switch(re.kind){case"insert-root-expression":Fe=ui({source:U,locator:re.locator,expectedSourceHash:re.sourceHash,action:{kind:"insert",jsx:re.node.jsx,placement:re.placement,replaceOriginal:re.replaceOriginal}});break;case"insert-child":Fe=Bn({source:U,locator:re.parentLocator,node:re.node,placement:re.placement,...re.anchorLocator?{anchorLocator:re.anchorLocator}:{}});break;default:Fe={ok:!1,source:U,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(re)}`}}}if(!Fe.ok)return{ok:!0,data:se(p,j.AST_PARSE_ERROR,Fe.diagnostic.message)};we=Fe.source}else{let ee=ga({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:W.version,expectedDocumentVersion:p.documentVersion,source:U,projection:ye,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!ee.ok)return{ok:!0,data:se(p,ms(ee.error.code),ee.error.message,{diagnostics:ee.error.diagnostics})};let re=ee.plan.rewriteStep,Fe;switch(re.kind){case"replace-root-expression":Fe=ui({source:U,locator:re.locator,expectedSourceHash:re.sourceHash,action:{kind:"replace",jsx:`<${Ie} />`}});break;case"replace-node":Fe=Lo({source:U,locator:re.locator,node:{jsx:`<${Ie} />`}});break;default:Fe={ok:!1,source:U,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${re.kind}`}}}if(!Fe.ok)return{ok:!0,data:se(p,j.AST_PARSE_ERROR,Fe.diagnostic.message)};let ct=await _l({routeState:y,placementUnitKey:p.target.placementUnitKey,source:U,mutatedSource:Fe.source});we=ct.source,Ne=await Promise.all(ct.files.map(async lt=>({operation:"delete",file:lt,baseContentHash:be(await n.readFile(lt))})))}let Ce=Vn({source:we,moduleSpecifier:v(y.entryFile,ae),imports:D.entry.export.kind==="default"?[{kind:"default",local:Ie}]:[{kind:"named",imported:D.entry.export.name,local:Ie}]});if(!Ce.ok)return{ok:!0,data:se(p,j.AST_PARSE_ERROR,Ce.diagnostic.message)};let F=D.files.map(ee=>({operation:"create-only",file:ee.path,content:ee.content})),K=[{operation:"upsert",file:y.entryFile,content:Ce.source,baseContentHash:be(U)},...F,...Ne];d+=1;try{let ee=await Dn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:K}});return!ee.ok&&ee.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:ee.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:ee}}finally{d-=1}}});return B.ok?B.data:se(p,j.VERSION_STALE,B.error.message,{materializationCode:B.error.code})}async function nh(p,y){if(p.kind!=="move-node"&&p.kind!=="remove-node")return se(p,j.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let x=y.document,I=y.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return se(p,j.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return se(p,j.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let w=await n.readFile(y.entryFile),_=ga({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:x.version,expectedDocumentVersion:p.documentVersion,source:w,projection:I,placementUnitKey:p.target.placementUnitKey,operation:p.kind,targetPlacement:p.kind==="move-node"&&p.params.kind==="move-node"&&"kind"in p.params.target&&p.params.target.kind==="page-composition"?p.params.target:void 0});if(!_.ok)return se(p,ms(_.error.code),_.error.message,{diagnostics:_.error.diagnostics});let M=_.plan.rewriteStep,B;switch(M.kind){case"move-node":B=jn({source:w,locator:M.locator,targetParentLocator:M.targetParentLocator,placement:M.placement,...M.anchorLocator?{anchorLocator:M.anchorLocator}:{}});break;case"remove-node":B=Ln({source:w,locator:M.locator});break;case"remove-root-expression":B=ui({source:w,locator:M.locator,expectedSourceHash:M.sourceHash,action:{kind:"remove"}});break;default:B={ok:!1,source:w,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${M.kind}`}}}if(!B.ok)return se(p,j.AST_PARSE_ERROR,B.diagnostic.message);let D=B.source,U=[];if(p.kind==="remove-node"){let ye=await _l({routeState:y,placementUnitKey:p.target.placementUnitKey,source:w,mutatedSource:D});D=ye.source,U=await Promise.all(ye.files.map(async ae=>({operation:"delete",file:ae,baseContentHash:be(await n.readFile(ae))})))}let W=[{operation:"upsert",file:y.entryFile,content:D,baseContentHash:be(w)},...U];d+=1;try{return await Dn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:W}})}finally{d-=1}}async function _l(p){let y={source:p.mutatedSource,files:[]},x=p.routeState.graph,I=p.routeState.pageCompositionProjection;if(!x||!I||I.status!=="supported"||!n.listFiles)return y;let _=I.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!_)return y;let M=[...x.elements.values()].find(F=>F.sourceFile===p.routeState.entryFile&&F.importedFrom&&C(F.sourceRange,_));if(!M?.importedFrom||!M.exportName)return y;let B=S(M.importedFrom),D="components/site/generated/";if(!B.startsWith(D))return y;let U=B.slice(D.length).split("/")[0];if(!U||!/-[0-9a-f]{8}$/i.test(U))return y;let W=`${D}${U}`;if([...x.elements.values()].filter(F=>F.sourceFile===p.routeState.entryFile&&S(F.importedFrom??"")===B).length!==1)return y;let ae=await n.listFiles({maxFiles:5e3,maxDepth:32}),Ie=Array.isArray(ae)?ae:ae.files;if(!Array.isArray(ae)&&ae.truncated)return y;let we=Ie.map(({path:F})=>F).filter(F=>F===W||F.startsWith(`${W}/`));if(we.length===0||!we.includes(B))return y;for(let{path:F}of Ie)if(!(F===p.routeState.entryFile||F===W||F.startsWith(`${W}/`)))try{if((await n.readFile(F)).includes(U))return y}catch{return y}let Ne=v(p.routeState.entryFile,B),Ce=Un({source:p.mutatedSource,moduleSpecifier:Ne,imports:M.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:M.exportName}]});return Ce.ok?{source:Ce.source,files:we.sort((F,K)=>F.localeCompare(K))}:y}async function rh(p){if(n.getFileInfo){for(let w of p)if(await n.exists(w.path)&&await n.getFileInfo(w.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${w.path}`,details:{path:w.path}}}for(let w of p){if(w.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(w.path))continue;let _=await n.exists(w.path)?await vs(n,w.path):null;if(_?.ok){let M=OC(_.content,w.content);if(!M.ok)return{ok:!1,errorCode:"invalid-params",message:M.message,details:{path:w.path,code:M.code}}}}let y=oh(p);if(y.length===0)return{ok:!0};let x=rR(n,p),I=uo({projectRoot:e.projectRoot,fileSystem:x,compositions:[...i.values()].map(w=>({context:w.composition,entryFile:w.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let w of y){let _=i.get(w)?.composition;if(!_)continue;let M={routeId:_.routeId,..._.effectiveTemplateId!==void 0?{templateId:_.effectiveTemplateId}:{}};await I.initializeComposition(M),I.getDocument(M)}}catch(w){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Ge(w)}`,details:{compositionKeys:y}}}finally{I.dispose()}return{ok:!0}}function oh(p){return p.map(x=>x.path).some(yg)?[...i.keys()]:[]}function us(p,y,x,I){let w=lo(y);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Y(p),error:{code:w,message:x,...I?{details:I}:{}}}}async function ds(p){let y=[];for(let x of new Set(p))y.push(await ih(x));return y}async function ih(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,G(p)),exists:!1};let x=await n.readFile(p);return{file:p,content:x,version:Math.max(1,G(p)),exists:!0,sha256:be(x)}}async function Ol(p,y,x,I){if(!e.historyStore)return null;let w=new Map(y.map(B=>[B.file,B])),_=new Map(x.map(B=>[B.file,B])),M=[...new Set([...w.keys(),..._.keys()])].sort().map(B=>{let D=w.get(B),U=_.get(B);return{path:B,preDigest:D?.exists===!1||!D?null:be(D.content),postDigest:U?.exists===!1||!U?null:be(U.content)}});return{schemaVersion:2,transactionId:`${p}:${I.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:I,files:M}}async function Ml(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Mn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function fs(p,y){let x=[];try{for(let I of p)await Dl(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),x.push(I.file)}catch(I){let w=await sh(y.filter(_=>x.includes(_.file)));return w.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Ge(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${w.failedFiles.join(", ")}: ${Ge(I)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(ah)}}async function Dl(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function sh(p){let y=[];for(let x of p)try{await Dl(x),typeof n.bumpVersion=="function"&&n.bumpVersion(x.file)}catch{y.push(x.file)}return y.length===0?{ok:!0}:{ok:!1,failedFiles:y}}function ah(p){let y=p.exists!==!1;return{file:p.file,content:y?p.content:"",version:p.version,exists:y,...y?{sha256:be(p.content)}:{}}}async function Dn(p){return h.runExclusive(()=>ch(p))}async function ch(p){let y=p.filePlan.edits.map(F=>F.file),x=o.resolveSelector(p.request.composition),I=x.context,w=p.historyPolicy==="none"?void 0:{initiatingComposition:I,affectedCompositions:Hg(y)},_=await ds(y),M=new Map(_.filter(F=>F.exists!==!1).map(F=>[F.file,F.content])),B=Bl(),D=new Map(f),U=new Set(m),W=new Set([...i.values()].filter(F=>p.filePlan.edits.some(K=>K.operation==="delete"&&K.file===F.entryFile)).map(F=>F.key)),ye=p.filePlan.edits.map(F=>F.operation==="delete"?{file:F.file,content:"",version:0,exists:!1}:{file:F.file,content:F.content,version:0,exists:!0,sha256:be(F.content)}),ae={operationId:p.filePlan.operationId,intents:p.filePlan.edits.map(F=>F.operation==="delete"?{kind:"delete",path:F.file}:{kind:F.operation==="create-only"?"create-only":"upsert",path:F.file,content:F.content})},Ie=null,we=!1,Ne=await zi({overlay:M,exists:F=>n.exists(F),plan:ae,buildCandidate:async({plan:F})=>({plan:F}),prepareHistory:async()=>{let F=p.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(p.request.composition).context,operationId:p.request.id,kind:p.request.kind,target:p.request.target,preSnapshots:_,postSnapshots:ye,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...w?{provenance:w}:{}}),K=F?.historyTransition?F.historyTransition:e.historyStore?KC(await e.historyStore.readIndex()):null;if(e.historyStore&&!K)throw new Error("Durable history did not provide an exact index transition.");return Ie=await Ol(p.request.id,_,ye,K),Ie=await Ml(Ie),{history:F,historyTransition:K}},reverify:async()=>{},writeCandidate:async()=>{let F=await u.executeFilePlan(p.filePlan);if(!F.ok)throw new Zi(F);return{postSnapshots:await ds(F.affectedFiles),affectedFiles:F.affectedFiles,internalResultVersion:F.resultVersion}},validateCandidate:async({candidate:F,receipt:K})=>{let ee=await So(K.affectedFiles,{changed:!0,minimumVersion:K.internalResultVersion,publish:!1,excludedCompositionKeys:W});if(ee.failedRoutes.length>0)throw new Fn(ee.failedRoutes);let re=$l(B,ee.candidateRouteStates??[]),Fe=jl(re,x.key);return{...F,rebuild:ee,routeSnapshots:re,resultVersion:Fe,...mg(p.selectionRef,re.map(ct=>ct.state.document))?{selectionRef:mg(p.selectionRef,re.map(ct=>ct.state.document))}:{}}},publishCandidate:async({candidate:F,history:K,receipt:ee})=>{K?.history&&(await l.publishPrepared(K.history),we=!0);let re=F.resultVersion??ee.internalResultVersion;return{composition:I,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:re,affectedFiles:ee.affectedFiles,...p.output?{output:p.output}:{},...F.selectionRef?{selectionRef:F.selectionRef}:{}}},swapCandidate:({candidate:F,receipt:K})=>{F.routeSnapshots&&Eo(F.routeSnapshots),F.rebuild?.candidateSourceCache&&cr(f,F.rebuild.candidateSourceCache),Pl(K.postSnapshots)},finalizeCandidate:async()=>{await Mn(Ie);for(let F of W)i.delete(F)},emitCommitted:({candidate:F,published:K})=>{ls(K,F.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:F,receipt:K})=>{if(we)throw new Error("history was published before transaction finalization failed");if(K){let ee=await fs(_,K.postSnapshots);if(!ee.ok)throw new Error(ee.reason)}Eo(B),cr(f,D),Al(U),F?.history&&await l.discardPrepared?.(F.history),await Mn(Ie)}});if(Ne.ok)return Ne.published;if(Ne.stage==="precheck"||Ne.stage==="build")try{await Mn(Ie)}catch(F){let K=await vo(Ge(F));return se(p.request,K,"Unable to clear an uncommitted transaction journal.")}if(Ne.recoveryRequired){let F=await vo(Ne.reason);return se(p.request,F===j.RECOVERY_PERSIST_FAILED?F:j.ROLLBACK_FAILED,Ne.reason)}let Ce=Ne.error;return Ce instanceof Zi?{...se(p.request,lo(Ce.result.errorCode),Ce.result.reason),...Ce.result.affectedFiles?{affectedFiles:Ce.result.affectedFiles}:{}}:Ce instanceof Fn?se(p.request,j.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Zc(Ce.failedRoutes)}`,{failedRoutes:Ce.failedRoutes}):se(p.request,Ul(Ne.stage),Ge(Ce))}async function Ll(p){return h.runExclusive(async()=>{let y=p==="undo"?await l.prepareUndo():await l.prepareRedo();return y?lh(p,y):{composition:o.entries[0].context,requestId:p,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:j.INTERNAL_ERROR,message:p==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function lh(p,y){let x=y.entry,I=p==="undo"?x.preSnapshots:x.postSnapshots,w=p==="undo"?x.postSnapshots:x.preSnapshots,_=I.map(K=>K.file),{context:M,key:B}=Gg(x,_),D=await ds(_),U=new Map(D.filter(K=>K.exists!==!1).map(K=>[K.file,K.content])),W=ve(B),ye=Bl(),ae=new Map(f),Ie=new Set(m),we=null,Ne=!1,Ce,F=await zi({overlay:U,plan:{operationId:`${p}:${x.operationId}`,intents:I.map(K=>K.exists===!1?{kind:"delete",path:K.file}:{kind:"upsert",path:K.file,content:K.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(we=await Ol(`${p}:${x.operationId}`,D,I,y.historyTransition),we=await Ml(we),y),reverify:async()=>{},writeCandidate:async()=>{let K=await fs(I,w);if(!K.ok)throw new Error(K.reason);return{snapshots:K.snapshots}},validateCandidate:async({candidate:K})=>{Ce=Wg(x,_);let ee=await So(_,{changed:!0,minimumVersion:W+1,publish:!1,affectedCompositionKeys:Ce});if(ee.failedRoutes.length>0)throw new Fn(ee.failedRoutes);let re=$l(ye,ee.candidateRouteStates??[]),Fe=jl(re,B);return{...K,rebuild:ee,routeSnapshots:re,resultVersion:Fe}},publishCandidate:async({candidate:K,history:ee})=>{if(!ee)throw new Error("history cursor intent is missing");await l.publishPrepared(ee),Ne=!0;let re=K.resultVersion??W+1;return{composition:M,requestId:p,kind:x.kind,target:x.target,ok:!0,resultVersion:re,affectedFiles:_,...x.output?{output:x.output}:{}}},swapCandidate:({candidate:K,receipt:ee})=>{K.routeSnapshots&&Eo(K.routeSnapshots),K.rebuild?.candidateSourceCache&&cr(f,K.rebuild.candidateSourceCache),Pl(ee.snapshots)},finalizeCandidate:async()=>{await Mn(we)},emitCommitted:({candidate:K,published:ee})=>ls(ee,K.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:K,receipt:ee})=>{if(Ne)throw new Error("history cursor was published before transaction finalization failed");if(ee){let re=await fs(w,ee.snapshots);if(!re.ok)throw new Error(re.reason)}Eo(ye),cr(f,ae),Al(Ie),K&&await l.discardPrepared?.(K),await Mn(we)}});if(F.ok)return F.published;if(F.stage==="precheck"||F.stage==="build")try{await Mn(we)}catch(K){let ee=await vo(Ge(K));return{composition:M,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:W,error:{code:ee,message:"Unable to clear an uncommitted transaction journal."}}}if(F.recoveryRequired){let K=await vo(F.reason);return{composition:M,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:W,affectedFiles:_,error:{code:K===j.RECOVERY_PERSIST_FAILED?K:j.ROLLBACK_FAILED,message:F.reason}}}return{composition:M,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:W,affectedFiles:_,error:{code:F.error instanceof Fn?j.ROUTE_REBUILD_FAILED:Ul(F.stage),message:Ge(F.error),...F.error instanceof Fn?{details:{failedRoutes:F.error.failedRoutes}}:{}}}}function Bl(){return[...i.values()].map(p=>({composition:p.composition,key:p.key,routeId:p.routeId,state:{...p,dependencyFiles:new Set(p.dependencyFiles),fileVersions:new Map(p.fileVersions)}}))}function jl(p,y){return p.find(I=>I.key===y)?.state.graph?.version??o.initialVersions.get(y)??0}function $l(p,y){let x=new Map(p.map(I=>[I.key,I]));for(let I of y)x.set(I.key,I);return[...x.values()]}function Eo(p){for(let y of i.values())k(y);for(let y of p){let x={...y.state,dependencyFiles:new Set(y.state.dependencyFiles),fileVersions:new Map(y.state.fileVersions)};i.set(y.key,x),P(x,x.dependencyFiles)}}async function ps(p){let y=i.get(p);if(!y)throw new Error(`Composition not found: ${p}`);if(y.graph)return;let x=await n.readFile(y.entryFile);await ue(p,x)}function ur(p,y){let x=i.get(o.resolveSelector(y).key)??null;return!x||!Vl(x,p)?null:x}function Vl(p,y){if(p.documentIndex?.entriesByKey.has(y)||p.graph?.elements.has(y))return!0;let x=yt(y);return x&&x!==y?p.graph?.elements.has(x)===!0:!1}function se(p,y,x,I){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Y(p),error:{code:y,message:x,...I?{details:I}:{}}}}function Ul(p){return p==="validate"?j.ROUTE_REBUILD_FAILED:p==="publish"?j.HISTORY_COMMIT_FAILED:j.WRITE_IO_ERROR}async function vo(p){if(g=!0,!l.markRecoveryRequired)return j.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),j.RECOVERY_REQUIRED}catch{return j.RECOVERY_PERSIST_FAILED}}function uh(p){let x=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return x?`Prefab${x}`:"GeneratedPrefab"}function ms(p){return p==="VERSION_STALE"?j.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?j.CROSS_PAGE_MOVE_UNSUPPORTED:j.UNSUPPORTED_OPERATION}async function Kl(p){if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await ps(x.key),x):se(p,j.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await ps(x.key),x):se(p,j.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return se(p,j.UNSUPPORTED_OPERATION,`${p.kind} source target execution is not implemented yet.`);let y=i.get(o.resolveSelector(p.composition).key)??null;return y?(y.graph||await ps(y.key),Vl(y,p.target.key)?y:se(p,j.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):se(p,j.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),f.clear(),m.clear()},registerComposition(p,y){let x=o.register({context:p,entryFile:y}),I=i.get(x.key);if(I?.entryFile===y)return;I&&k(I);let w=pg(x.context,y);i.set(x.key,w),P(w,w.dependencyFiles),r.emit({type:"graph-invalidated",composition:x.context})},unregisterComposition(p){let y=o.resolveSelector(p),x=i.get(y.key);x&&(k(x),i.delete(y.key),o.unregister(y.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:y.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let y=o.resolveSelector(p),x=i.get(y.key);if(!x)throw new Error(`Composition not registered: ${y.key}`);if(x.graph)t="ready";else{t="building";try{let I=await n.readFile(x.entryFile);await ue(y.key,I),t="ready",r.emit({type:"graph-ready",composition:y.context,version:i.get(y.key)?.graph?.version??0})}catch(I){throw t="idle",r.emit({type:"graph-error",composition:y.context,message:Ge(I)}),I}}},getDocument(p){let y=o.resolveSelector(p),x=i.get(y.key);if(!x)throw new Error(`Composition not registered: ${y.key}`);if(!x.document)throw new Error(`Composition not built: ${y.key}`);return x.document},async getHistoryStatus(){await E;let p=await l.getStatus?.();return p?{...p,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(p,y,x){let I=ur(p,y),w=yt(p)??p;if(I?.graph&&I.topology&&I.capabilities&&I.detailProjections){let _=I.detailProjections.get(w);if(_){let M=I.graph.elements.get(w);if(!M)throw new Error(`Key not found: ${p}`);let B=GC(p,w,x),D=new Map;if(_.isRepeat&&B?.instanceIndex!==void 0)for(let ye of M.attributes??[])D.set(ye.name,kc({file:M.sourceFile,source:f.get(M.sourceFile)??"",element:M,propertyName:ye.name,selectionRef:B,graph:I.graph,sources:f}));let U=Pm({element:M,graph:I.graph,source:f.get(M.sourceFile),documentVersion:I.graph.version,selectionRef:x,isRepeat:_.isRepeat,propertyProvenance:_.propertyProvenances,repeatTargets:D}),W=Fm(w,I.graph,I.topology,I.capabilities,_.textSources,_.provenances,_.dynamicData,U);return p===w?W:og(W,p,I.document??null,I.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,y){let x=ur(p,y),I=yt(p)??p;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let w=x.detailProjections.get(I);if(w){let _=Tm(I,x.graph,x.topology,x.capabilities,w.textSources,w.writeTarget,w.provenances,w.conditional,w.componentSemantic,w.styleSource,w.dynamicData);return p===I?_:rg(_,p,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,y){let x=ur(p,y),I=yt(p)??p;if(!x?.graph)throw new Error(`Key not found: ${p}`);let w=x.graph.elements.get(I);if(!w)throw new Error(`Key not found: ${p}`);let _=f.get(w.sourceFile);if(_===void 0)throw new Error(`Source not loaded: ${w.sourceFile}`);return Vs({key:I,route:{composition:x.composition,routeId:x.routeId,graph:x.graph,source:_}})},refreshSourceForKey:Zg,async execute(p){if(await E,g)return se(p,j.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return Qg(p);if(p.kind==="insert-page-resource")return qg(p);if(p.kind==="delete-page-source")return eh(p);let y=await Kl(p);if("ok"in y)return y;await Fl(p);let x=await Kl(p);if("ok"in x)return x;let I=x;if(p.target.kind==="page-unit"){let B=p;return p.kind==="insert-child"||p.kind==="replace-node"?th(B,I):p.kind==="move-node"||p.kind==="remove-node"?nh(B,I):se(p,j.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}if(!I.graph||!I.topology||!I.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Y(p),error:{code:p.target.kind==="route"?j.ROUTE_NOT_FOUND:j.NODE_NOT_FOUND,message:p.target.kind==="route"?"Composition not ready for route target.":p.target.kind==="node"?`Target key not found: ${p.target.key}`:`${p.kind} source target execution is not implemented yet.`}};let w=lR(I,I.graph,I.capabilities,f,i),_=await new Fi(w).plan(p);if(!_.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Y(p),error:{code:lo(_.errorCode),message:_.reason}};let M=_.plan;if(M.steps.length===0)return p.kind==="set-props"?{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Y(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Y(p),error:{code:j.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};d+=1;try{if(M.steps.some(D=>D.type==="invoke-external-adapter")){let D=await u.execute(M);if(!D.ok)return se(p,lo(D.errorCode),D.reason);let U={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(Y(p),D.resultVersion),affectedFiles:D.affectedFiles,...D.selectionRef?{selectionRef:D.selectionRef}:{}};return ls(U,{rebuiltRoutes:[],failedRoutes:[]}),U}let B=await u.prepareRewritePlan(M);return B.ok?await Dn({request:p,filePlan:B.filePlan,...B.selectionRef?{selectionRef:B.selectionRef}:{}}):se(p,lo(B.errorCode),B.reason)}catch(B){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Y(p),error:{code:j.INTERNAL_ERROR,message:Ge(B)}}}finally{d-=1}},async undo(p){if(await E,g)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:ve(o.entries[0].key),error:{code:j.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};d+=1;try{return await Ll("undo")}finally{d-=1}},async redo(p){if(await E,g)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:ve(o.entries[0].key),error:{code:j.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};d+=1;try{return await Ll("redo")}finally{d-=1}},notifyFileChanged(p){wl([p])},getAffectedCompositions(p){return zg(p)},subscribe(p){return r.subscribe(p)}}}function sR(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function aR(e,t,n){let r=new Map,o=new Map,i=(u,f,m)=>{let d=u.get(f)??new Set,g=d.size;return d.add(m),u.set(f,d),d.size!==g},s=(u,f)=>{if(!u.importedFrom)return!1;if(u.exportName==="default")return i(o,u.importedFrom,f);let m=i(r,`${u.importedFrom}#${u.tag}`,f);return u.exportName&&u.exportName!==u.tag&&(m=i(r,`${u.importedFrom}#${u.exportName}`,f)||m),m},a=u=>r.get(`${u.sourceFile}#${u.componentName}`)??o.get(u.sourceFile);for(let u of t.elements.values()){if(u.sourceFile!==n.entryFile||!u.importedFrom||!/^[A-Z]/.test(u.tag))continue;let f=n.placements.find(d=>d.members.some(g=>g.sourceRange!==null&&el(u.sourceRange,g.sourceRange)));if(!f)continue;let m=f.placementUnitKey;s(u,m)}let c=!0;for(;c;){c=!1;for(let u of t.elements.values()){if(u.sourceFile===n.entryFile||!u.importedFrom||!/^[A-Z]/.test(u.tag))continue;let f=a(u);if(f)for(let m of f)c=s(u,m)||c}}let l=n.placements.find(u=>u.placementKey===n.container.placementKey&&u.relation==="append");for(let u of e.entries){let f=yt(u.key)??u.key,m=t.elements.get(u.key)??t.elements.get(f);if(!m)continue;if(m.sourceFile===n.entryFile){if(n.container.sourceRange&&el(m.sourceRange,n.container.sourceRange)&&l){u.pageCompositionUnitKey=l.placementUnitKey;continue}let h=n.placements.find(E=>E.members.some(S=>S.sourceRange!==null&&(el(m.sourceRange,S.sourceRange)||cR(S.sourceRange,m.sourceRange))));if(h){u.pageCompositionUnitKey=h.placementUnitKey;continue}}let d=r.get(`${m.sourceFile}#${m.componentName}`);if(d){d.size===1&&(u.pageCompositionUnitKey=d.values().next().value);continue}let g=o.get(m.sourceFile);g?.size===1&&(u.pageCompositionUnitKey=g.values().next().value)}}function el(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function cR(e,t){return hg(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&hg(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function hg(e,t,n,r){return e!==n?e-n:t-r}function lR(e,t,n,r,o){let i=new Map,s=new Map,a=(u,f)=>{if(s.has(u))return;s.set(u,f);let m=t.elements.get(u);for(let d of m?.childKeys??[])a(d,f)};for(let u of t.regions)if(u.kind==="repeat-region")for(let f of u.childKeys)i.set(f,u.ownerKey),a(f,u.ownerKey);return{getNode(u){let f=c(u),m=t.elements.get(f.baseKey);return m?l(u,m):null},getChildNodes(u){let f=c(u),d=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(d)return d.map(h=>{let E=yt(h)??h,S=t.elements.get(E);return S?l(h,S):null}).filter(h=>h!==null);let g=t.elements.get(f.baseKey);return g?g.childKeys.map(h=>{let E=t.elements.get(h);return E?l(h,E):null}).filter(h=>h!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,f])=>({file:u,content:f}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let f=c(u),m=n.get(f.baseKey);return m?{...m,key:u,constraints:m.constraints.map(d=>({...d})),...m.editModes?{editModes:{...m.editModes}}:{}}:{composition:e.composition,key:u,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(u){return r.get(u)??""},getFileVersion(u){return Math.max(e.fileVersions.get(u)??0,t.version)},getRouteEntryFile(u){return e.routeId===u?e.entryFile:null},getComponentSemantic(u){let f=c(u);return e.detailProjections?.get(f.baseKey)?.componentSemantic??null},getClassNameSource(u){let f=c(u),m=t.elements.get(f.baseKey),d=m?r.get(m.sourceFile):void 0;return!m||d===void 0?null:Vs({key:f.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:d}})},getEditableTextSegmentIndex(u){let f=c(u),d=e.detailProjections?.get(f.baseKey)?.textTargets.keys()?.next();return d&&!d.done?d.value:null},async getTextWriteTarget(u,f){let m=c(u);return Yc(e.detailProjections?.get(m.baseKey)?.textTargets.get(f)??null,m.repeatIndex)},async getElementPropertyWriteTarget(u,f){let m=c(u);return Yc(e.detailProjections?.get(m.baseKey)?.elementPropertyTargets.get(f)??null,m.repeatIndex)},getPropertyState(u,f,m){let d=c(u),g=t.elements.get(d.baseKey);if(!g)return null;let E=e.detailProjections?.get(d.baseKey)?.propertyProvenances.get(f);if(E)return E;let S=g.attributes?.find(v=>v.name===f);return S?S.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${f}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:S,target:{kind:"jsx-attribute",file:g.sourceFile,sourceRange:S.sourceRange}}:(g.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${f}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(u,f,m){let d=c(u),g=t.elements.get(d.baseKey);if(!g)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let h=m?{...m,key:d.baseKey}:d.repeatIndex!==null?{key:d.baseKey,instanceIndex:d.repeatIndex}:void 0;return kc({file:g.sourceFile,source:r.get(g.sourceFile)??"",element:g,propertyName:f,selectionRef:h,graph:t,sources:r})},getTextProvenance(u,f){let m=c(u);return e.detailProjections?.get(m.baseKey)?.provenances.get(f)??null}};function c(u){let f=BC(u);return f?{baseKey:f.baseKey,repeatIndex:ng(e.document??null,u,f.baseKey,e.documentIndex)??tg(f)}:{baseKey:u,repeatIndex:null}}function l(u,f){let m=yt(u)??u,d=e.documentIndex?.entriesByKey.get(u);return{key:u,file:f.sourceFile,component:f.componentName,tag:f.tag,structuralPath:f.identity.structuralPath,sourceRange:f.sourceRange,parentKey:d?.parentKey??f.parentKey??void 0,isRepeatRegion:f.boundaryKind==="repeat-region"||s.has(m),isBoundary:!1,importedFrom:f.importedFrom,exportName:f.exportName,isRepeatItemRoot:i.has(m),repeatOwnerKey:i.get(m)??s.get(m),attributes:f.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(h=>({...h}))}:null,resolvedValue:g.resolvedValue}))}}}var uR={"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 lo(e){return uR[e]}function Ge(e){return e instanceof Error&&e.message?e.message:String(e)}function yg(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function dR(e){let t=_n(e);if(!VC.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=>UC.map(a=>`${s}/${a}`))}function fR(e){let n=_n(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function pR(e){return Sg(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function mR(e){return Sg(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Sg(e,t){let n=[];for(let r of e.matchAll(t)){let o=Eg(r[1]??"");o&&n.push(o)}return n}function xg(e,t){let n=Eg(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?_n(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?_n(`${gR(e)}/${n}`):n.startsWith("/")?_n(n.slice(1)):tl(n)?_n(n):null}function Eg(e){return e.split(/[?#]/,1)[0]?.trim()??""}function tl(e){return/\.css$/i.test(e)}function gR(e){let t=_n(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function hR(e){return Array.from(new Set(e))}function _n(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 yR(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 Qi=class{constructor(t){this.options=t,this.fileSystem=new pr(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return ko(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 Co(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return No(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Po(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Ao(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=bR.safeParse(t);if(!n.success)return{result:Io(t,n.error.issues.map(i=>i.message))};let r=new pr(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:dn(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=SR.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>ER(l,t.kind==="source-edit")),changedCompositions:o.getAffectedCompositions(a.map(l=>l.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:c.patches.map(l=>l.path),composition:i.composition,at:new Date().toISOString()}),{result:s,patchPlan:c}}finally{o.dispose()}}dispose(){this.engine.dispose()}createEngine(t,n={}){let r=n.emitEvents??!0;return uo({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Ro(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}:{}})}};function ER(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:be(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:be(e.before)},fullContent:e.after}}function vR(e){return new Qi(e)}import{SiteEditOperationRequestSchema as CR}from"@vcp-dev/contracts";import kt from"node:fs/promises";import Ye from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as IR,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as kR}from"@vcp-dev/contracts";var qi=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=uo({...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 No(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Po(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Ao(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 kt.readFile(Ye.join(n,r),"utf8")},async readFileBytes(r){return kt.readFile(Ye.join(n,r))},async getFileInfo(r){let o=Ye.join(n,...r.split("/"));try{let i=await kt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await Wo(Ye.join(n,r),o)},async createExclusive(r,o){let i=Ye.join(n,r);await kt.mkdir(Ye.dirname(i),{recursive:!0});let s=await kt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await kt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await kt.rm(Ye.join(n,r),{force:!0});let o=r.replace(/\\/g,"/"),i=["components/site/generated","src/components/site/generated"].find(c=>o.startsWith(`${c}/`));if(!i)return;let s=Ye.join(n,i),a=Ye.dirname(Ye.join(n,o));for(;a!==s&&a.startsWith(`${s}${Ye.sep}`);){try{await kt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Ye.dirname(a);continue}break}a=Ye.dirname(a)}},async exists(r){try{return await kt.access(Ye.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...kR,...IR],i=[],s=new Set,a=new Set,c=0;for(let f of o)await u(f,i,1);let l=i.sort((f,m)=>f.path.localeCompare(m.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(f,m,d){if(r.maxDepth!==void 0&&d>r.maxDepth){a.add("max-depth");return}let g=Ye.join(n,...f.split("/")),h;try{h=await kt.lstat(g)}catch{return}if(h.isSymbolicLink())return;if(h.isFile()){let S=h.ino>0?`${String(h.dev)}:${String(h.ino)}`:null;if(S&&s.has(S))return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+h.size>r.maxTotalBytes){a.add("max-total-bytes");return}S&&s.add(S),m.push({path:f,sizeBytes:h.size}),c+=h.size;return}if(!h.isDirectory())return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}let E=await kt.readdir(g,{withFileTypes:!0});for(let S of E)S.isSymbolicLink()||await u(`${f}/${S.name}`,m,d+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function nl(e){return new qi(e)}var es=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=nl({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Ro(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:ko(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:Co(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=CR.safeParse(r);if(!o.success)return Io(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:dn(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:dn(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:dn(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 RR(e){return new es(e)}import{createHash as wR,randomUUID as ml}from"node:crypto";import Pe from"node:fs/promises";import Te from"node:path";var xt=1,ol=1,NR=2,PR="index.json",AR="recovery.json",TR="transaction-journal.json",FR="document-version.json",ns={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},Q={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"},te=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};async function Tg(e,t={}){let n=zR(e),r=GR(t.limits),o=rl(n),i=HR(n),s=await qe(i),a=await qe(o)||s;a||(await BR(n),await jR(n)),a||await YR(n);let c=await it(n),l=new Set(a?(await as(n)).map(f=>f.stageId):[]);a||await fo(n,c.entryIds);let u=async()=>{if(await qe(o)||s)throw new te(Q.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Pg(n)},async writeDocumentVersion(f){if(await u(),!Number.isInteger(f)||f<0)throw new te(Q.INVALID_SCHEMA,"document version must be a non-negative integer");let m=await Pg(n);await po(Bg(n),{schemaVersion:1,version:Math.max(m,f)})},async stageAppend(f,m={}){await u();let d=await Ig(f,r),g={schemaVersion:ol,stageId:ml(),entryId:d.entryId,blobIds:d.blobs.map(h=>h.digest)};try{await kg(n,d),await MR(n,g,m.durableManifest!==!1)}catch(h){try{await Rg(n,g)}catch(E){throw new te(Q.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:E})}throw h}return{stageId:g.stageId,entryId:g.entryId,blobIds:g.blobIds}},async discardStage(f){await u(),cl(f);let m=await sl(n,f);m&&await Rg(n,m)},async previewStagedAppend(f,m){return await u(),(await vg(n,r,f,m)).transition},async previewCursor(f,m){await u();let d=await it(n);return ll(d,m),il(f,d.entryIds.length),Fg(d,d.entryIds,f)},async publishStagedAppend(f,m,d){if(await u(),rs(f,"entryId"),d){cl(d);let h=await sl(n,d);if(!h||h.entryId!==f)throw new te(Q.INVALID_SCHEMA,"history stage does not match the published entry")}let g=await vg(n,r,f,m);return Ng({rootDir:n,previousDigest:g.current.digest,entryIds:g.entryIds,cursor:g.cursor,afterWrite:async()=>{d?await os(n,d):await LR(n,f),await fo(n,g.entryIds)}})},async append(f){await u();let m=await it(n),d=await Ig(f,r),g=[...m.entryIds];m.cursor<g.length-1&&g.splice(m.cursor+1),g.push(d.entryId);try{await kg(n,d);let h=await _g(n,g,r);return await hl(n,h.entryIds,h.cursor),await fo(n,h.entryIds),it(n)}catch(h){throw await fo(n,m.entryIds),h}},async readEntry(f){return rs(f,"entryId"),go(n,f)},async readBlob(f){rs(f,"blobId");let m=await kl(n,f),d=await cn(m,Q.NOT_FOUND,"blob");return yl(d,f,m),d},async readIndex(){return it(n)},async readStatus(){let f=await it(n);return{canUndo:f.undoIds.length>0,canRedo:f.redoIds.length>0,undoDepth:f.undoIds.length,redoDepth:f.redoIds.length,cursor:f.cursor,recoveryRequired:await qe(o)||await qe(i)}},async readUndoRedoIds(){let f=await it(n);return{undoIds:f.undoIds,redoIds:f.redoIds,currentId:f.currentId}},async setCursor(f,m){await u();let d=await it(n);return ll(d,m),il(f,d.entryIds.length),Ng({rootDir:n,previousDigest:d.digest,entryIds:d.entryIds,cursor:f})},async markRecoveryRequired(f){await qe(o)||await po(rl(n),{schemaVersion:xt,reason:WR(f),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Pe.rm(rl(n),{force:!0})},async readTransactionJournal(){return await qe(i)?ts(i):null},async writeTransactionJournal(f){await u(),jg(f);try{await po(i,f)}catch(d){let g=await ts(i).catch(()=>null);if(g&&Buffer.from(st(g)).equals(Buffer.from(st(f))))return;throw g?new te(Q.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:d}):d}let m=await ts(i);if(!Buffer.from(st(m)).equals(Buffer.from(st(f))))throw new te(Q.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(f){let m=await qe(i)?await ts(i):null;if(m&&m.transactionId!==f)throw new te(Q.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Pe.rm(i,{force:!0})}catch(d){if(!await qe(i))return;throw d}if(await qe(i))throw new te(Q.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await u();for(let m of l)await os(n,m),l.delete(m);await $R(n);let f=await it(n);await fo(n,f.entryIds)}}}async function vg(e,t,n,r){rs(n,"entryId");let o=await it(e);ll(o,r);let i=await go(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await _g(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:Fg(o,a.entryIds,a.cursor)}}function Fg(e,t,n){return il(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:_R(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function _R(e,t){return ln(st({schemaVersion:xt,entryIds:e,cursor:t}))}function il(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new te(Q.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function OR(e){if(!Ct(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!at(e.expectedIndexDigest)||!at(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!at(n)?!1:t===-1?n===null:at(n)}async function Ig(e,t){if(!e.kind.trim())throw new te(Q.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new te(Q.INVALID_JSON,"history blob name must not be empty");let l=XR(c.data),u=ln(l);n.push({name:c.name,bytes:l,digest:u,sizeBytes:l.byteLength}),r.push({name:c.name,digest:u,sizeBytes:l.byteLength})}let o={schemaVersion:xt,kind:e.kind,manifest:e.manifest,blobs:r},i=st({...o}),s=ln(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new te(Q.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function kg(e,t){let n=Sl(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Cg(El(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},Il(e,a.digest))),Cg(n,st(r),{kind:"entry",digest:t.entryId},vl(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Cg(e,t,n,r){let o=await fl(e)??(r?await fl(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new te(n.kind==="blob"?Q.BLOB_CORRUPT:Q.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Dg(e,t)}async function _g(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await Mg(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new te(Q.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function MR(e,t,n){gl(t);let r=bl(e,t.stageId);if(n){await po(r,t);return}await JR(r,t)}async function sl(e,t){let n=await fl(bl(e,t));if(n===null)return null;let r=ho(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=gl(r);if(o.stageId!==t)throw new te(Q.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function as(e){let t=[];for(let n of await ss(xl(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);cl(r);let o=await sl(e,r);o&&t.push(o)}return t}async function Rg(e,t){gl(t);let n=await it(e),r=(await as(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await go(e,s);for(let c of a.blobs)i.add(c.digest)}for(let s of r){o.add(s.entryId);for(let a of s.blobIds)i.add(a)}o.has(t.entryId)||await wg(Sl(e,t.entryId),vl(e,t.entryId));for(let s of t.blobIds)i.has(s)||await wg(El(e,s),Il(e,s));await os(e,t.stageId),await pl(yo(e)),await pl(xo(e))}async function os(e,t){await al(bl(e,t)),await DR(e)}async function DR(e){try{await Pe.rmdir(xl(e))}catch(t){if(bo(t)||Ct(t)&&t.code==="ENOTEMPTY")return;throw t}}async function LR(e,t){for(let n of await as(e))n.entryId===t&&await os(e,n.stageId)}async function al(e){if(await Pe.rm(e,{force:!0}),await qe(e))throw new te(Q.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function wg(e,t){await al(e),await al(t)}function gl(e){if(!Ct(e)||e.schemaVersion!==ol||typeof e.stageId!="string"||!Og(e.stageId)||!at(e.entryId))throw new te(Q.INVALID_SCHEMA,"history stage schema is invalid");let t=Lg(e.blobIds,"history stage blobIds");return{schemaVersion:ol,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function cl(e){if(!Og(e))throw new te(Q.INVALID_PATH,"history stageId must be a UUID")}function Og(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 fo(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await go(e,c);for(let u of l.blobs)r.add(u.digest)}for(let c of await as(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=yo(e),i=await ss(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=Ag(c.slice(0,-5));l&&!n.has(l)&&await is(Te.join(o,c))}let s=xo(e),a=await ss(s);for(let c of a){let l=Ag(c);l&&!r.has(l)&&await is(Te.join(s,c))}}async function it(e){let t=cs(e),n=await cn(t,Q.NOT_FOUND,"index"),r=ho(Buffer.from(n).toString("utf8"),"index"),o=VR(r),i=[...o.entryIds],{totalBytes:s}=await Mg(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:xt,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function Mg(e,t){let n=0,r=new Set,o=cs(e),i=await cn(o,Q.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await go(e,s),c=await $g(e,s),l=await cn(c,Q.NOT_FOUND,"entry");n+=l.byteLength;for(let u of a.blobs){if(r.has(u.digest))continue;r.add(u.digest);let f=await kl(e,u.digest),m=await cn(f,Q.NOT_FOUND,"blob");yl(m,u.digest,f),n+=m.byteLength}}return{totalBytes:n}}async function go(e,t){let n=await $g(e,t),r=await cn(n,Q.NOT_FOUND,"entry"),o=ho(Buffer.from(r).toString("utf8"),`entry ${t}`),i=UR(o);if(i.id!==t)throw new te(Q.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(ln(st({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new te(Q.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=await kl(e,a.digest),l=await cn(c,Q.NOT_FOUND,"blob");yl(l,a.digest,c)}return i}async function hl(e,t,n){let r={schemaVersion:xt,digest:ln(st({schemaVersion:xt,entryIds:t,cursor:n})),entryIds:t,cursor:n};await po(cs(e),r)}function ll(e,t){if(t!==void 0&&e.digest!==t)throw new te(Q.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Ng(e){let t=ln(st({schemaVersion:xt,entryIds:e.entryIds,cursor:e.cursor}));try{return await hl(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await it(e.rootDir)}catch(n){let r=await it(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new te(Q.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function BR(e){await Pe.mkdir(e,{recursive:!0}),await Pe.mkdir(yo(e),{recursive:!0}),await Pe.mkdir(xo(e),{recursive:!0}),await Pe.mkdir(mo(e),{recursive:!0})}async function jR(e){await Pe.rm(mo(e),{recursive:!0,force:!0}),await Pe.mkdir(mo(e),{recursive:!0})}async function $R(e){let t=mo(e);await Pe.mkdir(t,{recursive:!0});for(let n of await ss(t))n!=="stages"&&await Pe.rm(Te.join(t,n),{recursive:!0,force:!0})}function VR(e){if(!Ct(e))throw new te(Q.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==xt)throw new te(Q.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Lg(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new te(Q.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!at(o))throw new te(Q.INDEX_CORRUPT,"index digest is invalid");let i=ln(st({schemaVersion:xt,entryIds:t,cursor:r}));if(o!==i)throw new te(Q.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:xt,digest:o,entryIds:t,cursor:r}}function UR(e){if(!Ct(e))throw new te(Q.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==xt)throw new te(Q.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!at(t))throw new te(Q.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new te(Q.ENTRY_CORRUPT,"entry kind is invalid");let r=dl(e.manifest,"entry.manifest"),o=KR(e.blobs);return{id:t,schemaVersion:xt,kind:n,manifest:r,blobs:o}}function KR(e){if(!Array.isArray(e))throw new te(Q.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!Ct(t))throw new te(Q.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new te(Q.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!at(o))throw new te(Q.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new te(Q.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function po(e,t){await Dg(e,st(t))}async function JR(e,t){let n=Te.dirname(e),r=Te.basename(e),o=Te.join(n,`.${r}.${process.pid}.${ml()}.tmp`);await Pe.mkdir(n,{recursive:!0});try{await Pe.writeFile(o,st(t),{flag:"wx"}),await Pe.rename(o,e)}finally{await is(o)}}async function Dg(e,t){let n=Te.dirname(e),r=Te.basename(e),o=Te.join(n,`.${r}.${process.pid}.${ml()}.tmp`);await Pe.mkdir(n,{recursive:!0});try{let i=await Pe.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await Pe.rename(o,e),await pl(n)}finally{await is(o)}}function st(e){return Buffer.from(JSON.stringify(ul(e)),"utf8")}function ul(e){if(Array.isArray(e))return e.map(t=>ul(t));if(Ct(e)){let t={};for(let n of Object.keys(e).sort())t[n]=ul(e[n]);return t}return e}function ho(e,t){try{return JSON.parse(e)}catch(n){throw new te(Q.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function dl(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=>dl(n,t));if(Ct(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=dl(o,t);return n}break}throw new te(Q.INVALID_JSON,`${t} must be JSON-serializable`)}function Lg(e,t){if(!Array.isArray(e))throw new te(Q.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!at(n))throw new te(Q.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function rs(e,t){if(!at(e))throw new te(Q.INVALID_PATH,`${t} must be a sha256 digest`)}function at(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function ln(e){return`sha256:${wR("sha256").update(e).digest("hex")}`}function XR(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function cn(e,t,n){try{return await Pe.readFile(e)}catch(r){throw new te(t,`${n} not found: ${e}`,{cause:r})}}async function fl(e){try{return await Pe.readFile(e)}catch(t){if(bo(t))return null;throw t}}function yl(e,t,n){if(ln(e)!==t)throw new te(Q.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function qe(e){try{return await Pe.access(e),!0}catch(t){if(bo(t))return!1;throw t}}async function is(e){try{await Pe.rm(e,{force:!0,recursive:!0})}catch{}}async function pl(e){try{let t=await Pe.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function ss(e){try{return await Pe.readdir(e)}catch(t){if(bo(t))return[];throw t}}function zR(e){if(typeof e!="string"||e.trim().length===0)throw new te(Q.INVALID_ROOT,"history store rootDir must be a non-empty string");return Te.resolve(e)}function cs(e){return Te.join(e,PR)}function rl(e){return Te.join(e,AR)}function HR(e){return Te.join(e,TR)}function Bg(e){return Te.join(e,FR)}async function Pg(e){try{let t=await Pe.readFile(Bg(e),"utf8"),n=ho(t,"document version");if(!Ct(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new te(Q.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(bo(t))return 0;throw t}}async function ts(e){let t=await cn(e,Q.RECOVERY_PENDING,"transaction journal"),n=ho(Buffer.from(t).toString("utf8"),"transaction journal");return jg(n),n}function jg(e){if(!Ct(e)||e.schemaVersion!==NR||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!OR(e.historyTransition)||!Array.isArray(e.files))throw new te(Q.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!Ct(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!at(t.preDigest)||t.postDigest!==null&&!at(t.postDigest))throw new te(Q.INVALID_SCHEMA,"transaction journal file digest is invalid")}function WR(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function yo(e){return Te.join(e,"entries")}function xo(e){return Te.join(e,"blobs")}function mo(e){return Te.join(e,"tmp")}function xl(e){return Te.join(mo(e),"stages")}function bl(e,t){return Te.join(xl(e),`${t}.json`)}function Sl(e,t){return Te.join(yo(e),`${Ug(t)}.json`)}function El(e,t){return Te.join(xo(e),Ug(t))}function vl(e,t){return Te.join(yo(e),`${t}.json`)}function Il(e,t){return Te.join(xo(e),t)}async function $g(e,t){return Vg(Sl(e,t),vl(e,t))}async function kl(e,t){return Vg(El(e,t),Il(e,t))}async function Vg(e,t){return await qe(e)?e:await qe(t)?t:e}function Ug(e){return e.slice(7)}function Ag(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return at(t)?t:null}function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bo(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function GR(e){return{maxEntries:e?.maxEntries??ns.maxEntries,maxSessionBytes:e?.maxSessionBytes??ns.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??ns.maxEntryBytes}}async function YR(e){let t=cs(e);await qe(t)||await hl(e,[],-1)}export{te as FileHistoryStoreError,Or as PageTemplateManagedSourceError,es as PreviewFileSystemSiteEditEngineRuntime,sd as SITE_EDIT_RAW_COLOR_LITERAL_RE,Qi as SnapshotSiteEditEngineRuntime,Gd as computeManagedPageTemplatePaths,RR as createPreviewSiteEditEngineRuntime,vR as createSiteEditEngineRuntime,zd as decodePageTemplateKey,Na as encodePageTemplateId,Yd as isManagedPageTemplateSourcePath,Tg as openFileHistoryStore,IE as resolveManagedPageTemplateComposition,pi as scanManagedPageTemplateCandidates,Qd as scanSiteEditCompositionsFromFiles,Nr as scanSiteEditThemeStyleViolations};