@vcp-dev/site-edit-engine 0.6.2 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +9 -9
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import{SiteEditOperationRequestSchema as Qb,SiteEditPatchPlanSchema as qb}from"@vcp-dev/contracts";function Ft(e){return{requestId:e.requestId,kind:e.kind,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function yr(e,t){return{ok:!1,error:{code:"INVALID_PARAMS",message:t[0]??"Site edit operation request failed contract validation."},data:{requestId:e.id,kind:e.kind,target:e.target,resultVersion:e.documentVersion}}}function xr(e,t){if(!e.pageComposition)throw new Error("RenderDocument is missing the required Page Composition projection.");return{siteId:t.siteId,snapshotId:t.snapshotId,routeId:e.routeId,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 Er(e){return{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:Ep(e.capabilities),provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,dynamicData:e.dynamicData,textSegments:e.textSegments.map(t=>({index:t.index,editable:t.editable,sourceKind:t.source?.kind??null})),boundaryKind:e.boundaryKind}}function Sr(e,t){let n=new Date().toISOString();return e.type==="document-changed"?{type:"site-edit.document.changed",siteId:t.siteId,snapshotId:t.snapshotId,routeId:e.routeId,version:e.version,at:n}:e.type==="operation-completed"?{type:"site-edit.operation.completed",siteId:t.siteId,result:Ft(e.result),at:n}:e.type==="operation-failed"?{type:"site-edit.operation.failed",siteId:t.siteId,requestId:e.requestId,error:e.error,at:n}:e.type==="capability-changed"?{type:"site-edit.capability.changed",siteId:t.siteId,routeId:"",keys:e.keys,at:n}:null}function Ep(e){return{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{composeSiteEditRepeatInstanceKey as VS,getSiteEditSourceDeleteProtectionReason as JS,isSiteEditTextSourcePath as XS,parseSiteEditRepeatInstanceKey as WS,SITE_EDIT_SOURCE_DELETE_CAPABILITY as zS,stripSiteEditRepeatInstanceKeys as Ke}from"@vcp-dev/contracts";import{parse as HS}from"yaml";import So from"node:path";function Rn(e,t,n){return`${e}::${t}::${n}`}var $={NODE_NOT_FOUND:"NODE_NOT_FOUND",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"};import Zo from"@babel/traverse";import*as y from"@babel/types";import{createHash as Cp}from"node:crypto";import*as Za from"@babel/parser";function Mt(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function K(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Mt(t,n,r,o)}}function Wo(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Mt(t,n,r,o)}}var Sp={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function tt(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Za.parse(t,{sourceType:"module",plugins:Sp[n]})}}catch(r){return{ok:!1,source:t,diagnostic:Mt("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function zo(e,t){return tt({source:e,profile:Qa(t.kind)})}function Ho(e,t){return tt({source:e,profile:Qa(t)})}function Qa(e){return"next-app-entry"}function Ot(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*as bp from"@babel/parser";import*as Zt from"@babel/types";import*as br from"node:path";var qa=[".tsx",".ts",".jsx",".js"],Ip=qa.map(e=>`/index${e}`);function ec(e){let t=[];for(let n of e.program.body)Zt.isImportDeclaration(n)&&typeof n.source.value=="string"&&wn(n.source.value)&&t.push(n.source.value),Zt.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&wn(n.source.value)&&t.push(n.source.value),Zt.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&wn(n.source.value)&&t.push(n.source.value);return t}function wn(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function kp(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=br.dirname(e);return br.join(n,t).replace(/\\/g,"/")}async function vp(e,t){for(let n of qa){let r=`${e}${n}`;if(await t(r))return r}for(let n of Ip){let r=`${e}${n}`;if(await t(r))return r}return null}async function tc(e,t,n){let r=await Ir(e,t,n);return r.ok?r.path:null}async function Ir(e,t,n){let r=kp(e,t);try{let o=await vp(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)}}}}}var Yo=(e,t)=>{let n=tt({source:t,profile:Ot({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${Cp("sha256").update(t).digest("hex")}`,ast:n.ast,imports:ec(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};var kr="components/ui";function _t(e){if(!e)return!1;let t=Go(e);return t===kr||t.startsWith(`${kr}/`)||t.includes(`/${kr}/`)||t.endsWith(`/${kr}`)}function Pn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?_t(e.slice(2)):e.startsWith("./")||e.startsWith("../")?_t(Go(`${Rp(t)}/${e}`)):_t(e):!1}function Go(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 Rp(e){let t=Go(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var wp=typeof Zo=="function"?Zo:Zo.default;function ve(e){return{startLine:e.loc?.start.line??0,startColumn:e.loc?.start.column??0,endLine:e.loc?.end.line??0,endColumn:e.loc?.end.column??0}}function Pp(e){return/^[A-Z]/.test(e)}function ni(e){let t=e.openingElement;return y.isJSXIdentifier(t.name)?t.name.name==="Fragment":y.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function qt(e){return y.isJSXFragment(e)}function oc(e){return y.isJSXIdentifier(e.name)?e.name.name:y.isJSXMemberExpression(e.name)?ic(e.name):y.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function ic(e){return y.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:y.isJSXMemberExpression(e.object)?`${ic(e.object)}.${e.property.name}`:e.property.name}function Ap(e){return e.split(".")[0]??e}function Tp(e){let t=e;for(;t;){let n=t.node;if(y.isFunctionDeclaration(n)&&n.id||y.isVariableDeclarator(n)&&y.isIdentifier(n.id))return n.id.name;if(y.isExportDefaultDeclaration(n)){let r=n.declaration;if(y.isFunctionDeclaration(r)&&r.id)return r.id.name;if(y.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function Np(){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 Fp(e){let t=new Map;for(let n of e.program.body){if(!y.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(y.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(y.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(y.isImportSpecifier(o)){let i=y.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function at(e,t=[]){if(y.isIdentifier(e))return t.push(e.name),t;if(y.isObjectPattern(e)){for(let n of e.properties)y.isObjectProperty(n)?at(n.value,t):y.isRestElement(n)&&at(n.argument,t);return t}if(y.isArrayPattern(e)){for(let n of e.elements)n&&(y.isRestElement(n)?at(n.argument,t):at(n,t));return t}return y.isAssignmentPattern(e)?(at(e.left,t),t):(y.isRestElement(e)&&at(e.argument,t),t)}function ht(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function vr(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 Mp(e,t,n){e.set(t,{resolved:!0,value:n})}function ri(e,t){e.set(t,{resolved:!1})}function sc(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n==null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return{kind:"known-empty"};n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return{kind:"known-empty"};n=n[r.index]}return{kind:"resolved",value:n}}function ct(e,t,n){if(y.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!y.isMemberExpression(e))return null;let r=[],o=e;for(;y.isMemberExpression(o);){if(o.computed)if(y.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(y.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&y.isExpression(o.property)){let i=Lt(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(!y.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return y.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:ht(e,t),base:o.name,path:r}:null}function Lt(e,t){if(y.isStringLiteral(e)||y.isNumericLiteral(e)||y.isBooleanLiteral(e))return e.value;if(y.isNullLiteral(e))return null;if(y.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(y.isIdentifier(e)){let n=vr(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(y.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||y.isSpreadElement(r))return;let o=Lt(r,t);if(o===void 0)return;n.push(o)}return n}if(y.isObjectExpression(e)){let n={};for(let r of e.properties){if(!y.isObjectProperty(r)||r.computed||!y.isExpression(r.value))return;let o=null;if(y.isIdentifier(r.key)?o=r.key.name:y.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!y.isIdentifier(r.value))return;let s=vr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Lt(r.value,t);if(i===void 0)return;n[o]=i}return n}if(y.isMemberExpression(e)){let n=ct(e,"",t);if(!n)return;let r=vr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=sc(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(y.isCallExpression(e))return cc(e,t)??void 0}function ac(e,t,n){let r=ct(e,n,t);if(!r)return y.isMemberExpression(e)||y.isBinaryExpression(e)||y.isLogicalExpression(e)||y.isConditionalExpression(e)||y.isCallExpression(e)?{value:ht(e,n),source:null}:null;let o=vr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?sc(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 Qo(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:Np(),parentStack:[],valueScopes:i,importMap:o}}function ei(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of at(o.id))ri(n,s);if(!y.isIdentifier(o.id)||!o.init||!y.isExpression(o.init))continue;let i=Lt(o.init,t);i!==void 0&&Mp(n,o.id.name,i)}}function Op(e){let t=[];for(let n of e){if(y.isVariableDeclaration(n)){t.push(n);continue}y.isExportNamedDeclaration(n)&&n.declaration&&y.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function _p(e,t,n){let r=[],o=0;for(let i of e)if(y.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:ve(i),editable:!0,source:null})}else if(y.isJSXExpressionContainer(i)&&y.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:ve(i),editable:!0,source:null});else if(y.isJSXExpressionContainer(i)&&y.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:ve(i),editable:!0,source:null}):r.push({index:o++,value:ht(s,n),sourceRange:ve(i),editable:!0,source:null})}else if(y.isJSXExpressionContainer(i)&&y.isExpression(i.expression)){let s=ac(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:ve(i),editable:!0,source:s.source})}return r}function Dp(e,t,n){let r=[];for(let o of e.attributes)if(!(!y.isJSXAttribute(o)||!y.isJSXIdentifier(o.name))){if(y.isStringLiteral(o.value)){r.push({name:o.name.name,value:o.value.value,sourceRange:ve(o),source:null});continue}if(y.isJSXExpressionContainer(o.value)&&y.isExpression(o.value.expression)){let i=Lt(o.value.expression,t);if(o.name.name==="className"){let a=typeof i=="string"?i:i===void 0?cc(o.value.expression,t):null;if(a){r.push({name:o.name.name,value:a,sourceRange:ve(o),source:null,resolvedValue:a});continue}}let s=ac(o.value.expression,t,n);if(i!==void 0&&typeof i!="string"&&typeof i!="number"){r.push({name:o.name.name,value:nc(i),sourceRange:ve(o),source:ct(o.value.expression,n,t),resolvedValue:i});continue}if(!s){i!==void 0&&r.push({name:o.name.name,value:nc(i),sourceRange:ve(o),source:ct(o.value.expression,n,t),resolvedValue:i});continue}r.push({name:o.name.name,value:s.value,sourceRange:ve(o),source:s.source})}}return r}function cc(e,t){let n=Qt(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function Qt(e,t){if(y.isStringLiteral(e))return[e.value];if(y.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(y.isNullLiteral(e))return[];if(y.isBooleanLiteral(e))return e.value?null:[];if(y.isIdentifier(e)||y.isMemberExpression(e)){if(y.isIdentifier(e)&&e.name==="undefined")return[];let n=Lt(e,t);return typeof n=="string"?[n]:null}if(y.isConditionalExpression(e)){let n=Qt(e.consequent,t),r=Qt(e.alternate,t);return!n||!r?null:[...n,...r]}if(y.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Lt(e.left,t);return n===!1||n===null?[]:Qt(e.right,t)}if(y.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||y.isSpreadElement(r))return null;let o=Qt(r,t);if(!o)return null;n.push(...o)}return n}if(y.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!y.isObjectProperty(r))return null;let o=jp(r.key);if(!o)return null;n.push(o)}return n}if(y.isCallExpression(e)){let n=Lp(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!y.isExpression(o))return null;let i=Qt(o,t);if(!i)return null;r.push(...i)}return r}return null}function Lp(e){return y.isIdentifier(e)?e.name:y.isMemberExpression(e)&&y.isIdentifier(e.property)?e.property.name:null}function jp(e){return y.isIdentifier(e)?e.name:y.isStringLiteral(e)?e.value:null}function $p(e,t){let n=e.attributes.find(r=>y.isJSXAttribute(r)&&y.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!y.isJSXAttribute(n)||!y.isJSXExpressionContainer(n.value)?null:n.value.expression}function Bp(e,t){for(let n of t){let r=$p(e,n);if(r)return r}return null}function Kp(e){return y.isJSXIdentifier(e.name)?e.name.name:null}function nc(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function Up(e){if(!y.isCallExpression(e)&&!y.isOptionalCallExpression(e))return null;let t=e.callee;return!y.isMemberExpression(t)&&!y.isOptionalMemberExpression(t)||!y.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!y.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function qo(e){return y.isArrowFunctionExpression(e)||y.isFunctionExpression(e)}function Vp(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function Jp(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function rc(e,t,n,r){if(!e||!y.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:ht(e,n),collectionSource:ct(e,n,r)};if(t){let i=t.params[0],s=t.params[1];y.isIdentifier(i)&&(o.itemParamName=i.name),y.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function gt(e,t,n){if(!e)return[];if(y.isJSXElement(e)){if(ni(e))return Ar(e.children,t,n);let r=wr(e,t,n);return r?[r]:[]}return qt(e)?Pr(e,t,n):y.isParenthesizedExpression(e)?gt(e.expression,t,n):y.isExpression(e)?Tr(e,t,n):[]}function Cr(e,t,n){let r=new Map;for(let o of e.params)for(let i of at(o))ri(r,i);t.valueScopes.push(r);try{if(!y.isBlockStatement(e.body))return gt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return lc(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function lc(e,t,n){let r=[];for(let o of e){if(y.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];i&&ei([o],t,i);continue}r.push(...ti(o,t,n))}return r}function ti(e,t,n){if(y.isReturnStatement(e))return e.argument?gt(e.argument,t,n):[];if(y.isBlockStatement(e))return Dt(e.body,t,n);if(y.isIfStatement(e)){let r=y.isBlockStatement(e.consequent)?Dt(e.consequent.body,t,n):ti(e.consequent,t,n),o=e.alternate?y.isBlockStatement(e.alternate)?Dt(e.alternate.body,t,n):ti(e.alternate,t,n):[];return[...r,...o]}if(y.isSwitchStatement(e))return Dt(e.cases.flatMap(r=>r.consequent),t,n);if(y.isTryStatement(e)){let r=Dt(e.block.body,t,n);return e.handler&&r.push(...Dt(e.handler.body.body,t,n)),e.finalizer&&r.push(...Dt(e.finalizer.body,t,n)),r}return[]}function Dt(e,t,n){let r=new Map;t.valueScopes.push(r);try{return lc(e,t,n)}finally{t.valueScopes.pop()}}function Rr(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:ve(r),sourceCandidates:i&&i.length>0?i:void 0})}function Xp(e,t,n,r){let o=Bp(e.openingElement,["items","dataSource","data"]),i={key:t,tag:oc(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!y.isJSXAttribute(s))continue;let a=Kp(s);if(!a||!y.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!y.isJSXEmptyExpression(c)){if(Vp(a)&&qo(c)){let l=Cr(c,n,r),u=rc(o,c,r,n);Rr(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(Jp(a)){let l=qo(c)?Cr(c,n,r):gt(c,n,r);Rr(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!y.isJSXExpressionContainer(s)||!qo(s.expression))continue;let a=Cr(s.expression,n,r),c=rc(o,s.expression,r,n);Rr(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function wr(e,t,n){let r=oc(e.openingElement);if(r==="Fragment"||ni(e))return Ar(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=Pp(r),a;if(s){let T=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${T}`}else{let T=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${T}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=Rn(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:u},p=s?"component-boundary":null,m=_p(e.children,t,n),S=Dp(e.openingElement,t,n),I,v,C=!1;if(s){let T=t.importMap.get(r)??t.importMap.get(Ap(r));T&&(I=T.specifier,v=T.exportName,C=Pn(T.specifier,t.file))}let A={identity:f,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:ve(e),parentKey:i,childKeys:[],textSegments:m,attributes:S.length>0?S:void 0,boundaryKind:p,isOpaque:s,...C?{isPublicUiComponent:!0}:{},importedFrom:I,exportName:v};return t.elements.set(u,A),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),Xp(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),Wp(e.children,t,n),t.parentStack.pop()),u}function Pr(e,t,n){return Ar(e.children,t,n)}function Ar(e,t,n){let r=[];for(let o of e)if(y.isJSXElement(o))if(ni(o))r.push(...Ar(o.children,t,n));else{let i=wr(o,t,n);i&&r.push(i)}else qt(o)?r.push(...Pr(o,t,n)):y.isJSXExpressionContainer(o)&&r.push(...Tr(o.expression,t,n));return r}function Wp(e,t,n){for(let r of e)y.isJSXElement(r)?wr(r,t,n):qt(r)?Pr(r,t,n):y.isJSXExpressionContainer(r)&&Tr(r.expression,t,n)}function zp(e){return e==="&&"||e==="||"||e==="??"}function Tr(e,t,n){if(y.isJSXEmptyExpression(e))return[];let r=Up(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:ht(r.collection,n),collectionSource:ct(r.collection,n,t)};if(y.isArrowFunctionExpression(a)||y.isFunctionExpression(a)){let u=a.params[0],f=a.params[1];y.isIdentifier(u)&&(c.itemParamName=u.name),y.isIdentifier(f)&&(c.indexParamName=f.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:ve(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(y.isArrowFunctionExpression(a)||y.isFunctionExpression(a))&&l.childKeys.push(...Cr(a,t,n)),l.childKeys}if(y.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:ht(e.test,n),conditionSource:ct(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:ve(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...gt(e.consequent,t,n)),s.childKeys.push(...gt(e.alternate,t,n)),s.childKeys}if(y.isLogicalExpression(e)&&zp(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:ht(e.left,n),conditionSource:ct(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:ve(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...gt(e.right,t,n)),s.childKeys}if(y.isParenthesizedExpression(e))return Tr(e.expression,t,n);if(y.isJSXElement(e)){let o=wr(e,t,n);return o?[o]:[]}return qt(e)?Pr(e,t,n):[]}function Hp(e){let t=e.argument;return t&&(y.isExpression(t)||qt(t))?t:null}function An(e,t){let n=[];for(let r of e){if(y.isReturnStatement(r)){let o=Hp(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(y.isIfStatement(r)){let o=y.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...An(o,r.test)),r.alternate){let i=y.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...An(i,r.test))}continue}if(y.isSwitchStatement(r))for(let o of r.cases){let i=o.test?y.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...An(o.consequent,i))}}return n}function uc(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=Fp(r);wp(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let p=Tp(f);if(!p)return;let m=f.node,S=[];if(y.isArrowFunctionExpression(m))y.isExpression(m.body)||qt(m.body)?S=[{argument:m.body,statement:y.returnStatement(y.isExpression(m.body)?m.body:null)}]:y.isBlockStatement(m.body)&&(S=An(m.body.body));else{let G=m.body;y.isBlockStatement(G)&&(S=An(G.body))}if(S.length===0){f.skip();return}let I=new Map;ei(Op(r.program.body),Qo(t,p,i,s,l,[I]),I);let v=new Map;for(let G of m.params)for(let fe of at(G))ri(v,fe);let C=y.isBlockStatement(m.body)?m.body.body:[],A=S[0]?.statement??null;for(let G of C){if(A&&G===A)break;y.isVariableDeclaration(G)&&ei([G],Qo(t,p,i,s,l,[I,v]),v)}let T=Qo(t,p,i,s,l,[I,v]);for(let G of S){let fe=gt(G.argument,T,n);for(let ue of fe)a.includes(ue)||a.push(ue);if(G.condition){let ue={kind:"conditional-branch",conditionExpression:ht(G.condition,n),conditionSource:ct(G.condition,n,T)};Rr(T,"conditional-region","",G.statement,fe,[ue])}}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 oi(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Nr(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function dc(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Yo,c=new Map,l=new Map,u=new Map,f=[],p=new Set,m=C=>{let A=`${C.path}\0${C.code}\0${C.message}\0${JSON.stringify(C.details??{})}`;p.has(A)||(p.add(A),f.push(C))},S=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(C=>({file:C.file,source:C.source,depth:0,diagnosticEntryFile:C.file,importStack:[]}))],I=new Set;for(;S.length>0;){let C=S.shift(),{file:A,source:T,depth:G,diagnosticEntryFile:fe,importStack:ue}=C;if(I.has(A))continue;I.add(A),c.set(A,T);let R=a(A,T);if(!R.ok){m(Nr(R.diagnostic,fe,ue));continue}u.set(A,R.module);let{graph:_,localImports:D}=uc(R.module);for(let L of _.elements.values())if(L.importedFrom&&wn(L.importedFrom)){let Z=L.importedFrom,Q=await Ir(A,Z,r);Q.ok?(L.importedFrom=Q.path,_t(Q.path)&&(L.isPublicUiComponent=!0)):Pn(Z,A)||m(Nr(Q.diagnostic,fe,oi(ue,A,Z,Q.diagnostic.path)))}if(l.set(A,_),!(G>=i))for(let L of D){if(Yp(L))continue;let Z=await Ir(A,L,r);if(!Z.ok){Pn(L,A)||m(Nr(Z.diagnostic,fe,oi(ue,A,L,Z.diagnostic.path)));continue}let Q=Z.path;if(I.has(Q)||_t(Q))continue;let me=oi(ue,A,L,Q);try{let H=await n(Q);S.push({file:Q,source:H,depth:G+1,diagnosticEntryFile:fe,importStack:me})}catch(H){m(Nr({path:Q,code:"import-read-failed",message:`Failed to read imported file: ${Q}`,details:{fromFile:A,specifier:L,reason:H instanceof Error?H.message:String(H)}},fe,me))}}}let v=Gp(e,l,s,(o.additionalEntries??[]).map(C=>C.file));return v.diagnostics=f,{graph:v,allSources:c,diagnostics:f,parsedModules:u,entryModule:u.get(e)??null}}function Yp(e){return/\.(?:css|scss|sass|less)(?:\?.*)?$/i.test(e)}function Gp(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 p=s.get(u)??[];s.set(u,[...p,...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}}function fc(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}),pc(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function pc(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}),pc(s,t,n,r,o))}}import{isSiteEditRuntimeContainerTag as Zp,isSiteEditRuntimeVoidElementTag as Qp}from"@vcp-dev/contracts/site-edit-runtime-capability";function qp(e,t,n){let r=t.nodes.get(e),o=n.elements.get(e);if(!r||!o)return{key:e,canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1,constraints:[{kind:"opaque-region",message:"Node not found in graph"}]};let i=r.constraints.map(T=>({kind:T.kind,message:T.reason})),s=o.isOpaque,c=r.parentKey===null&&o.componentName==="Page",l=o.tag.toLowerCase(),u=o.tag!==l,f=!u&&Qp(l),p=u||Zp(l),m=u&&o.childKeys.length>0&&!o.isPublicUiComponent,S=o.textSegments.length>0&&o.textSegments.some(T=>T.editable);f&&!i.some(T=>T.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' is void: children cannot be inserted`}),!f&&!p&&!i.some(T=>T.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' cannot contain structured children`});let I=S&&!s,v=!o.isPublicUiComponent&&!f&&p&&(!s||m);return{key:e,canUpdateText:I,canInsertChild:v,canMove:!c,canRemove:!c,constraints:i}}function mc(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,qp(r,e,t));return n}import{createHash as Ti}from"node:crypto";import vi from"@babel/traverse";function ii(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 Ch}from"node:crypto";import zc from"node:path";import*as zr from"@babel/parser";import Ei from"@babel/generator";import Si from"@babel/traverse";import*as Et from"@babel/types";import si from"@babel/traverse";var yt=typeof si=="function"?si:si.default,Fr=new WeakMap,hc=new WeakMap;function ut(e,t){let n=zo(e,t);if(!n.ok)return Wo(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=te(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}}:Wo(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function te(e,t){return t.kind==="jsx-node"?Ec(e,t):t.kind==="jsx-attribute"?im(e,t):t.kind==="value"?sm(e,t):t.kind==="expression"?am(e,t):t.kind==="directive"?cm(e,t):t.kind==="export"?lm(e,t):{ok:!1,diagnostic:Mt("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Ec(e,t){return t.strategy==="source-range"?em(e,t):tm(e,t)}function em(e,t){let n=null;if(yt(e,{JSXElement(o){if(!tn(o.node,t.sourceRange))return;let i=xe("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!tn(o.node,t.sourceRange))return;let i=xe("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!tn(o.node,t.sourceRange))return;let i=xe("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Ee("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!Sm(r.path,t.expectedIdentity)?Ee("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function tm(e,t){if(t.structuralPath===""){let r=rm(e,t.component);if(r){let o=om(r);if(o)return o}}let n=null;return yt(e,{JSXElement(r){if(Nn(r)!==t.component||ci(r)!==t.structuralPath)return;let i=xe("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Nn(r)!==t.component||ci(r)!==t.structuralPath)return;let i=xe("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=nm(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Ee("jsx-node","locator-miss","JSX node not found for structural-path locator")}function nm(e,t,n){let r=null;return yt(e,{JSXElement(o){if(Nn(o)!==t||!tn(o.node,n))return;let i=xe("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Nn(o)!==t||!tn(o.node,n))return;let i=xe("jsx-node",o);i&&(r=i,o.stop())}}),r}function rm(e,t){let n=null;return yt(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 om(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 Ee("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Ee("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 Ee("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function im(e,t){let n=Ec(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>bm(c,t.name));if(!s||!s.isJSXAttribute())return Ee("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=xe("jsx-attribute",s);return a?{ok:!0,match:a}:Ee("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function sm(e,t){let n=um(e,t);if(!n.ok)return n;let r=dm(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!lt(r.match.path.node.loc,t.expectedRange)?Ee("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function am(e,t){let n=null;return yt(e,{Identifier(r){if(!gm(r))return;let o=yc(r);if(!o||!xc(o,t))return;let i=xe("expression",r);i&&(t.expectedRange&&!lt(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=yc(r);if(!o||!xc(o,t))return;let i=xe("expression",r);i&&(t.expectedRange&&!lt(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Ee("expression","locator-miss","Expression not found")}function cm(e,t){let n=null;return yt(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!lt(i.node.loc,t.expectedRange))return;let s=xe("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Ee("directive","locator-miss",`Directive '${t.value}' not found`)}function lm(e,t){let n=null;return yt(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let p=xe("export",c);if(!p||t.expectedRange&&!lt(c.node.loc,t.expectedRange))return;n=p,r.stop();return}if(!c.isVariableDeclaration())return;let l=li(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let f=xe("export",u);if(!f||t.expectedRange&&!lt(u.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=li(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!lt(s.node.loc,t.expectedRange))return;let a=xe("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=xe("export",o);i&&(t.expectedRange&&!lt(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Ee("export","export-not-found",`Export '${Em(t)}' not found`)}function um(e,t){let n=null;return yt(e,{Expression(r){if(n||t.root.kind!=="expression"||!tn(r.node,t.root.sourceRange))return;let o=xe("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let m=r.get("init");if(!m.node)return;let S=xe("value",m);if(!S)return;n=S,r.stop();return}if(t.root.kind!=="hook-state")return;let o=t.root,i=r.get("id"),s=r.get("init");if(!i.isArrayPattern()||!s.isCallExpression()||i.node.elements.findIndex(m=>m?.type==="Identifier"&&m.name===o.name)!==0)return;let 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 p=xe("value",f);p&&(n=p,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=li(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=xe("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=xe("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:Ee("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 dm(e,t){let n=ai(e);for(let o of t){if(n=ai(n),o.kind==="property"){if(!n.isObjectExpression())return Ee("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return Ee("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>Im(l,o.name));if(!c||!c.isObjectProperty())return Ee("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return Ee("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return Ee("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return Ee("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=ai(n);let r=xe("value",n);return r?{ok:!0,match:r}:Ee("value","locator-miss","Resolved value has no source range")}function ai(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function xe(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 tn(e,t){return lt(e.loc,t)}function lt(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 ci(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Mr(n.node)){let o=Sc(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${gc(n,o)}`):t.unshift(`${o}#${gc(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||hm(n.parentPath))break;n=n.parentPath}return t.join("/")}function Mr(e){let t=e.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function gc(e,t){let n=fm(e);if(!n)return 0;let r=Fr.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Fr.get(n.node)?.get(t);if(!i){let s=Fr.get(n.node);s||(s=new Map,Fr.set(n.node,s)),i=new WeakMap,s.set(t,i)}for(let s of Tn(n))if(Sc(s.node.openingElement)===t){if(i.set(s.node,o),s.node===e.node)return o;o++}return i.get(e.node)??0}function fm(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Mr(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Tn(e){let t=hc.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(Mr(o.node)){n.push(...Tn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Tn(o));continue}o.isJSXExpressionContainer()&&n.push(...en(o.get("expression")))}return hc.set(e.node,n),n}function en(e){return e.isJSXElement()?Mr(e.node)?Tn(e):[e]:e.isJSXFragment()?Tn(e):e.isParenthesizedExpression()?en(e.get("expression")):e.isLogicalExpression()&&pm(e.node.operator)?en(e.get("right")):e.isConditionalExpression()?[...en(e.get("consequent")),...en(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:en(t)):[]}function pm(e){return e==="&&"||e==="||"||e==="??"}function Sc(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?mm(e.name):null}function mm(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 Nn(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 hm(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function gm(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function yc(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 xc(e,t){return e.base===t.base&&ym(e.path,t.path??[])}function ym(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 xm(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Em(e){return e.exportKind==="named"?e.name:e.exportKind}function Ee(e,t,n,r){return{ok:!1,diagnostic:Mt(t,n,e,r)}}function Sm(e,t){return Nn(e)!==t.component?!1:ci(e)===t.structuralPath}function bm(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function li(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Im(e,t){return e.isObjectProperty()?xm(e.node)===t:!1}import ui from"@babel/generator";var km=typeof ui=="function"?ui:ui.default;function vm(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 Cm(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 Rm(e,t){return e.split(`
3
- `).map(r=>Cm(r,t)).join(`
4
- `)}function Or(e){let{ast:t,source:n}=e;try{let r=vm(n),i=km(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Rm(i,r)),{ok:!0,source:i}}catch(r){return K(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}import*as Ic from"@babel/parser";import{arrayExpression as wm,booleanLiteral as Pm,identifier as Am,jsxAttribute as Tm,jsxExpressionContainer as Nm,jsxIdentifier as Fm,nullLiteral as Mm,numericLiteral as Om,objectExpression as _m,objectProperty as Dm,stringLiteral as kc}from"@babel/types";function bc(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 Fn(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:bc(e),afterSourceHash:bc(t),inverse:n.inverse}}}function ce(e,t,n){let r=Or({ast:e,source:t});return r.ok?Fn(t,r.source,n):r}function Se(e,t){let n=Ho(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function _r(e,t){return Or({ast:e,source:t})}function Lm(e,t,n){let r=te(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function vc(e,t,n){let r=Lm(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:K(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function Cc(e,t){let n=te(e,t);return n.ok?{ok:!0,match:n.match}:n.diagnostic.code==="locator-miss"?{ok:!0,match:null}:{ok:!1,diagnostic:n.diagnostic}}function nn(e){return typeof e=="string"?kc(e):typeof e=="number"?Om(e):typeof e=="boolean"?Pm(e):e===null?Mm():Array.isArray(e)?wm(e.map(t=>nn(t))):_m(Object.entries(e).map(([t,n])=>Dm(Am(t),nn(n))))}function jm(e){return typeof e=="string"?kc(e):Nm(nn(e))}function Dr(e,t){return Tm(Fm(e),jm(t))}function Rc(e,t){try{let r=Ic.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:K(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:K(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Lr(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=Se(t,"jsx-node");if(!i.ok)return i.result;let s=te(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=$m(s.match.path)[r];if(!c)return K(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=Bm(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 ce(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function $m(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=Km(r.get("expression"));o.length>0&&t.push(...o)}}return t}function Bm(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Km(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 di}from"@babel/types";function rn(e){let{source:t,locator:n}=e,r=Se(t,"jsx-node");if(!r.ok)return r.result;let o=te(r.ast,n);return o.ok?(Um(o.match.path),ce(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function Um(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(di());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(di());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(di());return}e.remove()}import{cloneNode as qm}from"@babel/types";import fi from"@babel/traverse";import*as U from"@babel/types";var Vm=typeof fi=="function"?fi:fi.default;function Le(e,t,n,r){if(!e.ok)return e;let o=De(n);if(!o)return e;let i=Jm(t,o,r);return i?{...e,selectionRef:i}:e}function Jm(e,t,n){let r=Xm(e,t);if(!r)return;let o=n.sourceLocator?wc(n.sourceLocator):void 0,i=n.targetParentLocator?wc(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??zm(r)??i?.component??o?.component;if(!(!s||!a))return{key:Rn(s,a,Hm(r))}}function wc(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Xm(e,t){let n=null;return Vm(e,{JSXElement(r){r.node===t&&(n=r,r.stop())}}),n}function De(e){if(!e)return null;if(U.isJSXElement(e))return on(e)?Pc(e.children):e;if(U.isJSXFragment(e))return Pc(e.children);if(U.isJSXExpressionContainer(e)||U.isParenthesizedExpression(e)||U.isTSAsExpression(e)||U.isTSSatisfiesExpression(e)||U.isTSTypeAssertion(e)||U.isTSNonNullExpression(e))return De(e.expression);if(U.isLogicalExpression(e))return De(e.right);if(U.isConditionalExpression(e))return De(e.consequent)??De(e.alternate);if(U.isCallExpression(e)||U.isOptionalCallExpression(e))return Mc(e)?Wm(e.arguments[0]):null;if(U.isArrayExpression(e))for(let t of e.elements){if(!t)continue;let n=De(t);if(n)return n}return null}function Pc(e){for(let t of e){let n=De(t);if(n)return n}return null}function Wm(e){return!e||!U.isArrowFunctionExpression(e)&&!U.isFunctionExpression(e)?null:U.isBlockStatement(e.body)?Mn(e.body.body):De(e.body)}function Mn(e){for(let t of e){if(U.isReturnStatement(t)){let n=De(t.argument);if(n)return n;continue}if(U.isBlockStatement(t)){let n=Mn(t.body);if(n)return n;continue}if(U.isIfStatement(t)){let n=Ac(t.consequent);if(n)return n;let r=t.alternate?Ac(t.alternate):null;if(r)return r;continue}if(U.isSwitchStatement(t))for(let n of t.cases){let r=Mn(n.consequent);if(r)return r}}return null}function Ac(e){return U.isBlockStatement(e)?Mn(e.body):Mn([e])}function zm(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(U.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&U.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 Tc=new WeakMap,Nc=new WeakMap,pi=new WeakMap;function Hm(e){let t=Tc.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Ym(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Tc.set(e.node,o),o}function Ym(e){let t=mi(e.node.openingElement.name);return!t||on(e.node)?null:/^[A-Z]/.test(t)?`component:${t}#${Fc(e,t)}`:`${t}#${Fc(e,t)}`}function Fc(e,t){let n=Gm(e);if(!n)return 0;let r=pi.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=pi.get(n.node);o||(o=new Map,pi.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of jt(n))if(mi(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 Gm(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(on(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function jt(e){let t=Nc.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(on(o.node)){n.push(...jt(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...jt(o));continue}o.isJSXExpressionContainer()&&n.push(...dt(o.get("expression")))}return Nc.set(e.node,n),n}function dt(e){if(e.isJSXElement())return on(e.node)?jt(e):[e];if(e.isJSXFragment())return jt(e);if(e.isParenthesizedExpression())return dt(e.get("expression"));if(e.isLogicalExpression())return dt(e.get("right"));if(e.isConditionalExpression())return[...dt(e.get("consequent")),...dt(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:dt(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Mc(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?Zm(n):[]}return[]}function Zm(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return on(t.node)?jt(t):[t];if(t.isJSXFragment())return jt(t);if(t.isParenthesizedExpression())return dt(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return dt(t);if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?dt(r):[]}return[]}function Mc(e){let t=e.callee;return(U.isMemberExpression(t)||U.isOptionalMemberExpression(t))&&U.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function on(e){let t=mi(e.openingElement.name);return t==="Fragment"||t==="React.Fragment"}function mi(e){return U.isJSXIdentifier(e)?e.name:U.isJSXMemberExpression(e)?Oc(e):U.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Oc(e){return`${U.isJSXIdentifier(e.object)?e.object.name:Oc(e.object)}.${e.property.name}`}function xt(e,t){if(t.parentPath===e&&t.listKey==="children"&&_c(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!_c(n))return null;let r=n;for(;r&&r!==e;){if(!Qm(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function _c(e){return e.isJSXElement()||e.isJSXFragment()}function Qm(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function sn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Se(t,"jsx-node");if(!a.ok)return a.result;let c=te(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return K(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 T=c.match.path.node;if(!T.closingElement||T.openingElement.selfClosing)return K(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=Rc(t,r.jsx);if(!u.ok)return u.result;let f=qm(u.node,!0),p=l.node.children,m={...s,targetParentLocator:n},S=T=>s?Le(T,a.ast,f,m):T;if(o==="append")return p.push(f),S(ce(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return p.unshift(f),S(ce(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return K(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let I=te(a.ast,i);if(!I.ok)return{ok:!1,source:t,diagnostic:I.diagnostic};let v=xt(c.match.path,I.match.path);if(!v)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=v;let C=l.node.children,A=C.findIndex(T=>T===I.match.path.node);return A===-1?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(C.splice(o==="before"?A:A+1,0,f),S(ce(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Dc from"@babel/parser";import{cloneNode as eh}from"@babel/types";function jr(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Se(t,"jsx-node");if(!a.ok)return a.result;let c=th(t,r);if(!c.ok)return c.result;let l=te(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return K(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let C=l.match.path.node;if(!C.closingElement||C.openingElement.selfClosing)return K(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,f=null;if(i){let C=te(a.ast,i);if(!C.ok)return{ok:!1,source:t,diagnostic:C.diagnostic};let A=xt(l.match.path,C.match.path);if(!A)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=A,f=C.match.path.node}else if(o==="before"||o==="after")return K(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=eh(c.node,!0),m=u.node.children,S={...s,targetParentLocator:n},I=C=>s?Le(C,a.ast,p,S):C;if(o==="append")return m.push(p),I(ce(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(p),I(ce(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let v=m.findIndex(C=>C===f);return v===-1?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(m.splice(o==="before"?v:v+1,0,p),I(ce(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function th(e,t){try{let r=Dc.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:K(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:K(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as nh,nullLiteral as hi}from"@babel/types";import*as an from"@babel/types";function cn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Se(t,"jsx-node");if(!a.ok)return a.result;let c=te(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=te(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return K(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 A=l.match.path.node;if(!A.closingElement||A.openingElement.selfClosing)return K(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let f=null;if(i){let A=te(a.ast,i);if(!A.ok)return{ok:!1,source:t,diagnostic:A.diagnostic};let T=xt(l.match.path,A.match.path);if(!T)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=T,f=A.match.path}else if(o==="before"||o==="after")return K(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=f&&typeof f.key=="number"?f.key:-1;if(f&&p===-1)return K(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let m=nh(c.match.path.node,!0);if(!an.isJSXElement(m)&&!an.isJSXExpressionContainer(m)&&!an.isJSXFragment(m))return K(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let S=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 K(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");rh(c.match.path);let I=u.node.children,v={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return I.push(m),Le(_r(a.ast,t),a.ast,m,v);if(o==="prepend")return I.unshift(m),Le(_r(a.ast,t),a.ast,m,v);let C=p-(S!==-1&&S<p?1:0);return I.splice(o==="before"?C:C+1,0,m),Le(_r(a.ast,t),a.ast,m,v)}function rh(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(hi());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(hi());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(hi());return}e.remove()}import*as Lc from"@babel/parser";import{cloneNode as oh,nullLiteral as gi}from"@babel/types";function $r(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=Se(t,"jsx-node");if(!c.ok)return c.result;let l=ih(t,s);if(!l.ok)return l.result;let u=te(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let f=te(c.ast,r);if(!f.ok)return{ok:!1,source:t,diagnostic:f.diagnostic};if(!f.match.path.isJSXElement()&&!f.match.path.isJSXFragment())return K(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(f.match.path.isJSXElement()){let T=f.match.path.node;if(!T.closingElement||T.openingElement.selfClosing)return K(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let p=f.match.path,m=null;if(i){let T=te(c.ast,i);if(!T.ok)return{ok:!1,source:t,diagnostic:T.diagnostic};let G=xt(f.match.path,T.match.path);if(!G)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");p=G,m=T.match.path.node}else if(o==="before"||o==="after")return K(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return K(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let S=p.node,I=oh(l.node,!0);sh(u.match.path);let v={...a,sourceLocator:n,targetParentLocator:r},C=S.children;if(o==="append")return C.push(I),Le(ce(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,I,v);if(o==="prepend")return C.unshift(I),Le(ce(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,I,v);let A=C.findIndex(T=>T===m);return A===-1?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(C.splice(o==="before"?A:A+1,0,I),Le(ce(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,I,v))}function ih(e,t){try{let r=Lc.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:K(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:K(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function sh(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(gi());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(gi());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(gi());return}e.remove()}function Br(e){let{source:t,locator:n,props:r}=e,o=Se(t,"jsx-node");if(!o.ok)return o.result;let i=vc(o.ast,n,t);if(!i.ok)return i.result;let s=i.match.path.node.openingElement;for(let[a,c]of Object.entries(r)){if(c===void 0)continue;let l={kind:"jsx-attribute",element:n,name:a},u=Cc(o.ast,l);if(u.ok&&u.match!==null){let f=u.match.path.node;f.value=c===""?Dr(a,"").value:Dr(a,c).value}else s.attributes.push(Dr(a,c))}return ce(o.ast,t,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}import{getBindingIdentifiers as ah,identifier as On,importDeclaration as ch,importDefaultSpecifier as lh,importNamespaceSpecifier as uh,importSpecifier as dh,isImportDefaultSpecifier as jc,isImportNamespaceSpecifier as $c,isImportSpecifier as Bc,stringLiteral as fh}from"@babel/types";function ln(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(v=>!bh(v));if(o!==-1){let v=r[o],C=v&&typeof v=="object"&&"kind"in v?v.kind:void 0;return K(t,"unsupported-syntax",`Unsupported import spec kind: ${String(C)}`)}let i=xh(r);if(!i.ok)return K(t,"unsupported-syntax",i.message);let s=Se(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(v=>v.type==="ImportDeclaration"&&v.source.value===n),u=new Set(l.flatMap(v=>v.specifiers.flatMap(C=>{let A=Ih(v,C);return A?[A]:[]}))),f=i.imports.filter(v=>!u.has(Wc(v)));if(f.length===0)return Fn(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let p=Eh(c.body),m=f.find(v=>p.has(yi(v)));if(m)return K(t,"unsupported-syntax",`Import local binding already exists: ${yi(m)}`);let S=yh(f);if(S.reduce((v,C)=>v+C.length,0)!==f.length)return K(t,"unsupported-syntax","Unsupported import specifier grouping");for(let v of S){if(!Jc(Uc(v)))return K(t,"unsupported-syntax","Unsupported import specifier combination");let C=l.find(A=>ph(A,v));if(C)mh(C,v);else{let A=ch(Kc(v),fh(n));Sh(c.body,A),l.push(A)}}return ce(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function ph(e,t){return e.importKind==="type"?!1:Jc(gh(hh(e),Uc(t)))}function mh(e,t){let n=!1,r=new Set(e.specifiers.map(o=>xi(o)));for(let o of Kc(t)){let i=xi(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return Xc(e.specifiers),{changed:n}}function Kc(e){let t=e.map(n=>{switch(n.kind){case"named":return dh(n.local?On(n.local):On(n.imported),On(n.imported));case"default":return lh(On(n.local));case"namespace":return uh(On(n.local));default:return n}});return Xc(t),t}function Uc(e){let t=Vc();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 hh(e){let t=Vc();for(let n of e.specifiers)jc(n)?t.defaultLocals.add(n.local.name):$c(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Vc(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function gh(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Jc(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function Xc(e){let t=[...e.filter(n=>jc(n)),...e.filter(n=>$c(n)),...e.filter(n=>Bc(n))];e.splice(0,e.length,...t)}function yh(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 xh(e){let t=new Map,n=new Map;for(let r of e){let o=Wc(r);if(t.has(o))continue;let i=yi(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 Eh(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(ah(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 Sh(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 bh(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 Wc(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 yi(e){return e.kind==="named"?e.local??e.imported:e.local}function Ih(e,t){return e.importKind==="type"||Bc(t)&&t.importKind==="type"?null:xi(t)}function xi(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=>!vh(u));if(o!==-1){let u=r[o],f=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return K(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(f)}`)}let i=Se(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 Fn(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),ce(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(f=>kh(u,f))),l.specifiers.length===0&&a.body.splice(c,1),ce(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function kh(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 vh(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 _n(e){let{source:t,locator:n,next:r}=e,o=Jr(t,n);return o.ok?(o.path.replaceWith(nn(r)),ce(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Kr(e){let{source:t,locator:n,index:r,value:o}=e,i=Jr(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?K(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?K(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,nn(o)),ce(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):K(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function Ur(e){let{source:t,locator:n,index:r}=e,o=Jr(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?K(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?K(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),ce(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):K(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function Vr(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=Jr(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return K(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return K(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 K(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),ce(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function Jr(e,t){let n=Se(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=te(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}}}var Rh=typeof Ei=="function"?Ei:Ei.default;function Ii(e){let t=qc(e);if(t)return{ok:!1,error:t};let n=e.projection,r=ki(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.containerSourceRange??n.container.sourceRange,i=r.placement;if((n.container.kind==="virtual-route-root"||n.container.kind==="starter-placeholder")&&(n.container.sourceRange===null||n.container.sourceKind==="jsx-element"||n.container.sourceKind==="atomic-expression"||n.container.kind==="starter-placeholder"))return n.container.sourceKind==="atomic-expression"?{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"An indirect page expression does not expose a safe return boundary.",diagnostics:[]}}:{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:i.placementUnitKey,importStep:Hc(e),returnStep:{kind:"insert-return",node:{jsx:`<${e.component.localName} />`},placement:i.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}};if(!o)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition does not expose a safe placement boundary.",diagnostics:[]}};let a={kind:"jsx-node",strategy:"source-range",sourceRange:o},c=ut(e.source,a);if(!c.ok||!c.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:c.ok===!1?c.diagnostic.message:"Route page composition anchor could not be resolved.",diagnostics:c.ok?[]:[Xr(c.diagnostic)]}};let l=Wr(e.source,c.match.node.start??null,c.match.node.end??null);if(Ah(o,n.container.sourceRange)&&n.container.sourceHash&&l!==n.container.sourceHash)return{ok:!1,error:{code:"VERSION_STALE",message:"Route page composition container hash no longer matches the current source.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition container hash no longer matches the current source."}]}};let u=Hc(e);return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:r.placement.placementUnitKey,parentLocator:a,importStep:u,insertStep:{kind:"insert-child",parentLocator:a,node:{jsx:`<${e.component.localName} />`},placement:r.placement.relation,...r.placement.anchorSourceRange?{anchorLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:r.placement.anchorSourceRange}}:{}}}}}function Hc(e){let t=Ph(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 Zc(e){let t;try{t=zr.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(i){return{ok:!1,source:e.source,diagnostic:{message:i instanceof Error?i.message:String(i)}}}let n=zr.parseExpression(e.jsx,{plugins:["jsx","typescript"]}),r=!1;return(typeof Si=="function"?Si:Si.default)(t,{ExportDefaultDeclaration(i){let s=i.get("declaration"),a=wh(i,s);if(a){if(a.isArrowFunctionExpression()&&!a.get("body").isBlockStatement()){let c=a.get("body");c.replaceWith(Yc(c.node,n,e.placement,e.replaceOriginal===!0)),r=!0,i.stop();return}a.traverse({Function(c){c.node!==a.node&&c.skip()},ReturnStatement(c){if(r)return;let l=c.get("argument");l.node&&(l.replaceWith(Yc(l.node,n,e.placement,e.replaceOriginal===!0)),r=!0,c.stop())}}),r&&i.stop()}}}),r?{ok:!0,source:Rh(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:"Route default return boundary could not be resolved."}}}function wh(e,t){if(t.isFunctionDeclaration()||t.isFunctionExpression()||t.isArrowFunctionExpression())return t;if(!t.isIdentifier())return null;let n=e.scope.getBinding(t.node.name);if(!n)return null;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression())return r;if(r.isVariableDeclarator()){let o=r.get("init");if(o.isArrowFunctionExpression()||o.isFunctionExpression())return o}return null}function Yc(e,t,n,r){if(Et.isNullLiteral(e)||r)return t;let s=n==="before"||n==="prepend"?[t,e]:[e,t];return Et.jsxFragment(Et.jsxOpeningFragment(),Et.jsxClosingFragment(),s)}function Qc(e){let t=qc(e);if(t)return{ok:!1,error:t};let n=e.projection;if(n.container.sourceRange===null)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition does not expose a safe placement boundary.",diagnostics:[]}};let r=el(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:[]}};let i=bi(o.sourceRange),s=ut(e.source,i);if(!s.ok||!s.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:s.ok===!1?s.diagnostic.message:"Route page composition source anchor could not be resolved.",diagnostics:s.ok?[]:[Xr(s.diagnostic)]}};if(Wr(e.source,s.match.node.start??null,s.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:i}}};if(!e.targetPlacement)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit move requires a target placement.",diagnostics:[]}};if(e.targetPlacement.routeId!==e.routeId)return{ok:!1,error:{code:"CROSS_PAGE_MOVE_UNSUPPORTED",message:"Page-unit move across routes is not supported.",diagnostics:[]}};if(e.targetPlacement.documentVersion!==e.expectedDocumentVersion)return{ok:!1,error:{code:"VERSION_STALE",message:"Page-unit target placement belongs to a different document version.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Page-unit target placement belongs to a different document version."}]}};let c=ki(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!c.ok)return{ok:!1,error:{code:c.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:c.diagnostic.message,diagnostics:[c.diagnostic]}};let l=c.placement;if(l.placementUnitKey!==e.targetPlacement.placementUnitKey||l.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 u=l.containerSourceRange;if(!u||!l.containerSourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable container boundary.",diagnostics:[]}};let f=bi(u),p=ut(e.source,f);if(!p.ok||!p.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:p.ok===!1?p.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:p.ok?[]:[Xr(p.diagnostic)]}};if(Wr(e.source,p.match.node.start??null,p.match.node.end??null)!==l.containerSourceHash)return Gc("Route page composition target container hash no longer matches the current source.");if(l.relation==="before"||l.relation==="after"){let S=l.anchorSourceRange,I=l.anchorSourceHash;if(!S||!I)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let v=bi(S),C=ut(e.source,v);return!C.ok||!C.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:C.ok===!1?C.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:C.ok?[]:[Xr(C.diagnostic)]}}:Wr(e.source,C.match.node.start??null,C.match.node.end??null)!==I?Gc("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:i,targetParentLocator:f,anchorLocator:v,placement:l.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:i,targetParentLocator:f,placement:l.relation}}}}function Gc(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Xr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function qc(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.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 Ph(e,t){let n=zc.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=zc.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function bi(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Wr(e,t,n){return t==null||n==null?null:`sha256:${Ch("sha256").update(e.slice(t,n)).digest("hex")}`}function Ah(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 Th=typeof vi=="function"?vi:vi.default;function nl(e){if(!e.ast)return nt(e,[we("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=jh(e.ast);if(!t)return nt(e,[we("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=Bh(t);if(n.length===0)return nt(e,[we("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")]);if(n.length>1)return nt(e,[we("MULTIPLE_PAGE_RETURNS","Route default export contains multiple page-level return statements",{returnCount:n.length})]);let r=Kh(n[0].argument);if(!r)return nt(e,[we("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})]);if(r.isNullLiteral())return tl(e,t,"virtual-route-root");if(Uh(r,t))return nt(e,[we("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(Vh(r,t)||Jh(r)&&!e.source.includes("DESIGN_PLAN_REPLACE_ME"))return nt(e,[we("UNSUPPORTED_PAGE_SHAPE","Route default export shape does not provide a single safe placement boundary",{reason:"ambiguous-placement"})]);if(r.isJSXFragment()){let i=bt(r);if(i.unsupported)return nt(e,[we("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=Ci({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-fragment",source:e.source,containerPath:r,members:i.members});return Hr(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-fragment"})}if(r.isJSXElement()&&!dn(r)){let i=Pi(r),s=Ci({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[i]});return Hr(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-element"})}if(r.isJSXElement()){let i=bt(r);if(i.unsupported)return nt(e,[we("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=i.members;if(Wh(e.source,r,s))return tl(e,t,"starter-placeholder");let a=Ci({input:e,containerKind:"jsx-container",sourceKind:"jsx-element",source:e.source,containerPath:r,members:s});return Hr(e,t,a,{kind:"jsx-container",sourceKind:"jsx-element"})}if(Xh(r))return nt(e,[we("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let o=Hh({input:e,source:e.source,expression:r});return Hr(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"})}function ki(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:we("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:we("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function el(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:we("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:we("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function rl(e){return e.ok?Nh(e.projection):Fh(e.projection)}function Nh(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((I,v)=>ol(e,u,I,v,e.container.placementKey)),p=f.filter(({member:I})=>I.isBusinessMember).map(({sourceMember:I})=>Oh(l,I,u.independent)),m=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,m.map(({sourceMember:I})=>I)),o.set(l,p);let S=m[0]?.sourceMember.key??l;n.push({key:l,containerKey:S,businessMemberKeys:p.map(I=>I.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,routeId:e.route,placementUnitKey:l.placementUnitKey,relation:l.relation}));return{status:"supported",version:e.version,routeId:e.route,container:Mh(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function Fh(e){let t=e.diagnostics.map(_h);return{status:"unsupported",version:e.version,routeId:e.route,reason:Dh(e.diagnostics),diagnostics:t}}function Mh(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 ol(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)=>ol(e,t,a,c,i))]}function Oh(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function _h(e){return{code:Lh(e),message:e.message}}function Dh(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 Lh(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 jh(e){let t=null;return Th(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=$h(o.path);i&&(t=i,n.stop())}}),t}function $h(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 Bh(e){if(e.isArrowFunctionExpression()){let r=e.get("body");if(!r.isBlockStatement())return[{argument:r}]}let t=e.get("body");if(!t.isBlockStatement())return[];let n=[];return t.traverse({Function(r){r.node!==e.node&&r.skip()},ReturnStatement(r){n.push({argument:r.get("argument")})}}),n}function Kh(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 Uh(e,t){if(e.isIdentifier())return Yr(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Yr(n.node.name,t)}return!1}function Vh(e,t){return e.isConditionalExpression()?St(e.get("consequent"),t)||St(e.get("alternate"),t):e.isLogicalExpression()?St(e.get("left"),t)||St(e.get("right"),t):!1}function Jh(e){if(!e.isJSXElement()||!dn(e))return!1;let t=bt(e).members;if(t.length!==1)return!1;let n=t[0];return n.kind==="jsx-element"&&!n.isBusinessMember&&n.businessMemberCount>0}function St(e,t){if(e.isIdentifier())return Yr(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Yr(n.node.name,t)}return e.isConditionalExpression()?St(e.get("consequent"),t)||St(e.get("alternate"),t):e.isLogicalExpression()?St(e.get("left"),t)||St(e.get("right"),t):!1}function Yr(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 Xh(e){return e.isJSXSpreadChild()}function Wh(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&wi(t)}function wi(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(!wi(t))return!1;continue}if(t.isJSXElement()&&!wi(t))return!1}return!0}function bt(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Ai(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:Xe(r.node.loc),businessMemberCount:0,parentSourceRange:Xe(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=bt(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=dn(o)?bt(o):null;n||=i?.unsupported??!1,t.push({...Pi(o,i?.members),sourceRange:Xe(r.node.loc),parentSourceRange:Xe(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Ai(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:Xe(r.node.loc),businessMemberCount:1,parentSourceRange:Xe(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&il(r)){let o=bt(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=dn(r)?bt(r):null;n||=o?.unsupported??!1,t.push({...Pi(r,o?.members),parentSourceRange:Xe(e.node.loc)})}}return{members:t,unsupported:n}}function Pi(e,t){let n=e.isJSXElement()&&dn(e)?t??bt(e).members:[],r=e.isJSXElement()&&!dn(e)&&!il(e);return{memberKey:Ai(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:Xe(e.node.loc),businessMemberCount:r?1:sl(n),parentSourceRange:Xe(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:zh(e)}}function il(e){if(e.isJSXFragment())return!0;let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name==="Fragment"||t.type==="JSXMemberExpression"&&t.object.type==="JSXIdentifier"&&t.object.name==="React"&&t.property.name==="Fragment"}function dn(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name!=="Fragment"&&t.name[0]===t.name[0]?.toLowerCase()}function zh(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 sl(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Gr(e){return e.length===0?0:Math.max(1,sl(e))}function Ci(e){let t=Xe(e.containerPath.node.loc),n=cl(e.source,e.containerPath.node.start,e.containerPath.node.end),r=je(e.input,e.containerKind,e.sourceKind,t),o=je(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:Gr(e.members)<=1,memberCount:Gr(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function Hh(e){let t=Xe(e.expression.node.loc),n=cl(e.source,e.expression.node.start,e.expression.node.end),r=je(e.input,"virtual-route-root","atomic-expression",t),o=je(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:je(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 Hr(e,t,n,r){let o=n.containerSourceRange??n.sourceRange,i=Yh(e,n,o),s=ii(i),a={status:"supported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:ll(t),container:{kind:r.kind,placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,version:e.version,isEmptyPage:n.memberCount===0,sourceKind:r.sourceKind,sourceRange:o,sourceHash:n.sourceHash},placements:i,diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map};return Object.defineProperties(a,{placementByKey:{value:s.placementByKey,enumerable:!1},unitByKey:{value:s.unitByKey,enumerable:!1},placementsByUnitKey:{value:s.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:s.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:a}}function Yh(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,f,p,m,S,I=n)=>({...t,placementKey:u,placementUnitKey:f,containerKey:t.placementKey,independent:Gr(S)<=1,memberCount:Gr(S),sourceRange:p,sourceHash:p?Ri(e.source,p):null,relation:l,containerSourceRange:I,containerSourceHash:I?Ri(e.source,I):null,anchorSourceRange:m,anchorSourceHash:m?Ri(e.source,m):null,members:S}),i=t.placementKey,s=t.members.map(l=>je(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",je(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,f=je(e,i,"placement-unit",l.sourceRange);r.push(o("before",je(e,f,"before",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",je(e,f,"after",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function tl(e,t,n){let r=je(e,n,"empty-container",void 0),o=je(e,n,"empty-unit",void 0),i={placementKey:r,placementUnitKey:o,version:e.version,containerKey:r,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},s=ii([i]),a={status:"supported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:ll(t),container:{kind:n,placementKey:r,placementUnitKey:o,version:e.version,isEmptyPage:!0,sourceKind:n==="starter-placeholder"?"starter-placeholder":"jsx-fragment",sourceRange:null,sourceHash:null},placements:[i],diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map};return Object.defineProperties(a,{placementByKey:{value:s.placementByKey,enumerable:!1},unitByKey:{value:s.unitByKey,enumerable:!1},placementsByUnitKey:{value:s.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:s.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:a}}function nt(e,t){return{ok:!1,projection:{status:"unsupported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,diagnostics:t}}}function we(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function je(e,t,n,r){return al([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Ai(e,t,n){return al(["member",e,String(t??-1),String(n??-1)])}function al(e){return`pc_${Ti("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function cl(e,t,n){return t==null||n==null?null:`sha256:${Ti("sha256").update(e.slice(t,n)).digest("hex")}`}function Ri(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:${Ti("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function Xe(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function ll(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}function Zh(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var Qh=160;function ul(e,t,n,r={}){let o=[];for(let[i,s]of e.elements){let a=n.get(i),c={canUpdateText:r.canUpdateTextByKey?.get(i)??a?.canUpdateText??!1,canInsertChild:a?.canInsertChild??!1,canMove:a?.canMove??!1,canRemove:a?.canRemove??!1};o.push({key:i,tag:s.tag,label:s.tag===s.componentName?s.tag:`${s.tag} (${s.componentName})`,parentKey:s.parentKey,childKeys:[...s.childKeys],operationSummary:c,...r.dynamicDataSummaryByKey?.get(i)?{dynamicDataSummary:r.dynamicDataSummaryByKey.get(i)}:{}})}return{routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:o}}function dl(e,t,n,r,o,i,s,a,c,l,u,f,p){let m=t.elements.get(e),S=n.nodes.get(e),I=r.get(e);if(!m||!S||!I)throw new Error(`Node not found: ${e}`);let v=gl(m.textSegments,s),C=yl(e,t,m,I,v),A=v?tg(v):void 0,T=ng(i,v),G=m.textSegments.map(_=>({index:_.index,value:_.value,editable:xl(_,I,s?.get(_.index)??null),source:o.get(_.index)??null})),fe=ml(m,t),ue=m.childKeys.map(_=>{let D=t.elements.get(_);return D?{key:_,tag:D.tag,label:D.tag}:null}).filter(_=>_!==null),R=[];if(m.parentKey){let _=t.elements.get(m.parentKey);if(_)for(let D of _.childKeys){if(D===e)continue;let L=t.elements.get(D);L&&R.push({key:D,tag:L.tag,label:L.tag})}}return{key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:pl(m),label:m.tag,capabilities:C,writeTarget:i,effectiveWriteTarget:T,provenanceChain:A,componentSemantic:c,contentModel:l,mediaModel:u,styleSource:f,conditional:a,...p?{dynamicData:p}:{},textSegments:G,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:fe,children:ue,siblings:R}}function fl(e,t,n,r,o,i,s){let a=t.elements.get(e),c=n.nodes.get(e),l=r.get(e);if(!a||!c||!l)throw new Error(`Node not found: ${e}`);let u=gl(a.textSegments,i);return{key:e,tag:a.tag,componentName:a.componentName,sourceFile:a.sourceFile,sourceLocator:pl(a),label:a.tag,capabilities:yl(e,t,a,l,u),provenanceChain:u?{editMode:u.editMode,diagnostics:u.diagnostics.map(f=>({code:f.code,message:f.message}))}:void 0,...s?{dynamicData:s}:{},textSegments:a.textSegments.map(f=>{let p=o.get(f.index);return{index:f.index,editable:xl(f,l,i?.get(f.index)??null),source:p?{kind:p.kind}:null}}),boundaryKind:a.boundaryKind,isOpaque:a.isOpaque,ancestors:ml(a,t)}}function pl(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:qh(e.sourceRange),structuralPath:e.identity.structuralPath,...eg(e.textSegments)}}function ml(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 qh(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function eg(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,Qh)}:{}}function hl(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 gl(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function yl(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&&El(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 xl(e,t,n){return!e.editable||!t.canUpdateText?!1:n?El(n.editMode):!0}function El(e){return e==="direct"||e==="proxy"||e==="upstream"}function tg(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 ng(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}:Zh(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}}function Sl(e){let{key:t,element:n,graph:r,provenances:o}=e,i=og(t,n,r),s=i?.tag??($t(n.tag)?n.tag:n.componentName),a=i?.identity.key??bl(n,r)??t,c=ag(i),l=cg(t,n,r,o,i),u=rg(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:sg(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:u,impactScope:lg(u),alternativeStrategies:ug(u)}}function rg(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Ni(e,n)?"instance":!$t(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function bl(e,t){if($t(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&ig(r,e.componentName));return n.length!==1?null:n[0].identity.key}function og(e,t,n){if($t(t.tag))return t;let r=Ni(e,n);if(r)return r;let o=bl(t,n);return o?n.elements.get(o)??null:null}function ig(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function sg(e,t){return $t(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function ag(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 cg(e,t,n,r,o){let i=new Set,s=Ni(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&&$t(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Ni(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if($t(r.tag))return r;n=r.parentKey}return null}function $t(e){return/^[A-Z]/.test(e)}function lg(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function ug(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}var dg=new Set(["markdown","body","content","value","document"]),Il=[];function vl(e){if(!(!mg(e.tag)||!e.attributes))for(let t of e.attributes){if(!dg.has(t.name))continue;if(pg(t))return{kind:"markdown",field:t.name,schema:"markdown",valuePath:t.source?.expression,operationBoundary:Il};let n=fg(t.resolvedValue);if(n==="prosemirror-doc"||n==="node-array")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:n,operationBoundary:Il};if(n==="unsupported-json-tree")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:"unsupported-json-tree",operationBoundary:[],diagnostics:[{code:"unsupported-schema",field:t.name,message:'Only top-level node arrays and { type: "doc", content: [] } rich-text JSON are editable in stage D'}]}}}function fg(e){if(e){if(Array.isArray(e)&&e.every(t=>kl(t)))return"node-array";if(kl(e)){if(e.type==="doc"&&Array.isArray(e.content))return"prosemirror-doc";if(Array.isArray(e.content)||Array.isArray(e.children))return"unsupported-json-tree"}}}function kl(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null}function pg(e){return e.name==="markdown"}function mg(e){return/^[A-Z]/.test(e)}var hg=["src","alt","poster","caption","width","height"];function Cl(e){let t=e.attributes?.filter(i=>hg.includes(i.name))??[];if(t.length===0)return;let n=t.map(i=>i.name),r=Object.fromEntries(t.filter(i=>i.source?.expression).map(i=>[i.name,i.source.expression])),o=yg(t.map(i=>i.value));return{kind:gg(e.tag,n),sourceType:o,fields:n,editableFields:[],operationBoundary:[],...Object.keys(r).length>0?{valuePaths:r}:{}}}function gg(e,t){return e==="img"?"image":e==="video"||t.includes("poster")?"video":"media"}function yg(e){return e.some(t=>t.startsWith("cms:"))?"cms-media-field":e.some(t=>/^(\.?\/|\/)/.test(t))?"local-file-reference":"asset-id"}var Fi=["set-class-name-source","apply-style-draft"],Rl=["block","inline-block","inline","flex","inline-flex","grid","inline-grid","hidden"],wl=["static","fixed","absolute","relative","sticky"],Li=["z-auto","z-0","z-10","z-20","z-30","z-40","z-50"],Pl=["flex-row","flex-row-reverse","flex-col","flex-col-reverse"],Al=["flex-nowrap","flex-wrap","flex-wrap-reverse"],Mi=["grow","grow-0"],Oi=["shrink","shrink-0"],ji=["basis-auto","basis-full","basis-1/2","basis-1/3","basis-2/3","basis-1/4","basis-3/4","basis-px"],$i=["order-first","order-last","order-none","order-1","order-2","order-3","order-4","order-5","order-6"],Bi=["grid-cols-1","grid-cols-2","grid-cols-3","grid-cols-4","grid-cols-5","grid-cols-6","grid-cols-12","grid-cols-none","grid-cols-subgrid"],Ki=["grid-rows-1","grid-rows-2","grid-rows-3","grid-rows-4","grid-rows-5","grid-rows-6","grid-rows-none","grid-rows-subgrid"],Ui=["col-auto","col-span-1","col-span-2","col-span-3","col-span-4","col-span-6","col-span-12","col-span-full"],Vi=["row-auto","row-span-1","row-span-2","row-span-3","row-span-4","row-span-6","row-span-full"],Tl=["items-start","items-end","items-center","items-baseline","items-stretch"],Nl=["justify-normal","justify-start","justify-end","justify-center","justify-between","justify-around","justify-evenly","justify-stretch"],Fl=["overflow-auto","overflow-hidden","overflow-clip","overflow-visible","overflow-scroll"],_i=["font-sans","font-serif","font-mono"],Ji=["font-thin","font-extralight","font-light","font-normal","font-medium","font-semibold","font-bold","font-extrabold","font-black"],Xi=["text-xs","text-sm","text-base","text-lg","text-xl","text-2xl","text-3xl","text-4xl","text-5xl","text-6xl","text-7xl","text-8xl","text-9xl"],Wi=["text-left","text-center","text-right","text-justify","text-start","text-end"],Ml=["uppercase","lowercase","capitalize","normal-case"],Ol=["underline","overline","line-through","no-underline"],zi=["indent-0","indent-4","indent-8","indent-12"],_l=["[writing-mode:horizontal-tb]","[writing-mode:vertical-rl]"],Dl=["whitespace-normal","whitespace-nowrap","whitespace-pre","whitespace-pre-line","whitespace-pre-wrap","whitespace-break-spaces"],Ll=["break-normal","break-words","break-all","break-keep"],Hi=["line-clamp-none","line-clamp-1","line-clamp-2","line-clamp-3","line-clamp-4","line-clamp-5","line-clamp-6"],Di=["tracking-tighter","tracking-tight","tracking-normal","tracking-wide","tracking-wider","tracking-widest"],Yi=["border-solid","border-dashed","border-dotted","border-double","border-hidden","border-none"],Gi=["border","border-0","border-2","border-4","border-8"],jl=["object-contain","object-cover","object-fill","object-none","object-scale-down"],Zi=["aspect-auto","aspect-square","aspect-video"],Qi=["shadow-none","shadow-sm","shadow","shadow-md","shadow-lg","shadow-xl","shadow-2xl"],fC=[{property:"display",exact:Rl,isMatch:e=>e==="gallery-item",options:[...Rl]},{property:"position",exact:wl,isMatch:e=>e==="cta-shine",options:[...wl]},{property:"top",isMatch:e=>Zr("top",e)},{property:"right",isMatch:e=>Zr("right",e)},{property:"bottom",isMatch:e=>Zr("bottom",e)},{property:"left",isMatch:e=>Zr("left",e)},{property:"zIndex",exact:Li,isMatch:Rg,options:[...Li]},{property:"flexDirection",exact:Pl,options:[...Pl]},{property:"flexWrap",exact:Al,options:[...Al]},{property:"flexGrow",exact:Mi,isMatch:e=>Mi.includes(e)||/^grow-\[.+\]$/.test(e),options:[...Mi]},{property:"flexShrink",exact:Oi,isMatch:e=>Oi.includes(e)||/^shrink-\[.+\]$/.test(e)||/^flex-shrink-(?:0|\[.+\])$/.test(e),options:[...Oi]},{property:"flexBasis",exact:ji,isMatch:Sg,options:[...ji]},{property:"flex",isMatch:e=>/^flex-(?:\d+|auto|initial|none|\[.+\])$/.test(e)},{property:"order",exact:$i,isMatch:bg,options:[...$i]},{property:"gridTemplateColumns",exact:Bi,isMatch:Ig,options:[...Bi]},{property:"gridTemplateRows",exact:Ki,isMatch:kg,options:[...Ki]},{property:"columns",isMatch:e=>e==="gallery-grid"||/^columns-(?:\d+|auto|3xs|2xs|xs|sm|md|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|\[.+\])$/.test(e)},{property:"gridColumn",exact:Ui,isMatch:vg,options:[...Ui]},{property:"gridRow",exact:Vi,isMatch:Cg,options:[...Vi]},{property:"gap",prefix:"gap-",isMatch:e=>e.startsWith("gap-")&&!e.startsWith("gap-x-")&&!e.startsWith("gap-y-")},{property:"gapX",prefix:"gap-x-"},{property:"gapY",prefix:"gap-y-"},{property:"spaceX",prefix:"space-x-"},{property:"spaceY",prefix:"space-y-"},{property:"alignItems",exact:Tl,options:[...Tl]},{property:"alignSelf",isMatch:e=>/^self-(?:auto|start|end|center|stretch|baseline)$/.test(e)},{property:"justifyContent",exact:Nl,options:[...Nl]},{property:"marginTop",prefix:"mt-",isMatch:e=>It("m","t",e)},{property:"marginRight",prefix:"mr-",isMatch:e=>It("m","r",e)},{property:"marginBottom",prefix:"mb-",isMatch:e=>It("m","b",e)},{property:"marginLeft",prefix:"ml-",isMatch:e=>It("m","l",e)},{property:"paddingTop",prefix:"pt-",isMatch:e=>It("p","t",e)},{property:"paddingRight",prefix:"pr-",isMatch:e=>It("p","r",e)},{property:"paddingBottom",prefix:"pb-",isMatch:e=>It("p","b",e)},{property:"paddingLeft",prefix:"pl-",isMatch:e=>It("p","l",e)},{property:"width",prefix:"w-",isMatch:e=>e.startsWith("w-")||$l(e)},{property:"height",prefix:"h-",isMatch:e=>e.startsWith("h-")||$l(e)},{property:"minWidth",prefix:"min-w-"},{property:"minHeight",prefix:"min-h-"},{property:"maxWidth",isMatch:e=>e==="container"||e.startsWith("max-w-")},{property:"maxHeight",prefix:"max-h-"},{property:"overflow",exact:Fl,isMatch:e=>/^overflow(?:-[xy])?-.+$/.test(e),options:[...Fl]},{property:"fontFamily",exact:_i,isMatch:e=>_i.includes(e)||/^font-\[.+\]$/.test(e)||/^font-[a-z][\w-]*$/.test(e)&&!Fg(e),options:[..._i]},{property:"fontSize",exact:Xi,isMatch:Kl,options:[...Xi]},{property:"fontWeight",exact:Ji,options:[...Ji]},{property:"lineHeight",prefix:"leading-"},{property:"letterSpacing",exact:Di,isMatch:e=>Di.includes(e)||e.startsWith("tracking-["),options:[...Di]},{property:"textAlign",exact:Wi,options:[...Wi]},{property:"textTransform",exact:Ml,options:[...Ml]},{property:"textDecoration",exact:Ol,options:[...Ol]},{property:"textOverflow",exact:["truncate","text-ellipsis","text-clip"]},{property:"fontStyle",exact:["italic","not-italic"]},{property:"textUnderlineOffset",prefix:"underline-offset-"},{property:"textIndent",exact:zi,isMatch:Ag,options:[...zi]},{property:"writingMode",exact:_l,options:[..._l]},{property:"whiteSpace",exact:Dl,options:[...Dl]},{property:"wordBreak",exact:Ll,options:[...Ll]},{property:"lineClamp",exact:Hi,isMatch:Pg,options:[...Hi]},{property:"fontVariantNumeric",isMatch:e=>/^(?:normal-nums|ordinal|slashed-zero|lining-nums|oldstyle-nums|proportional-nums|tabular-nums|diagonal-fractions|stacked-fractions)$/.test(e)},{property:"screenReaderOnly",exact:["sr-only","not-sr-only"]},{property:"color",isMatch:xg},{property:"backgroundColor",isMatch:Eg},{property:"backgroundImage",isMatch:e=>e.startsWith("bg-[url")||e.startsWith("bg-gradient-")},{property:"borderStyle",exact:Yi,options:[...Yi]},{property:"borderWidth",exact:Gi,isMatch:Ul,options:[...Gi]},{property:"divideWidth",isMatch:e=>/^divide-[xy](?:-\d+|-0|-reverse)?$/.test(e)},{property:"borderRadius",prefix:"rounded"},{property:"borderColor",isMatch:wg},{property:"divideColor",isMatch:e=>e.startsWith("divide-")&&!/^divide-[xy](?:-\d+|-0|-reverse)?$/.test(e)},{property:"objectFit",exact:jl,options:[...jl]},{property:"objectPosition",isMatch:e=>/^object-(?:bottom|center|left|left-bottom|left-top|right|right-bottom|right-top|top|\[.+\])$/.test(e)},{property:"aspectRatio",exact:Zi,isMatch:Tg,options:[...Zi]},{property:"opacity",prefix:"opacity-"},{property:"boxShadow",exact:Qi,isMatch:Ng,options:[...Qi]},{property:"transform",isMatch:Mg},{property:"transformOrigin",isMatch:e=>/^origin-(?:center|top|top-right|right|bottom-right|bottom|bottom-left|left|top-left|\[.+\])$/.test(e)},{property:"transitionProperty",isMatch:e=>/^transition(?:-(?:none|all|colors|opacity|shadow|transform|\[.+\]))?$/.test(e)||["motion-link","image-zoom","card-lift","cta-shine","gallery-item-img","showcase-img"].includes(e)},{property:"transitionDuration",isMatch:e=>/^duration-(?:\d+|slow|\[.+\])$/.test(e)},{property:"transitionTimingFunction",isMatch:e=>/^ease-(?:linear|in|out|in-out|\[.+\])$/.test(e)},{property:"animation",isMatch:e=>/^(?:animate-.+|fade-.+|slide-in-.+)$/.test(e)||["section-reveal","scroll-reveal","first-viewport-entrance","media-reveal","media-entrance","gallery-fade-enter","number-pop"].includes(e)},{property:"pointerEvents",exact:["pointer-events-none","pointer-events-auto"]},{property:"cursor",isMatch:e=>/^cursor-(?:auto|default|pointer|wait|text|move|help|not-allowed|none|context-menu|progress|cell|crosshair|vertical-text|alias|copy|no-drop|grab|grabbing|all-scroll|col-resize|row-resize|n-resize|e-resize|s-resize|w-resize|ne-resize|nw-resize|se-resize|sw-resize|ew-resize|ns-resize|nesw-resize|nwse-resize|zoom-in|zoom-out|\[.+\])$/.test(e)},{property:"userSelect",exact:["select-none","select-text","select-all","select-auto"]},{property:"outlineStyle",isMatch:e=>/^outline(?:-(?:none|hidden|solid|dashed|dotted|double|\d+|\[.+\]))?$/.test(e)},{property:"resize",exact:["resize-none","resize","resize-y","resize-x"]},{property:"ringWidth",isMatch:e=>/^ring(?:-\d+|-\[.+\]|-inset)?$/.test(e)},{property:"ringColor",isMatch:e=>e.startsWith("ring-")&&!/^ring(?:-\d+|-\[.+\]|-inset)?$/.test(e)},{property:"backdropFilter",isMatch:e=>/^backdrop-(?:blur|brightness|contrast|grayscale|hue-rotate|invert|opacity|saturate|sepia)(?:-.+)?$/.test(e)},{property:"overscrollBehavior",isMatch:e=>/^overscroll(?:-[xy])?-(?:auto|contain|none)$/.test(e)},{property:"scrollMarginTop",prefix:"scroll-mt-"}];function Bl(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Fi,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element"}]};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:Fi,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Fi}}function Kl(e){return Xi.includes(e)||/^text-\[.+\]$/.test(e)&&!Og(e.slice(6,-1))}function xg(e){return!e.startsWith("text-")||Wi.includes(e)?!1:!Kl(e)}function Eg(e){return e.startsWith("bg-")?!(e.startsWith("bg-gradient-")||e.startsWith("bg-[url")||["bg-fixed","bg-local","bg-scroll","bg-clip-border","bg-clip-padding","bg-clip-content","bg-clip-text","bg-origin-border","bg-origin-padding","bg-origin-content"].includes(e)):!1}function Ul(e){return Gi.includes(e)||/^border-\[.+\]$/.test(e)||/^border-(?:x|y|t|r|b|l)(?:-\d+|-\[.+\])?$/.test(e)}function Zr(e,t){let n=e==="top"||e==="bottom"?"y":e==="right"||e==="left"?"x":"";return new RegExp(`^-?${e}-.+$`).test(t)||new RegExp(`^-?inset-${n}-.+$`).test(t)||/^-?inset-.+$/.test(t)}function Sg(e){return ji.includes(e)||/^basis-\[.+\]$/.test(e)}function bg(e){return $i.includes(e)||/^-?order-(?:\d+|\[.+\])$/.test(e)}function Ig(e){return Bi.includes(e)||/^grid-cols-\[.+\]$/.test(e)}function kg(e){return Ki.includes(e)||/^grid-rows-\[.+\]$/.test(e)}function vg(e){return Ui.includes(e)||/^(?:col|col-span|col-start|col-end)-.+$/.test(e)}function Cg(e){return Vi.includes(e)||/^(?:row|row-span|row-start|row-end)-.+$/.test(e)}function Rg(e){return Li.includes(e)||/^-?z-(?:\d+|\[.+\])$/.test(e)}function wg(e){return e.startsWith("border-")?!(Yi.includes(e)||Ul(e)||e.startsWith("border-spacing-")||/^border-(?:x|y|t|r|b|l)(?:-|$)/.test(e)):!1}function Pg(e){return Hi.includes(e)||/^line-clamp-\[.+\]$/.test(e)}function Ag(e){return zi.includes(e)||/^-?indent-\[.+\]$/.test(e)}function Tg(e){return Zi.includes(e)||/^aspect-\[.+\]$/.test(e)}function Ng(e){return Qi.includes(e)||/^shadow-(?:\[.+\]|[a-z][\w-]*)$/.test(e)}function Fg(e){return Ji.includes(e)}function It(e,t,n){let r=t==="t"||t==="b"?"y":"x";return new RegExp(`^-?${e}${t}-.+$`).test(n)||new RegExp(`^-?${e}${r}-.+$`).test(n)||new RegExp(`^-?${e}-.+$`).test(n)}function $l(e){return/^size-.+$/.test(e)}function Mg(e){return e==="transform"||e==="transform-gpu"||e==="transform-none"||e.startsWith("translate-")||e.startsWith("-translate-")||e.startsWith("scale-")||e.startsWith("-scale-")||e.startsWith("rotate-")||e.startsWith("-rotate-")||e.startsWith("skew-")||e.startsWith("-skew-")}function Og(e){return e.startsWith("#")||e.startsWith("rgb")||e.startsWith("hsl")||e.startsWith("oklch")||e.startsWith("color(")}import{createHash as _g}from"node:crypto";var Dn=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function ae(e){return`sha256:${_g("sha256").update(e).digest("hex")}`}function Xl(e){let t=e.route.graph.elements.get(e.key);if(!t)return{key:e.key,routeId:e.route.routeId,filePath:"",componentName:"",sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ae(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Dg(e.route.source,t);if(!n)return{key:e.key,routeId:e.route.routeId,filePath:t.sourceFile,componentName:t.componentName,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ae(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(c=>c.type==="JSXAttribute"&&c.name.type==="JSXIdentifier"&&c.name.name==="className"),i={key:e.key,routeId:e.route.routeId,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:Jl(r),version:{documentVersion:e.route.graph.version,contentHash:ae(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:Vl(e.route.source,o),valueRaw:s?Vl(e.route.source,s):null,attrRange:Jl(o),diagnostics:[]}}function Wl(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 Dg(e,t){let n=tt({source:e,profile:Ot({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=te(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Lg(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function zl(e){let t=tt({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 Vl(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Jl(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 Lg(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}import*as hs from"@babel/parser";import rs from"@babel/traverse";import*as x from"@babel/types";import*as pt from"node:path";import*as Ql from"@babel/parser";import ts from"@babel/traverse";import*as fn from"@babel/types";import*as W from"@babel/types";function eo(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Qr(n,t):null}if(e.isMemberExpression()){let n=Vg(e.node),r=jg(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Qr(o,[...r,...t]):null}return e.isAwaitExpression()||es(e.node)?kt(Xg(e.node),t,"awaited or fetched expression"):null}function jg(e){let t=[],n=e;for(;W.isMemberExpression(n);){if(n.computed)if(W.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(W.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(W.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return W.isIdentifier(n)?t:null}function Qr(e,t=[]){let n=$g(e,t);if(n)return n;let r=Bg(e,t);if(r)return r;let o=Kg(e,t);return o||null}function jn(e){return e?.kind==="api-source"}function $g(e,t){if(e.path.isVariableDeclarator()&&W.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&qi(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return kt(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&W.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>W.isObjectProperty(c)&&Gl(c)==="data"&&Ln(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&qi(a.node))return kt(e.identifier.name,t,"query hook data binding")}let n=Ug(e);if(!n||Gl(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()||!qi(i.node)?null:kt(e.identifier.name,t,"query hook data binding")}function Bg(e,t){if(e.path.isVariableDeclarator()&&W.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!Yl(a.node))return null;let[c,l]=e.path.node.id.elements;return!W.isIdentifier(c)||c.name!==e.identifier.name||!W.isIdentifier(l)?null:Hl(e,l.name)?kt(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()||!Yl(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return W.isIdentifier(s)&&Hl(e,s.name)?kt(e.identifier.name,t,"state setter is updated by API data"):null}function Kg(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()?kt(e.identifier.name,t,"awaited binding result"):es(r.node)?kt(e.identifier.name,t,"fetch-backed binding result"):null:null}function Ug(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 Ln(e,t){return W.isIdentifier(e)?e.name===t:W.isAssignmentPattern(e)?Ln(e.left,t):W.isObjectPattern(e)?e.properties.some(n=>W.isObjectProperty(n)?Ln(n.value,t):Ln(n.argument,t)):W.isArrayPattern(e)?e.elements.some(n=>!!n&&Ln(W.isRestElement(n)?n.argument:n,t)):!1}function Hl(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){es(i.node)&&(n=!0),(Jg(i.node.callee,t)||i.node.arguments.some(s=>W.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function qi(e){let t=to(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Yl(e){return to(e.callee)==="useState"}function es(e){return qr(e,t=>W.isCallExpression(t)&&to(t.callee)==="fetch")}function Vg(e){let t=e;for(;W.isMemberExpression(t);)t=t.object;return W.isIdentifier(t)?t.name:null}function Gl(e){return e.computed?null:W.isIdentifier(e.key)?e.key.name:W.isStringLiteral(e.key)?e.key.value:null}function to(e){return W.isIdentifier(e)?e.name:W.isMemberExpression(e)&&W.isIdentifier(e.property)?e.property.name:null}function Jg(e,t){return qr(e,n=>W.isIdentifier(n)&&n.name===t)}function qr(e,t){if(t(e))return!0;let n=W.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(W.isNode(i)&&qr(i,t))return!0;continue}if(W.isNode(o)&&qr(o,t))return!0}return!1}function Xg(e){return W.isIdentifier(e)?e.name:W.isCallExpression(e)?to(e.callee)??"api":W.isAwaitExpression(e)?"awaited-api":"api"}function kt(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:Wg(e,t),reason:n}}function Wg(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var ql=typeof ts=="function"?ts:ts.default;function eu(e,t){let n=nu(e);if(!n)return{allowed:!0};let r=!1;return ql(n,{CallExpression(o){if(!ru(o.node,t.sourceRange)||!zg(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||jn(eo(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function tu(e,t){let n=nu(e);if(!n)return{allowed:!0};let r=!1;return ql(n,{JSXExpressionContainer(o){ru(o.node,t.sourceRange)&&(fn.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 nu(e){try{return Ql.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function zg(e){let t=e.callee;return fn.isMemberExpression(t)&&fn.isIdentifier(t.property)&&t.property.name==="map"}function ru(e,t){let n=e.loc;return n?Zl({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Zl({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Zl(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}import*as ne from"@babel/types";function ou(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 rt(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Bt(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(ne.isObjectPattern(n)||ne.isArrayPattern(n))return Bt(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(Yg(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Bt(e,t,n=!1){return ne.isIdentifier(e)?e.name===t&&n:ne.isObjectPattern(e)?e.properties.some(r=>ne.isObjectProperty(r)?Bt(r.value,t,n):Bt(r.argument,t,n)):ne.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=ne.isRestElement(r)?r.argument:r;return Bt(o,t,n)}):ne.isAssignmentPattern(e)?Bt(e.left,t,!0):ne.isRestElement(e)?Bt(e.argument,t,n):!1}function pn(e,t){if(e.path.isObjectPattern()){if(t){let r=We(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:rt(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:rt(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=iu(r),i=!1,s=o?o.initBinding&&ns(o.initBinding)?(i=rt(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=pn(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=We(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||rt(e)}}}}let n=Qg(e);if(n){let r=Hg(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||rt(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=Gg(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:rt(e)}}let i=$n(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:rt(e)}:null}if(ns(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:rt(e)}}return null}function Hg(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=iu(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=ns(i)?(a=rt(i),[...s]):(()=>{let u=pn(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=We(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||rt(t)}:null}function iu(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=qg(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function ns(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function Yg(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Gg(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=We(i.node,t);if(a)return a}return null}function su(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=no(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=$n(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=Zg(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=$n(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 no(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=$n(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&We(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=no(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=no(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=no(r,t);if(o)return o}}return null}function We(e,t,n=[]){if(ne.isIdentifier(e))return e.name===t?n:null;if(ne.isObjectPattern(e)){for(let r of e.properties)if(ne.isObjectProperty(r)){let o=$n(r);if(!o)continue;let i=We(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(ne.isRestElement(r)){let o=We(r.argument,t,n);if(o)return o}}if(ne.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=ne.isRestElement(o)?o.argument:o,s=We(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return ne.isAssignmentPattern(e)?We(e.left,t,n):null}function Zg(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function Qg(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 $n(e){return e.computed?null:ne.isIdentifier(e.key)?e.key.name:ne.isStringLiteral(e.key)?e.key.value:null}function qg(e){let t=[],n=e;for(;ne.isMemberExpression(n);){if(n.computed)if(ne.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ne.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ne.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ne.isIdentifier(n)?{base:n.name,path:t}:null}var Pt=typeof rs=="function"?rs:rs.default;function le(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 mn(e){return{file:e.file,component:e.component}}function ey(e){return e.target.kind==="node"?e.target.key:null}function ty(e){return"kind"in e}function ro(e){return!ty(e)}function ls(e,t){let n=pt.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=pt.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function os(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=ut(n,le(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function gs(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 ze(e){try{return hs.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ny(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function ry(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 ie(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Vt(e,t){let n=ie(e);return!!(n&&He(t,n))}function He(e,t){return t.start>=e.start&&t.end<=e.end}function Iu(e){if(x.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(x.isJSXMemberExpression(e)){let t=e;for(;x.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function oy(e,t){let n=ie(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);if(!a||Vt(a.path.node,n))return;t.scope.getBinding(i)!==a&&r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Iu(i.node.name);s&&o(s,i)}}),[...r].sort()}function au(e,t,n){let r=ze(e);if(!r)return{ok:!0};let o=te(r,le(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=te(r,le(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};if(Lu(o.match.path,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let s=oy(o.match.path,i.match.path);return s.length>0?{ok:!1,bindingNames:s}:{ok:!0}}function cu(e,t,n){let r=vt(t,n);return r?ft(e,r):null}function vt(e,t){let n=te(e,le(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:ms(e,t)}function ft(e,t){let n=t.findParent(I=>I.isArrowFunctionExpression()||I.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(I=>I===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=ao(e,u.node),p=r.node.params.map(I=>ao(e,I)),m=ie(i.node),S=ie(r.node);return!f||p.some(I=>I.length===0)||!m||!S?null:{callStart:m.start,callEnd:m.end,callbackStart:S.start,callbackEnd:S.end,collectionExpression:f,callbackParams:p,mapOperator:x.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:Ss(u.node),callbackPath:r,collectionPath:u}}function ao(e,t){let n=ie(t);return n?e.slice(n.start,n.end):""}function oo(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function iy(e,t){let n=ie(e.node);return n?sy(t).some(r=>{let o=ie(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function sy(e){let t=e.callbackPath.node.body;return x.isBlockStatement(t)?Ct(t.body):wt(t)}function Ct(e){let t=[];for(let n of e){if(x.isReturnStatement(n)){n.argument&&t.push(...wt(n.argument));continue}if(x.isBlockStatement(n)){t.push(...Ct(n.body));continue}if(x.isIfStatement(n)){let r=x.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...Ct(r)),n.alternate){let o=x.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...Ct(o))}continue}if(x.isSwitchStatement(n)){for(let r of n.cases)t.push(...Ct(r.consequent));continue}x.isTryStatement(n)&&(t.push(...Ct(n.block.body)),n.handler&&t.push(...Ct(n.handler.body.body)),n.finalizer&&t.push(...Ct(n.finalizer.body)))}return t}function wt(e){return x.isJSXElement(e)?ay(e)?lu(e.children):[e]:x.isJSXFragment(e)?lu(e.children):x.isParenthesizedExpression(e)||x.isTSAsExpression(e)||x.isTSSatisfiesExpression(e)||x.isTSNonNullExpression(e)||x.isTSTypeAssertion(e)?wt(e.expression):x.isConditionalExpression(e)?[...wt(e.consequent),...wt(e.alternate)]:x.isLogicalExpression(e)&&$u(e.operator)?wt(e.right):[]}function lu(e){return e.flatMap(t=>x.isJSXElement(t)||x.isJSXFragment(t)?wt(t):x.isJSXExpressionContainer(t)&&(x.isJSXElement(t.expression)||x.isJSXFragment(t.expression)||x.isConditionalExpression(t.expression)||x.isLogicalExpression(t.expression))?wt(t.expression):[])}function ay(e){let t=e.openingElement.name;return x.isJSXIdentifier(t)?t.name==="Fragment":x.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function cy(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function is(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function uu(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Lu(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=ie(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>Es(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);if(!u||Vt(u.path.node,o)||i.has(u.path.node))return;t.scope.getBinding(c)!==u&&s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Iu(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function du(e,t,n){let r=ie(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Es(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return ys(e,s=>{let a=s.scope.getBinding(s.node.name);if(!a||Vt(a.path.node,r)||o.has(a.path.node))return;t.scope.getBinding(s.node.name)!==a&&i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function ly(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Es(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);if(!l||n.has(l.path.node))return;t.scope.getBinding(a)!==l&&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(x.isIdentifier(l))o(l.name,c);else{let u=uy(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function uy(e){let t=e;for(;x.isTSQualifiedName(t);)t=t.left;return x.isIdentifier(t)?t.name:null}function ku(e,t){let n=ie(e.node),r=new Set;return ys(e,o=>{let i=o.scope.getBinding(o.node.name);if(!i||n&&Vt(i.path.node,n))return;t.scope.getBinding(o.node.name)!==i&&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 ys(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function dy(e){let t=fy(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Bu(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=Cy({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Du(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?Ss(o):!0}}}function fy(e,t,n){let r=Ru(e,t);if(wu(e,r),Pu(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 Pt(e,{JSXElement(s){Ou(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:xs(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 py(e){if(!e.knownSourceFiles)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without project-wide source visibility"};if(!e.routeEntryFiles)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without registered route visibility"};let t=new Set(e.knownSourceFiles.map(a=>Kn(a.file)));if(!t.has(Kn(e.sourceFile))||!t.has(Kn(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(Kn(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=yy(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=ze(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=my(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=vu({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!Ye(s.file,e.targetFile)||xs(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}}function my(e,t){let n=new Map,r=i=>{let s=hn(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 hy(i,n))o=r(s)||o}return[...n.values()]}function hy(e,t){let n=[],r=gy(e,t);for(let o of e.ast.program.body){if(x.isExportDefaultDeclaration(o)&&x.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=Vn(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(x.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Jn(e.file,o.source.value);for(let s of o.specifiers){if(x.isExportNamespaceSpecifier(s)){let l=Rt(s.exported);for(let u of t.values())Ye(u.file,i)&&n.push({file:e.file,namespace:us(l,u.namespace),exportName:u.exportName});continue}if(!x.isExportSpecifier(s))continue;let a=Rt(s.local),c=[...t.values()].filter(l=>Ye(l.file,i)&&Kt(l.namespace,a));if(c.length>0){let l=Rt(s.exported);for(let u of c){let f=Vn(u.namespace,a,l);f&&n.push({file:e.file,namespace:f,exportName:u.exportName})}continue}t.has(hn({file:i,exportName:a}))&&n.push({file:e.file,exportName:Rt(s.exported)})}continue}if(x.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!x.isExportSpecifier(i))continue;let s=Rt(i.local),a=r.get(s)??[];if(a.length>0){let c=Rt(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=Vn(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(x.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Jn(e.file,o.source.value),s=o.exported;if(s){let a=Rt(s);for(let c of t.values())Ye(c.file,i)&&n.push({file:e.file,namespace:us(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())Ye(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function us(e,t){return t?`${e}.${t}`:e}function Kt(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Vn(e,t,n){return!Kt(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function gy(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(!x.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Jn(e.file,i.source.value);for(let a of i.specifiers){if(x.isImportDefaultSpecifier(a)){let c=t.get(hn({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>Ye(u.file,s)&&Kt(u.namespace,"default"));for(let u of l){let f=Vn(u.namespace,"default",a.local.name);f&&r(a.local.name,{...u,namespace:f})}continue}if(x.isImportSpecifier(a)){let c=Rt(a.imported),l=[...t.values()].filter(f=>Ye(f.file,s)&&Kt(f.namespace,c));for(let f of l)r(a.local.name,f);let u=t.get(hn({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(x.isImportNamespaceSpecifier(a))for(let c of t.values())Ye(c.file,s)&&r(a.local.name,{...c,namespace:us(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(x.isVariableDeclaration(i))for(let s of i.declarations){if(!x.isIdentifier(s.id)||!s.init)continue;let a=gn(s.init);if(!a||!x.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(hn));for(let f of c){let p=Vn(f.namespace,a.name,s.id.name),m=p?{...f,namespace:p}:f,S=hn(m);u.has(S)||(r(s.id.name,m),u.add(S),o=!0)}}}return n}function hn(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${fs(e.file)}#${t}`}function Rt(e){return x.isIdentifier(e)?e.name:e.value}function yy(e,t){for(let n of e.program.body){if(x.isExportDefaultDeclaration(n)){let o=n.declaration;if((x.isFunctionDeclaration(o)||x.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(x.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!x.isExportNamedDeclaration(n))continue;let r=n.declaration;if((x.isFunctionDeclaration(r)||x.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(x.isVariableDeclaration(r)){for(let o of r.declarations)if(x.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!x.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:x.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function vu(e){let t=xy(e),n=[],r=Pu(e.ast,t);return Pt(e.ast,{JSXElement(o){Ye(e.file,e.sourceFile)&&xs(o)===e.sourceComponent||Ou(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Cu(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Ru(e,t){let n=Cu();return Pt(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function xy(e){let t=Cu();return Ye(e.file,e.sourceFile)&&Ey(t,Ru(e.ast,e.sourceComponent)),Pt(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Jn(e.file,o),s=e.componentIdentities.filter(a=>Ye(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(x.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),x.isImportDefaultSpecifier(a)){let l=s.filter(u=>Kt(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let f of l){let p=pu(f,"default");p&&u.add(p)}t.namespaceMembers.set(c,u)}continue}if(x.isImportSpecifier(a)){let l=x.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(f=>Kt(f.namespace,l));if(u.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let p of u){let m=pu(p,l);m&&f.add(m)}t.namespaceMembers.set(c,f);continue}s.some(f=>!f.namespace&&f.exportName===l)&&t.localBindings.add(c);continue}if(x.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)}}}}}),wu(e.ast,t),t}function Ey(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 wu(e,t){Pt(e,{VariableDeclarator(n){if(!n.node.init)return;let r=gn(n.node.init);if(r){if(x.isIdentifier(n.node.id)){let o=Ut(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&ds(t,i,o);return}if(x.isObjectPattern(n.node.id)){let o=Ut(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Nu(n.node.id,o.namespaceMembers,t,n)}}}})}function Pu(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Pt(e,{ReferencedIdentifier(r){if(n){r.stop();return}Sy(r)||!r.isIdentifier()||!Au(r,t)||by(r,t)||Iy(r)||(n=!0,r.stop())}}),n}function Sy(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 Au(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)&&Ut(r.node,t,r)?r:null}function by(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!fu(e,r))return!1;let o=Au(e,t);if(!o)return!1;if(gn(r.node)===o.node)return!!Ut(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&fu(e,a)&&!!Ut(a.node,t,a)}function Iy(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function fu(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Ut(e,t,n){let r=gn(e);if(!r)return null;if(x.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(x.isObjectExpression(r))return ky(r,t,n);let o=Mu(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?Tu(s,o.slice(1).join(".")):null}function ky(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!x.isObjectProperty(i))continue;let s=Fu(i);if(!s||!x.isExpression(i.value)){x.isExpression(i.value)&&(o||=Ut(i.value,t,n)!==null);continue}let a=Ut(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 Tu(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 ds(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 Nu(e,t,n,r){for(let o of e.properties){if(x.isRestElement(o)){if(x.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&ds(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!x.isObjectProperty(o))continue;let i=Fu(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Tu(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=x.isAssignmentPattern(o.value)?o.value.left:o.value;if(x.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&ds(n,c,s);continue}if(x.isObjectPattern(a)&&s.namespaceMembers.size>0){Nu(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Fu(e){return e.computed?x.isStringLiteral(e.key)||x.isNumericLiteral(e.key)?String(e.key.value):null:vy(e.key)}function vy(e){return x.isIdentifier(e)?e.name:x.isStringLiteral(e)||x.isNumericLiteral(e)?String(e.value):null}function gn(e){return x.isParenthesizedExpression(e)||x.isTSAsExpression(e)||x.isTSSatisfiesExpression(e)||x.isTSNonNullExpression(e)||x.isTSTypeAssertion(e)?gn(e.expression):x.isExpression(e)?e:null}function Mu(e){if(x.isIdentifier(e))return[e.name];if((x.isMemberExpression(e)||x.isOptionalMemberExpression(e))&&!e.computed&&x.isIdentifier(e.property)){let t=gn(e.object),n=t?Mu(t):null;return n?[...n,e.property.name]:null}return null}function pu(e,t){if(!Kt(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 Ou(e,t){let n=e.node.openingElement.name;if(x.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=_u(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 _u(e){if(x.isJSXIdentifier(e))return[e.name];if(x.isJSXMemberExpression(e)){let t=_u(e.object);return t?[...t,e.property.name]:null}return null}function xs(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()&&x.isIdentifier(n.node.id))return n.node.id.name}return null}function Cy(e){let t=ie(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||Vt(a.path.node,t))return;let c=Py(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 u=Ty(e.callSitePath,c.propName,e.source);if(!u.ok){o=u.reason;return}let f=Ry(u.expression,c.remainingPath);if(!f){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let p=ku(u.expressionPath,e.targetParentPath);if(!p.ok){o=p.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${p.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:f});return}e.targetParentPath.scope.getBinding(s.node.name)!==a&&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:Ny(e.source,t,[...n.values()])}}function Ry(e,t){if(t.length===0)return e;let n=Du(e);if(!n)return null;let r=Ss(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=wy(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function wy(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function Py(e,t,n){let r=Ay(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=pn(t,o);if(!i)return null;let s=r?.range??ie(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function Ay(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Vt(n.node,t)||n.node.computed||!x.isIdentifier(n.node.property))return null;let r=ie(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Ty(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()&&x.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=ao(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 Ny(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 Du(e){try{let n=hs.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=x.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&x.isExpression(r)?r:null}catch{return null}}function Fy(e){let t=ie(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||Vt(s.path.node,t))return;let a=mu(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=mu(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!My(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 ys(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 My(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 mu(e,t,n){let r=Oy(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Jn(t,i),a=i.startsWith(".")?ls(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=x.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 Oy(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Jn(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?pt.normalize(pt.join(pt.dirname(e),t)).replace(/\\/g,"/"):t}function Ye(e,t){return fs(e)===fs(t)}function fs(e){let t=Kn(e);return t.endsWith("/index")?t.slice(0,-6):t}function Kn(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Es(e){let t=[],n=r=>{if(r){if(x.isIdentifier(r)){t.push(r.name);return}if(x.isObjectPattern(r)){for(let o of r.properties){if(x.isRestElement(o)){n(o.argument);continue}x.isObjectProperty(o)&&n(o.value)}return}if(x.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(x.isAssignmentPattern(r)){n(r.left);return}if(x.isRestElement(r)){n(r.argument);return}x.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function _y(e){let t=[];for(let n of e.callbackPath.node.params){if(x.isIdentifier(n)){t.push(n.name);continue}if(x.isRestElement(n)&&x.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 Dy(e,t){return{...e,callbackParams:t}}function hu(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function Ss(e){return!(x.isIdentifier(e)||x.isThisExpression(e)||x.isMemberExpression(e)||x.isOptionalMemberExpression(e)||x.isCallExpression(e)||x.isOptionalCallExpression(e))}function Lu(e,t){return ju(e,t).length>0}function ss(e,t){let n=ie(e.node),r=ie(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()&&!Ly(o,n,r)))return!0;o=o.parentPath}return!1}function Ly(e,t,n){let r=ie(e.node.consequent);if(r&&He(r,t)&&!He(r,n))return!1;let o=e.node.alternate?ie(e.node.alternate):null;return!(o&&He(o,t)&&!He(o,n))}function ju(e,t){let n=ie(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=ie(o.node.consequent),a=ie(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()&&$u(o.node.operator)){let s=ie(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 gu(e,t,n,r){let o=ju(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=ao(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=jy(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${By(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function jy(e,t){return $y(e.node)?t:`(${t})`}function $y(e){return x.isIdentifier(e)||x.isThisExpression(e)||x.isSuper(e)||x.isMemberExpression(e)||x.isOptionalMemberExpression(e)||x.isCallExpression(e)||x.isOptionalCallExpression(e)||x.isBooleanLiteral(e)||x.isNumericLiteral(e)||x.isStringLiteral(e)||x.isNullLiteral(e)||x.isUnaryExpression(e)}function $u(e){return e==="&&"||e==="||"||e==="??"}function By(e){return e.trim().startsWith("<")?e:`(${e})`}function Bu(e,t){let n=ie(e.node),r=ie(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=yu(e),i=yu(t);if(!o||!i||!Ky(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=Uy(s.node,n);if(a&&!He(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=ie(s.node.right);if(a&&He(a,n)&&!He(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())&&Vy(s)){let a=ie(s.node.body)??ie(s.node);if(a&&!He(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 yu(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?ie(t.node.argument):null;if(t.isArrowFunctionExpression()&&(x.isJSXElement(t.node.body)||x.isJSXFragment(t.node.body)||x.isConditionalExpression(t.node.body)||x.isLogicalExpression(t.node.body)))return ie(t.node.body);t=t.parentPath}return null}function Ky(e,t){return e.start===t.start&&e.end===t.end}function Uy(e,t){let n=ie(e.consequent);if(n&&He(n,t))return n;let r=ie(e.alternate);return r&&He(r,t)?r:null}function Vy(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}var Jy={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 io(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=Jy[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 Xy(e,t){for(let n of e.program.body){if(!x.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>x.isImportDefaultSpecifier(o));if(r&&x.isImportDefaultSpecifier(r))return r.local.name}return null}function Wy(e,t,n){for(let r of e.program.body){if(!x.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>x.isImportSpecifier(i)&&(x.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&x.isImportSpecifier(o))return o.local.name}return null}function xu(e){let t=new Set;return Pt(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function Eu(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function zy(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=gs(e),o=ze(t);if(n.exportName!=="default"){let a=o?Wy(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?Eu(r,xu(o)):r;return{localName:c,importStep:as(e,c)}}if(!o)return{localName:r,importStep:as(e,r)};let i=Xy(o,n.source);if(i)return{localName:i};let s=Eu(r,xu(o));return{localName:s,importStep:as(e,s)}}function Hy(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??gs(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 Yy(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?Gy(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function Gy(e){return Object.fromEntries(Object.entries(e).filter(t=>ps(t[1])))}function ps(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(ps):typeof e=="object"?Object.values(e).every(ps):!1}function Zy(e,t){let n=ze(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=vu({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 as(e,t=gs(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 Su(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 Qy(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Bn(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function bs(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Un(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:bs(e,t.slice(0,n)),index:r.index}}return null}function cs(e,t){return e.locator?e.collectionPathMap?.[t]?bs(e.locator,e.collectionPathMap[t]):Un(e.locator)?ex(e.locator,tx(t,e.collectionIndexMap)):null:null}function qy(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:Ku(o,t)}function Ku(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Ku(r,t);return o===void 0?void 0:{[n.name]:o}}function so(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 ex(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},bs(e,i)}return null}function tx(e,t){return t?.[e]??e}function bu(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 nx(e,t){return rx(e.root,t.root)&&ix(e.path??[],t.path??[])}function rx(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&&ox(e.sourceRange,t.sourceRange)}}function ox(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function ms(e,t){let n=null;return Pt(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 ix(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 co=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:Bn(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:Bn(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:Bn(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:Bn(t.kind,t.params.kind)};let r=t;if(!ro(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Su(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:Bn(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=ey(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.routeId&&n.routeId&&n.params.routeId!==n.routeId?{ok:!1,errorCode:"stale-version",reason:"The className source route changed before save."}: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.buildSetPropsSteps({initialOrder:0,node:r,props:n.params.props,request:n});return i.ok?this.buildPlan(t,n,i.steps,o):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.buildSetPropsSteps({initialOrder:s.length,node:r,props:n.params.props,request:n});if(!a.ok)return a;s.push(...a.steps)}return this.buildPlan(t,n,s,i)}async buildSetPropsSteps(t){let{initialOrder:n,node:r,props:o,request:i}=t,s=r.file,a=[],c={};for(let[l,u]of Object.entries(o)){if(u===void 0)continue;let f=await this.graph.getElementPropertyWriteTarget?.(r.key,l),p=r.attributes?.find(m=>m.name===l);if(!(typeof p?.resolvedValue=="string"&&p.resolvedValue===u||p?.source===null&&p.value===u)){if(f?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`set-props cannot overwrite readonly external property '${l}'`};if(f?.kind==="value-binding"&&f.locator){let m=f.locator;if(f.sourceKind==="repeat-template"&&typeof i.selectionRef?.instanceIndex=="number"){let S=cs(f,i.selectionRef.instanceIndex);if(!S)return{ok:!1,errorCode:"invalid-params",reason:"set-props could not resolve the selected repeat item"};m=S}a.push({order:n+a.length,file:f.file,type:"update-value",locator:m,value:u});continue}c[l]=u}}return Object.keys(c).length>0&&a.push({order:n+a.length,file:s,type:"set-props",locator:le(r),props:c}),{ok:!0,steps:a}}buildTextRewriteSteps(t,n,r,o,i){if(o?.kind==="value-binding"&&o.locator){if(o.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let a=cs(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:le(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=ze(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=te(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!ny(a.match.path))return{ok:!0,value:r};let c=ry(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=cs(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.buildPlan(t,n,[{order:0,file:o.file,type:"update-array-item",locator:c,value:l.value}],r):l}planUpdateText(t,n,r,o,i){if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let s=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return s.ok?this.buildPlan(t,n,s.steps,o):s}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 p=Un(f.locator);if(p)return this.buildPlan(t,n,[{order:0,file:f.file,type:"remove-bound-array-item",locator:p.locator,index:p.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=so(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:le(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||Zy(n,t)>1)return null;let r=ls(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(!ro(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=so(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 p=this.getRepeatBackedTemplateStructureReason(r);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let m=eu(this.graph.getFileContent(r.file),r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot insert child into this node"};let S=io(r,n.params.node);if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S};let I=[],v=0,C=n.params.node.kind==="component-call"?zy(n.params.node,this.graph.getFileContent(r.file)):void 0,A=C?.importStep;return A&&I.push({order:v++,file:r.file,type:"add-import",moduleSpecifier:A.moduleSpecifier,imports:A.imports}),I.push({order:v++,file:r.file,type:"insert-child",parentLocator:le(r),node:{jsx:Hy(n.params.node,C?.localName)},placement:n.params.position.relation,anchorLocator:i?le(i):void 0}),this.buildPlan(t,n,I,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!ro(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:Yy(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(!ro(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=Un(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=qy(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"?bu(0,a.collectionIndexMap):bu(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=so(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 this.isRepeatTemplateRootNode(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:")||this.isInsideMapCallback(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}isRepeatTemplateRootNode(t){let n=ze(this.graph.getFileContent(t.file));if(!n)return t.isRepeatItemRoot===!0;let r=te(n,le(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ms(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=ft(this.graph.getFileContent(t.file),o);return i?iy(o,i):t.isRepeatItemRoot===!0}isInsideMapCallback(t){let n=ze(this.graph.getFileContent(t.file));if(!n)return!1;let r=te(n,le(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ms(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}planRepeatTemplateInternalMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=ze(c);if(!l)return null;let u=vt(l,r),f=vt(l,o);if(!u||!f)return null;let p=ft(c,u),m=ft(c,f);if(!oo(p,m))return null;if(a&&(s==="before"||s==="after")){let I=vt(l,a),v=I?ft(c,I):null;if(!oo(p,v))return null}if(ss(u,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let S=au(c,r,o);return S.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:le(r),targetParentLocator:le(o),placement:s,anchorLocator:a?le(a):void 0,selectionContext:mn(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:S.reason??`Cannot move node because it depends on bindings outside the target scope: ${S.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=ze(c);if(!l)return null;let u=vt(l,r),f=vt(l,o);if(!u||!f)return null;let p=ft(c,u);if(!p)return null;let m=ft(c,f);if(oo(p,m))return null;if(m&&!cy(m,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let T=cu(c,l,a);if(m&&!oo(m,T)||!m&&T)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 T=io(o,{kind:"native-tag",tag:r.tag});if(T)return{ok:!1,errorCode:"unsupported-operation",reason:T}}let S=os(this.graph,r);if(!S)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(ss(u,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let I=gu(c,u,f,S);for(let T of I.conditionPaths){let G=du(T,f,p);if(!G.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${G.bindingNames.join(", ")}`}}let v=uu(u,f,p,{preserveConditionalBoundary:I.conditionPaths.length>0});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${v.bindingNames.join(", ")}`};let C=ly(p,f);if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${C.bindingNames.join(", ")}`};let A=p;if(r.component!==o.component){let T=dy({source:c,ast:l,sourceContext:p,sourceNode:r,targetParent:o,targetParentPath:f});if(!T.ok)return{ok:!1,errorCode:"unsupported-operation",reason:T.reason};A=T.context}else{let T=ku(p.collectionPath,f);if(!T.ok)return{ok:!1,errorCode:"unsupported-operation",reason:T.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${T.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:le(r),targetParentLocator:le(o),placement:s,anchorLocator:a?le(a):void 0,repeatExpression:hu(A,I.sourceJsx),selectionContext:mn(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),u=ze(c),f=ze(l);if(!u||!f)return null;let p=py({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let m=vt(u,r),S=vt(f,o);if(!m||!S)return null;let I=Bu(p.callSitePath,S);if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason};let v=ft(c,m);if(!v)return null;if(ft(l,S))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&cu(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 D=io(o,{kind:"native-tag",tag:r.tag});if(D)return{ok:!1,errorCode:"unsupported-operation",reason:D}}let A=os(this.graph,r);if(!A)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(ss(m,S))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let T=gu(c,m,S,A);for(let D of T.conditionPaths){let L=du(D,S,v);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 G=uu(m,S,v,{preserveConditionalBoundary:T.conditionPaths.length>0});if(!G.ok)return{ok:!1,errorCode:"unsupported-operation",reason:G.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${G.bindingNames.join(", ")}`};let fe=Fy({sourceFile:r.file,targetFile:o.file,sourceContext:v,targetParentPath:S});if(!fe.ok)return{ok:!1,errorCode:"unsupported-operation",reason:fe.reason};let ue=_y(v);if(!ue.ok)return{ok:!1,errorCode:"unsupported-operation",reason:ue.reason};let R=Dy(v,ue.callbackParams),_=[{order:0,file:r.file,type:"remove-node",locator:le(r),removeWhitespace:!0}];for(let D of fe.imports)_.push({order:_.length,file:o.file,type:"add-import",moduleSpecifier:D.moduleSpecifier,imports:D.imports});return _.push({order:_.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:le(o),expression:hu(R,T.sourceJsx),placement:s,anchorLocator:a?le(a):void 0,selectionContext:mn(o)}),this.buildPlan(t,n,_,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};let i=Su(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(Qy(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 C=n.params.target.relation,A=i.anchorNode&&(C==="before"||C==="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:C,anchorSourceId:A?.kind==="external-entry"?A.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=so(r,a,this.graph.getTextProvenance?.(r.key,0)??null);if(f&&!is(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 C=a,A=await this.graph.getTextWriteTarget(u.key,0);if(C?.kind==="value-binding"&&A?.kind==="value-binding"&&C.locator&&A.locator){let T=Un(C.locator),G=Un(A.locator);if(T&&G&&C.file===A.file&&nx(T.locator,G.locator)){let fe=T.index,ue=G.index,R=l==="before"?ue-(fe<ue?1:0):ue+(fe<ue?0:1);return this.buildPlan(t,n,[{order:0,file:C.file,type:"move-array-item",locator:T.locator,fromIndex:fe,toIndex:R}],o)}}}if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let p=this.getRepeatBackedTemplateStructureReason(r),m=is(f)?f:p;if(m&&is(m)){let C=this.planRepeatTemplateInternalMove(t,n,r,s,o,l,u);if(C)return C;let A=this.planRepeatTemplateHoistMove(t,n,r,s,o,l,u);if(A)return A;let T=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,l,u);return T||{ok:!1,errorCode:"unsupported-operation",reason:m}}if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let S=await this.getUpstreamBackedDescendantReason(r);if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S};if(r.tag&&r.tag.toLowerCase()===r.tag){let C=io(s,{kind:"native-tag",tag:r.tag});if(C)return{ok:!1,errorCode:"unsupported-operation",reason:C}}if(c)return this.planCrossFileMove(t,n,r,s,o,l,u);let I=au(this.graph.getFileContent(r.file),r,s);if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason??`Cannot move node because it depends on bindings outside the target scope: ${I.bindingNames.join(", ")}`};let v=[{order:0,file:r.file,type:"move-node",locator:le(r),targetParentLocator:le(s),placement:l,anchorLocator:u?le(u):void 0,selectionContext:mn(s)}];return this.buildPlan(t,n,v,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),f=os(this.graph,r)??`<${r.component} />`,p=tu(u,r);if(!p.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:le(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let S=r.tag??r.component,v={moduleSpecifier:ls(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:S}]:[{kind:"named",imported:r.exportName,local:S===r.exportName?void 0:S}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:v.moduleSpecifier,imports:v.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:le(o),node:{jsx:f},placement:s,anchorLocator:a?le(a):void 0,selectionContext:mn(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:le(o),node:{jsx:f},placement:s,anchorLocator:a?le(a):void 0,selectionContext:mn(o)});let m=this.buildRemoveComponentImportStep(r,u);return m&&c.push({...m,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:ae(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};import Xn from"node:path";import*as qu from"@babel/parser";import Is from"@babel/traverse";import*as E from"@babel/types";var ed=typeof Is=="function"?Is:Is.default;function td(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var Uu=new WeakMap;function Vu(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 nd(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Fs(s,t,n);if(!a)return null;let c=Ms(a,r.sourceRange);if(!c)return null;let l=r.source??await Ze({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await Bs({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});if(!m)return null;if(m.kind==="external")return{kind:"external-entry",file:m.file,sourceType:m.sourceType,sourceId:m.sourceId,adapterId:m.adapterId,displayExpression:m.displayPath};let S={kind:"value",root:m.root,path:m.path.length>0?m.path:[]};return{kind:"value-binding",file:m.file,locator:S,root:m.root,path:m.path,displayExpression:m.displayExpression??Hn(c.node,n),sourceKind:m.sourceKind,...m.collectionIndexMap?{collectionIndexMap:m.collectionIndexMap}:{},...m.collectionPathMap?{collectionPathMap:m.collectionPathMap}:{}}}let u=new Set,f=await Mx({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});if(!f)return null;if(f.kind==="external")return{kind:"external-entry",file:f.file,sourceType:f.sourceType,sourceId:f.sourceId,adapterId:f.adapterId,displayExpression:f.displayPath};let p={kind:"value",root:f.root,path:f.path.length>0?f.path:[]};return{kind:"value-binding",file:f.file,locator:p,root:f.root,path:f.path,displayExpression:f.displayExpression??l.expression,sourceKind:f.sourceKind,...f.collectionIndexMap?{collectionIndexMap:f.collectionIndexMap}:{},...f.collectionPathMap?{collectionPathMap:f.collectionPathMap}:{}}}async function rd(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Fs(i,t,n);if(!s)return null;let a=e.expression!==void 0?(e.sourceRange?ad(s,n,e.expression,e.sourceRange):null)??Ds(s,n,e.expression):e.sourceRange?Ms(s,e.sourceRange):null;if(!a)return null;let c=lx(a),l=new Set,u=e.sourceInfo??await Ze({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),f=u?await Fe({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 zx({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 cx(f,e.expression??Hn(c.node,n))}async function Ns(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Fs(i,t,n);if(!s)return Ne("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?ux({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}):dx({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}function od(e){try{return qu.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Fs(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=od(n);return e.set(t,{source:n,ast:o}),o}function Ms(e,t){let n=null,r=-1;for(let o of zn(e).expressions){let i=o.node.loc;if(!i||!Os(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function sx(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of zn(e).expressions){if(!ax(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function id(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of zn(e).jsxElements){let i=o.node.loc;if(!i||!Os(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function zn(e){let t=Uu.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return ed(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),Uu.set(e,n),n}function ax(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 Os(e,t){let n=Ju({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=Ju({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function sd(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 Ju(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}async function Ze(e){if(E.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!E.isMemberExpression(e.expression))return null;let t=await xd(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:Hn(e.expression,e.source),base:t.base,path:t.path}:null}function cx(e,t){if(!e)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}:{}}}function lx(e){if(e.isLogicalExpression()&&(e.node.operator==="||"||e.node.operator==="??")){let t=e.get("left");if(!Array.isArray(t)&&t.isExpression())return t}return e}function Hn(e,t){if(t)return _s(e,t);let n=oE(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function _s(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Ds(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of zn(e).expressions){if(_s(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function ad(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of zn(e).expressions){if(_s(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!Os(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}async function ux(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Ms(r,o.sourceRange),u=o.source??(l?await Ze({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null);if(!u){if(!l)return fx(t,o.value);let p=await Bs({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return p?p.kind==="external"?Yu(t,p):Ps(t,Hn(l.node,n),p):px({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Ne("unsupported-expression","Unable to locate text expression for provenance resolution");let f=await Fe({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 p=ws(l.node);if(p)return Ne(p.code,p.message);let m=l.scope.getBinding(u.base);if(m?.path.isVariableDeclarator()){let S=ws(m.path.node.init);if(S)return Ne(S.code,S.message)}return m?.path.isVariableDeclarator()&&E.isCallExpression(m.path.node.init)?mx("unsupported-expression",fd(m.path.node.init,e.functionCallContracts)):Ne("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return f.kind==="external"?Yu(t,f):Ps(t,u.expression,f)}async function dx(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Ne("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Ds(r,n,o.conditionExpression);if(!l)return Ne("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await Fe({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 Ne("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Ne("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=Ps(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 fx(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 px(e){let t=await ld(e);if(t.length===0)return Ne("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(hx(e.expression))return cd(t);if(dd(e.expression))return Ne("unsupported-expression","i18n helpers require a static message id string");if(E.isMemberExpression(e.expression)&&e.expression.computed&&!E.isNumericLiteral(e.expression.property)&&!E.isStringLiteral(e.expression.property))return Ne("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Ne(n.code,n.message)}function Ne(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function mx(e,t){return cd([{code:e,message:t}])}function cd(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function hx(e){return E.isCallExpression(e)||E.isConditionalExpression(e)||E.isLogicalExpression(e)||E.isBinaryExpression(e)}function Wn(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 ld(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=ws(t);if(l)return[l];if(E.isCallExpression(t))return[{code:"unsupported-expression",message:fd(t,c)}];if(E.isMemberExpression(t)&&t.computed){let u=t.property;if(!E.isNumericLiteral(u)&&!E.isStringLiteral(u)){if(!E.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let p=await Qe(u,n,r,o,i,s,a);if(typeof p!="string"&&!Number.isInteger(p))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return E.isBinaryExpression(t)?Wn([...await ks(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):E.isLogicalExpression(t)?Wn([...await ks(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"}]):E.isConditionalExpression(t)?Wn([...await ks(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 ws(e){return dd(e)?Xu("i18n helpers require a static message id string"):Sx(e)?Xu("CMS helpers require static entry id and field path string arguments"):null}async function ks(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await ld({...t,expression:o}));return r}function gx(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:[yx(e.sourceType)]}}async function Ls(e){for(let n of vx){if(!Wu(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Hu(zu(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(!Wu(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Hu(zu(r),e.externalAdapters)}return null}function yx(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function xx(e){return{code:"external-source-readonly",message:e}}function Xu(e){return{code:"unsupported-expression",message:e}}function js(e){return!e||!E.isCallExpression(e)?null:E.isIdentifier(e.callee)?e.callee.name:E.isMemberExpression(e.callee)&&!e.callee.computed&&E.isIdentifier(e.callee.object)&&E.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Wu(e,t){if(!t||t.length===0)return!0;let n=js(e.node);return n?t.includes(n):!1}function zu(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Wn(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Hu(e,t){let n=gx(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:Wn([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function Ex(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!E.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!E.isStringLiteral(n)||!E.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 Sx(e){return!!e&&E.isCallExpression(e)&&E.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!E.isStringLiteral(e.arguments[0])||!E.isStringLiteral(e.arguments[1]))}function ud(e){if(!(!e||!E.isCallExpression(e))){if(E.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&E.isStringLiteral(t)?t.value:null}if(E.isMemberExpression(e.callee)&&!e.callee.computed&&E.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&E.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!E.isObjectExpression(t))return null;for(let n of t.properties)if(E.isObjectProperty(n)&&!n.computed&&(E.isIdentifier(n.key)&&n.key.name==="id"||E.isStringLiteral(n.key)&&n.key.value==="id")&&E.isStringLiteral(n.value))return n.value.value;return null}}}function dd(e){return ud(e)===null}async function bx(e,t,n){let r=new Set,o=Xn.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Xn.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"]:[Xn.posix.join(i,"locales"),Xn.posix.join(i,"messages")];for(let a of s){let c=Xn.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function Ix(e){let t=ud(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await bx(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function kx(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!E.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!E.isExpression(n))return null;let o=await Qe(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:[xx("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var vx=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>Ex(e)},{helperNames:["apiField"],resolve:e=>kx(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>Ix({currentFile:e,expressionPath:t,exists:n})}];function Yu(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 Ps(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=Fx(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:!0}):n.sourceKind==="imported-binding"?c.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:!0}):n.sourceKind==="repeat-template"&&c.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:!0}),n.path.length>0&&n.sourceKind!=="repeat-template"&&c.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:!0}),i&&c.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:!0}),{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:c,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var Cx=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function $s(e,t){let n=[...Cx,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function fd(e,t){let n=e.callee;return E.isIdentifier(n)&&$s(n.name,t)?.purity==="side-effect"?`Helper "${n.name}" is registered as side-effectful and remains readonly`:"Function calls are recognized but remain readonly until a pure-call strategy is registered"}async function Bs(e){let t=await Ls(e);if(t)return t;let n=await pd({...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 Ze({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 Fe({...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 Tx(e)}async function pd(e){let t=await Ge({...e,allowComposed:!1});return t?.kind==="source"?t.provenance:null}async function Ge(e){let t=Rx(e.expressionPath),n=Ax(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 Ze({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 Fe({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 Ze({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 Fe({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 Ge({...e,expressionPath:r,allowComposed:!0}),a=await Ge({...e,expressionPath:o,allowComposed:!1}),c=await Ge({...e,expressionPath:i,allowComposed:!1});return vs(s,a,c)}if(t.isCallExpression())return wx({...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 Ge({...e,expressionPath:r,allowComposed:!0}),s=await Ge({...e,expressionPath:o,allowComposed:!0});return vs(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 Ge({...e,expressionPath:r,allowComposed:!0}),s=await Ge({...e,expressionPath:o,allowComposed:!0});return vs(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Ge({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Rx(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 wx(e){let t=js(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:Ge({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(E.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Ge({...e,expressionPath:o,allowComposed:!1})}}return null}function vs(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!Px(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function Px(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 Ax(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function Tx(e){if(!e.expressionPath.isCallExpression())return null;let t=js(e.expressionPath.node);if(!t)return null;let n=$s(t,e.functionCallContracts);if(!n||n.purity!=="pure")return null;let r=n.sourceArgIndex??0,o=e.expressionPath.get(`arguments.${r}`);return!o||Array.isArray(o)||!o.isExpression()?null:await md({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})}async function md(e){let t=await Ls({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 Ze({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 Fe({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 Bs({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 Nx(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!E.isCallExpression(t))return null;let n=t.callee;if(!E.isIdentifier(n))return null;let r=$s(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}`);return!s||Array.isArray(s)||!s.isExpression()?null:await md({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})}function Fx(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=lo(t,e.path);return{sourceId:o,displayPath:o}}async function Mx(e){let t=e.segment.source;return t?Fe({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 Fe(e){let t=e.sourceInfo,n=hd(e.expressionPath,t.base);if(n){let l=await gd({currentFile:e.currentFile,callPath:n.callPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:e.fileCache,visited:e.visited});if(!l){let I=_x(n.callPath,[...n.basePath,...t.path]);return jn(I)?Vu(e.currentFile,I.sourceId,I.displayPath):null}let u=iE(l,[...n.basePath,...t.path]),f=l.collectionIndexMap?.[0]??0,p=[...l.pathPrefix??[],{kind:"index",index:f},...n.basePath,...t.path],m=[{kind:"index",index:0},...n.basePath,...t.path];return ot(l.value,m)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??p,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;let o=ou(r);if(o){let l=o.expressionPath,u=await Ze({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 Fe({...e,expressionPath:l,sourceInfo:{...u,expression:lo(u.expression,t.path),path:[...u.path,...t.path]}});if(f)return f}if(t.path.length===0){let f=await pd({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 Qx({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 Nx({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=Qr(r,t.path);if(jn(s))return Vu(e.currentFile,s.sourceId,s.displayPath);let a=await yn({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:ot(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}function hd(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=We(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!Ox(s,r)?null:{callPath:s,basePath:i}}function Ox(e,t){let n=e.node.callee;return!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}async function gd(e){let{currentFile:t,callPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.node.callee;if(!E.isMemberExpression(a)||!E.isIdentifier(a.property)||a.property.name!=="map")return null;let c=n.get("callee");if(!c.isMemberExpression())return null;let l=c.get("object");if(Array.isArray(l)||!l.isExpression())return null;let u=await Yn({currentFile:t,expressionPath:l,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return!u||!Array.isArray(u.value)||u.value.length===0?null:u}function _x(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:eo(r,t)}async function Yn(e){let{currentFile:t,expressionPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e;if(n.isIdentifier()){let a=n.scope.getBinding(n.node.name);if(!a)return null;let c=await yn({currentFile:t,binding:a,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return c?.kind==="static"?c:null}if(n.isCallExpression())return yd({currentFile:t,callPath:n,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(n.isTSAsExpression()||n.isTSSatisfiesExpression()||n.isTSNonNullExpression()){let a=n.get("expression");if(!Array.isArray(a)&&a.isExpression())return Yn({...e,expressionPath:a})}if(n.isArrayExpression()){let a=sd(n.node);if(!a)return null;let c=await Qe(n.node,n.scope,t,r,o,i,s);return Array.isArray(c)?{kind:"static",file:t,root:{kind:"expression",sourceRange:a},value:c,sourceKind:"binding"}:null}if(n.isMemberExpression()){let a=await Ze({expression:n.node,scope:n.scope,currentFile:t,readFile:r,exists:o,fileCache:i,visited:s});if(!a)return null;let c=await Fe({currentFile:t,expressionPath:n,sourceInfo:a,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(!c||c.kind==="external")return null;let l=await Dx({currentFile:t,expressionPath:n,provenance:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(!l||l.kind!=="static")return null;if(c.collectionPathMap?.length){let f=sE(l.value,c.collectionPathMap);if(f)return{kind:"static",file:c.file,root:c.root,value:f.value,sourceKind:c.sourceKind,collectionPathMap:f.collectionPathMap}}let u=ot(l.value,c.path);return Array.isArray(u)?{kind:"static",file:c.file,root:c.root,value:u,sourceKind:c.sourceKind,pathPrefix:c.path,collectionIndexMap:c.collectionIndexMap,collectionPathMap:c.collectionPathMap}:null}return null}async function Dx(e){let{provenance:t}=e;if(t.root.kind==="binding"){let i=e.expressionPath.scope.getBinding(t.root.name);return i?await yn({currentFile:e.currentFile,binding:i,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}if(t.root.kind!=="expression")return null;let n=await Gn(t.file,e.readFile,e.fileCache);if(!n.ast)return null;let r=sx(n.ast,t.root.sourceRange);if(!r)return null;let o=await Qe(r.node,r.scope,t.file,e.readFile,e.exists,e.fileCache,e.visited);return o===void 0?null:{kind:"static",file:t.file,root:t.root,value:o,sourceKind:t.sourceKind}}async function yd(e){return await Lx(e)??await jx(e)??await $x(e)}async function Lx(e){let{callPath:t}=e,n=t.node.callee;if(!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="filter")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await Yn({currentFile:e.currentFile,expressionPath: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});if(!i||!Array.isArray(i.value))return null;let[s]=t.node.arguments;if(!E.isArrowFunctionExpression(s)&&!E.isFunctionExpression(s))return null;let a=s.params[0];if(!E.isIdentifier(a))return null;let c=Bx(s);if(!c)return null;let l=[],u=[],f=[];for(let[p,m]of i.value.entries()){let S=Kx(c,a.name,m);if(typeof S!="boolean")return null;if(S){l.push(m),u.push(i.collectionIndexMap?.[p]??p);let I=i.collectionPathMap?.[p];I&&f.push(I)}}return{...i,value:l,pathPrefix:i.pathPrefix,collectionIndexMap:u,...f.length>0?{collectionPathMap:f}:{}}}async function jx(e){let{callPath:t}=e,n=t.node.callee;if(!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="slice")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await Yn({currentFile:e.currentFile,expressionPath: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});if(!i||!Array.isArray(i.value))return null;let[s,a]=t.node.arguments,c=Gu(s,0),l=Gu(a,i.value.length);if(c===null||l===null)return null;let u=Math.max(0,c<0?i.value.length+c:c),f=Math.max(0,l<0?i.value.length+l:l),p=i.value.map((S,I)=>i.collectionIndexMap?.[I]??I).slice(u,f),m=i.collectionPathMap?.slice(u,f);return{...i,value:i.value.slice(u,f),pathPrefix:i.pathPrefix,collectionIndexMap:p,...m?{collectionPathMap:m}:{}}}function Gu(e,t){return e?E.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}async function $x(e){let{callPath:t}=e,n=t.node.callee;if(!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="sort"&&n.property.name!=="toSorted")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await Yn({currentFile:e.currentFile,expressionPath: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});if(!i||!Array.isArray(i.value))return null;let[s]=t.node.arguments;if(!E.isArrowFunctionExpression(s)&&!E.isFunctionExpression(s))return null;let[a,c]=s.params;if(!E.isIdentifier(a)||!E.isIdentifier(c))return null;let l=i.value.map((f,p)=>({value:f,sourceIndex:i.collectionIndexMap?.[p]??p,originalIndex:p})),u=[...l];for(let f of l)for(let p of l)if(Zu(s,a.name,c.name,f.value,p.value)===void 0)return null;return u.sort((f,p)=>{let m=Zu(s,a.name,c.name,f.value,p.value)??0;return m===0?f.originalIndex-p.originalIndex:m}),{...i,value:u.map(f=>f.value),pathPrefix:i.pathPrefix,collectionIndexMap:u.map(f=>f.sourceIndex),...i.collectionPathMap?{collectionPathMap:u.map(f=>i.collectionPathMap?.[f.originalIndex]).filter(f=>!!f)}:{}}}function Zu(e,t,n,r,o){let i=E.isExpression(e.body)?e.body:e.body.body.find(a=>E.isReturnStatement(a))?.argument;if(!i||!E.isExpression(i))return;let s=As(i,t,n,r,o);return typeof s=="number"?s:void 0}function As(e,t,n,r,o){if(E.isNumericLiteral(e)||E.isStringLiteral(e)||E.isBooleanLiteral(e))return e.value;if(E.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(E.isMemberExpression(e)){let i=Ts(e,t);if(i)return ot(r,i);let s=Ts(e,n);return s?ot(o,s):void 0}if(E.isBinaryExpression(e)&&e.operator==="-"){let i=E.isExpression(e.left)?As(e.left,t,n,r,o):void 0,s=E.isExpression(e.right)?As(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function Bx(e){if(E.isExpression(e.body))return e.body;for(let t of e.body.body)if(E.isReturnStatement(t)&&t.argument&&E.isExpression(t.argument))return t.argument;return null}function Kx(e,t,n){let r=Jt(e,t,n);return typeof r=="boolean"?r:void 0}function Jt(e,t,n){if(E.isStringLiteral(e)||E.isNumericLiteral(e)||E.isBooleanLiteral(e))return e.value;if(E.isNullLiteral(e))return null;if(E.isIdentifier(e))return e.name===t?n:void 0;if(E.isMemberExpression(e)){let r=Ts(e,t);return r?ot(n,r):void 0}if(E.isUnaryExpression(e)&&e.operator==="!"){let r=Jt(e.argument,t,n);return r===void 0?void 0:!r}if(E.isLogicalExpression(e)){let r=Jt(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&Jt(e.right,t,n);if(e.operator==="||")return r||Jt(e.right,t,n)}if(E.isBinaryExpression(e)){let r=E.isExpression(e.left)?Jt(e.left,t,n):void 0,o=E.isExpression(e.right)?Jt(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 Ts(e,t){let n=[],r=e;for(;E.isMemberExpression(r);){if(r.computed)if(E.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(E.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!E.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!E.isIdentifier(r)||r.name!==t?null:n}async function yn(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=`${t}::${n.kind}::${n.identifier.name}`;if(s.has(a))return null;s.add(a);try{let c=await Ux({currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s});if(c)return c;if(n.path.isImportSpecifier()||n.path.isImportDefaultSpecifier())return await tE({currentFile:t,binding:n,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:i,visited:s});if(n.kind==="param")return null;if(n.path.isVariableDeclarator()){let l=n.path.node.init;if(!l||!E.isExpression(l))return null;let u=n.path.get("init");if(u&&!Array.isArray(u)&&u.isExpression()){let p=await Ls({currentFile:t,expressionPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(p)return p;if(u.isCallExpression()){let m=await yd({currentFile:t,callPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(m)return m}}let f=await Qe(l,n.path.scope,t,r,o,i,s);return f===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:f,sourceKind:"binding"}}if(n.path.isIdentifier()&&n.path.parentPath?.isExportDefaultDeclaration()){let l=n.path.parentPath.node.declaration;if(!E.isExpression(l))return null;let u=await Qe(l,n.path.scope,t,r,o,i,s);return u===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:u,sourceKind:"binding"}}return null}finally{s.delete(a)}}async function Ux(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e;if(!n.path.isVariableDeclarator()||!n.path.get("id").isArrayPattern())return null;let a=n.path,c=a.node.init;if(!c||!E.isCallExpression(c))return null;let l=Vx(c);if(!l||!E.isArrayPattern(a.node.id)||a.node.id.elements.findIndex(S=>E.isIdentifier(S)&&S.name===n.identifier.name)!==0)return null;let f=l==="useReducer"?1:0,p=c.arguments[f];if(!p||!E.isExpression(p))return null;let m=await Qe(p,a.scope,t,r,o,i,s);return m===void 0?null:{kind:"static",file:t,root:{kind:"hook-state",name:n.identifier.name,hook:l},value:m,sourceKind:"binding"}}function Vx(e){return E.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:E.isMemberExpression(e.callee)&&E.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function Jx(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()||!E.isIdentifier(n.node.id))return null;let r=n.node.id.name,o=n.parentPath,i=o?.parentPath?.isExportDefaultDeclaration()?"default":(o?.parentPath?.isExportNamedDeclaration(),r);return{componentName:r,exportName:i}}function Xx(e,t){let n=Jx(e.path);if(!n)return null;let r=pn(e,t);return r?{...n,...r}:null}function lo(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Wx(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}async function zx(e){let t=Yx(e.expressionPath.node);if(!t||!Gx(t.segments))return null;let n=await Fe({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 Hx({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:Hn(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function Hx(e){let t=null,n,r=[];for(let i of e.segments){if(i.kind!=="dynamic")continue;let s=await Ze({expression:i.expression,scope:e.expressionPath.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!s)return null;let a=hd(e.expressionPath,s.base);if(!a)return null;let c=await gd({currentFile:e.currentFile,callPath:a.callPath,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(!c||!Array.isArray(c.value))return null;let l=c.value.map((u,f)=>{let p=ot(c.value,[{kind:"index",index:f},...a.basePath,...s.path]);return Zx(p)});if(l.some(u=>u===null)||t!==null&&t!==l.length)return null;t=l.length,n??=c.collectionIndexMap,r.push(l)}if(t===null||t===0)return null;let o=[];for(let i=0;i<t;i+=1){let s=[...e.rootPath],a=0;for(let c of e.segments){if(c.kind==="dynamic"){let l=r[a]?.[i];if(!l)return null;s.push(l),a+=1;continue}s.push({...c})}o.push(s)}return{...n?{collectionIndexMap:n}:{},collectionPathMap:o}}function Yx(e){let t=[],n=e;for(;E.isMemberExpression(n)||E.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(E.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(E.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(E.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(E.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return E.isIdentifier(n)?{base:n.name,segments:t}:null}function Gx(e){return e.some(t=>t.kind==="dynamic")}function Zx(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}async function Qx(e){let t=Xx(e.binding,e.sourceInfo);if(!t||!e.graph)return null;let n=[...e.graph.elements.values()].filter(l=>Wx(l,e.currentFile,t.componentName,t.exportName));if(n.length!==1)return null;let r=n[0],o=r.attributes?.find(l=>l.name===t.propName);if(o&&!o.source){let l=await qx({caller:r,propName:t.propName,remainingPath:t.remainingPath,readFile:e.readFile,fileCache:e.fileCache});if(l)return Cs(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile})}if(!o?.source){let l=await eE({caller:r,propName:t.propName,remainingPath:t.remainingPath,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(l)return Cs(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile});let u=su(e.binding,t.componentName,t.propName);if(!u||u.propName!==t.propName)return null;let f=await Qe(u.expressionPath.node,u.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(f===void 0)return null;let p=t.remainingPath;return p.length>0&&ot(f,p)===void 0?null:{kind:"value",file:e.currentFile,root:{kind:"binding",name:t.propName},path:p,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.displayPath,chainPrefix:[{kind:"component-prop",file:e.currentFile,displayName:u.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let i=await Gn(r.sourceFile,e.readFile,e.fileCache);if(!i.ast)return null;let s=ad(i.ast,i.source,o.source.expression,o.sourceRange)??Ds(i.ast,i.source,o.source.expression);if(!s)return null;let a={...o.source,expression:lo(o.source.expression,t.remainingPath),path:[...o.source.path,...t.remainingPath]},c=await Fe({currentFile:r.sourceFile,expressionPath:s,sourceInfo:a,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 c?Cs(c.kind==="external"?c:{...c,displayExpression:a.expression},{componentName:t.componentName,propName:t.propName,file:r.sourceFile}):null}async function qx(e){let t=await Gn(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=id(t.ast,e.caller.sourceRange);if(!n)return null;let r=n.get("openingElement").get("attributes").find(a=>a.isJSXAttribute()&&a.node.name.type==="JSXIdentifier"&&a.node.name.name===e.propName);if(!r?.isJSXAttribute())return null;let o=r.get("value"),i=o.isStringLiteral()?o:o.isJSXExpressionContainer()?o.get("expression"):null;if(!i?.isExpression())return null;let s=sd(i.node);return s?{kind:"value",file:e.caller.sourceFile,root:{kind:"expression",sourceRange:s},path:e.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:e.propName,editMode:"upstream",diagnostics:[]}:null}async function eE(e){let t=await Gn(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=id(t.ast,e.caller.sourceRange);if(!n)return null;let r=n.get("openingElement");for(let o of r.get("attributes")){if(!o.isJSXSpreadAttribute())continue;let i=o.get("argument");if(!i.isExpression())continue;let s=await Ze({expression:i.node,scope:i.scope,source:t.source,currentFile:e.caller.sourceFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!s)continue;let a=[{kind:"property",name:e.propName},...e.remainingPath],c={...s,expression:lo(s.expression,a),path:[...s.path,...a]},l=await Fe({currentFile:e.caller.sourceFile,expressionPath:i,sourceInfo:c,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(l)return l.kind==="external"?l:{...l,displayExpression:c.expression}}return null}function Cs(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"}}async function tE(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.path.parentPath;if(!a||!a.isImportDeclaration())return null;let c=a.node.source.value;if(typeof c!="string")return null;let l=await tc(t,c,o);if(!l)return null;if(n.path.isImportDefaultSpecifier()){let m=await Qu({file:l,exportName:"default",readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return!m||m.kind!=="static"?null:{kind:"static",file:l,root:{kind:"default-export"},value:m.value,sourceKind:"imported-binding"}}if(!n.path.isImportSpecifier())return null;let u=n.path.node.imported,f=E.isIdentifier(u)?u.name:u.value,p=await Qu({file:l,exportName:f,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return p?p.kind==="external"?p:{kind:"static",file:l,root:{kind:"named-export",name:f},value:p.value,sourceKind:"imported-binding"}:null}async function Qu(e){let{file:t,exportName:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=await Gn(t,r,i);if(!a.ast)return;let c=rE(a.ast,n);if(!c||c.kind==="default-expression")return;let l=c.name;if(!l)return;let u=nE(a.ast).getBinding(l);return u?await yn({currentFile:t,binding:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s})??void 0:void 0}function nE(e){let t=null;if(ed(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}function rE(e,t){for(let n of e.program.body){if(t==="default"&&E.isExportDefaultDeclaration(n))return E.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(E.isFunctionDeclaration(n.declaration)||E.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(E.isExportNamedDeclaration(n)){if(n.declaration){if(E.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(E.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((E.isFunctionDeclaration(n.declaration)||E.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((E.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&E.isExportSpecifier(r))return{kind:"local-binding",name:r.local.name}}}return null}async function Qe(e,t,n,r,o,i,s){if(E.isStringLiteral(e)||E.isNumericLiteral(e)||E.isBooleanLiteral(e))return e.value;if(E.isNullLiteral(e))return null;if(E.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(E.isTSAsExpression(e)||E.isTSSatisfiesExpression(e)||E.isTSNonNullExpression(e))return await Qe(e.expression,t,n,r,o,i,s);if(E.isIdentifier(e)){let a=t.getBinding(e.name);if(!a)return;let c=await yn({currentFile:n,binding:a,readFile:r,exists:o,fileCache:i,visited:s});return c?.kind==="static"?c.value:void 0}if(E.isArrayExpression(e)){let a=[];for(let c of e.elements){if(!c||E.isSpreadElement(c))return;let l=await Rs(c,t,n,r,o,i,s);if(l===void 0)return;a.push(l)}return a}if(E.isObjectExpression(e)){let a={};for(let c of e.properties){if(!E.isObjectProperty(c)||c.computed)return;let l=null;if(E.isIdentifier(c.key)?l=c.key.name:E.isStringLiteral(c.key)&&(l=c.key.value),!l)return;if(c.shorthand){if(!E.isIdentifier(c.value))return;let f=await Rs(c.value,t,n,r,o,i,s);if(f===void 0)return;a[l]=f;continue}if(!E.isExpression(c.value))return;let u=await Rs(c.value,t,n,r,o,i,s);u!==void 0&&(a[l]=u)}return a}if(E.isMemberExpression(e)){let a=await xd(e,t,n,r,o,i,s);if(!a)return;let c=t.getBinding(a.base);if(!c)return;let l=await yn({currentFile:n,binding:c,readFile:r,exists:o,fileCache:i,visited:s});return!l||l.kind!=="static"?void 0:ot(l.value,a.path)}}async function Rs(e,t,n,r,o,i,s){if(!E.isSpreadElement(e))return await Qe(e,t,n,r,o,i,s)}async function xd(e,t,n,r,o,i,s){if(E.isIdentifier(e))return{base:e.name,path:[]};if(!E.isMemberExpression(e))return null;let a=[],c=e;for(;E.isMemberExpression(c);){if(c.computed){let l=c.property;if(E.isNumericLiteral(l))a.unshift({kind:"index",index:l.value});else if(E.isStringLiteral(l))a.unshift({kind:"property",name:l.value});else{let u=E.isExpression(l)?await Qe(l,t,n,r,o,i,s):void 0;if(typeof u=="string")a.unshift({kind:"property",name:u});else if(Number.isInteger(u))a.unshift({kind:"index",index:u});else return null}}else{if(!E.isIdentifier(c.property))return null;a.unshift({kind:"property",name:c.property.name})}c=c.object}return E.isIdentifier(c)?{base:c.name,path:a}:null}function oE(e){if(E.isIdentifier(e))return{base:e.name,path:[]};if(!E.isMemberExpression(e))return null;let t=[],n=e;for(;E.isMemberExpression(n);){if(n.computed)if(E.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(E.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!E.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return E.isIdentifier(n)?{base:n.name,path:t}:null}function ot(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 iE(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 sE(e,t){let n=[],r=[];for(let o of t){let i=ot(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}}async function Gn(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=od(o),s={source:o,ast:i};return n.set(e,s),s}import Xs from"@babel/generator";import{parse as xE}from"@babel/parser";import Ws from"@babel/traverse";import*as k from"@babel/types";import*as Id from"@babel/types";import Ks from"@babel/generator";import*as re from"@babel/types";var aE=typeof Ks=="function"?Ks:Ks.default,cE=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,lE=/^((?:https?:)?\/\/)[^/@\s]+@/i,uE=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Sd(e,t){let n=it(e.callee);if(!n)return null;if(n==="fetch")return Us(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Ed(r))return Us(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Ed(r))return Us(e.arguments[0],r,t,["ky client contract"])}return null}function Us(e,t,n,r){if(!e||re.isSpreadElement(e)||re.isJSXNamespacedName(e))return mE(t,n,r,"missing url argument");let o=Zn(e);return{sourceKind:pE(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 Zn(e){if(re.isStringLiteral(e))return uo(e.value);if(re.isTemplateLiteral(e))return uo(dE(e));if(re.isBinaryExpression(e)&&e.operator==="+"){let t=Zn(e.left),n=Zn(e.right);return!t&&!n?void 0:uo(`${t??Vs(e.left)}${n??Vs(e.right)}`)}if(re.isMemberExpression(e)){let t=bd(e);if(t)return`env:${t}`}if(!(re.isCallExpression(e)&&it(e.callee)==="new URL")){if(re.isNewExpression(e)&&re.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!re.isSpreadElement(t)?Zn(t):void 0,o=n&&!re.isSpreadElement(n)?Zn(n):void 0;return o&&r?uo(`${o} + ${r}`):r??o}if(re.isIdentifier(e))return`:${e.name}`}}function dE(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+=Vs(r))}return t}function Vs(e){if(re.isIdentifier(e))return`:${e.name}`;if(re.isMemberExpression(e)){let t=bd(e);if(t)return`env:${t}`}return`:${fE(e)}`}function fE(e){return aE(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function uo(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(lE,"$1<redacted>@").replace(uE,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?cE.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function pE(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 mE(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function Ed(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function bd(e){return!re.isMemberExpression(e.object)||!re.isIdentifier(e.object.object,{name:"process"})||!hE(e.object.property,"env")?null:re.isIdentifier(e.property)?e.property.name:re.isStringLiteral(e.property)?e.property.value:null}function hE(e,t){return re.isIdentifier(e)&&e.name===t}function it(e){if(re.isIdentifier(e))return e.name;if(re.isMemberExpression(e)){let t=it(e.object),n=re.isIdentifier(e.property)?e.property.name:re.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var gE=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),yE=new Set(["getConfig","submit"]);function kd(e,t){let n=it(e.callee);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!gE.has(i))return null;let s=Js(e,0);return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:i,...s?{collection:s}:{},endpointPattern:s?`/collections/${s}`:"/collections/:collection",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(!yE.has(i))return null;let s=Js(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=Js(e,0)??"/cms/:path";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:n,endpointPattern:i,confidence:i==="/cms/:path"?"partial":"safe-derived",evidence:[{file:t.file,symbol:n,reason:"VCP CMS fetch helper"}]}}return null}function vd(e,t){let n=it(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 Cd(e){let t=it(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function Js(e,t){let n=e.arguments[t];return Id.isStringLiteral(n)?n.value:null}var Td=typeof Ws=="function"?Ws:Ws.default,zC=typeof Xs=="function"?Xs:Xs.default,EE={maxFunctionDepth:8,maxImportDepth:6},SE=new Set(["src","href","alt","poster","content","title","aria-label"]);async function Nd(e){let t=e.fileCache??new Map,n=Bd(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...EE,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set},o=[];o.push(...await IE(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await kE(s,e.element,e.graph,r);a&&o.push(zs(a,"text","children"))}for(let s of e.element.attributes??[]){let a=bE(s);if(!a)continue;let c=await Fd(s.source,e.element,e.graph,r);c&&o.push(zs(c,a,s.name))}let i=KE(o).sort(jd);return{hasDynamicData:i.length>0,bindings:i}}function bE(e){return e.name==="dangerouslySetInnerHTML"?"richtext":SE.has(e.name)?"attribute":null}async function IE(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 Hs(i.collectionSource,n);s&&r.push(zs(xn(s),"repeat-region",i.collectionExpression))}return r}async function kE(e,t,n,r){return Fd(e.source,t,n,r)}async function Fd(e,t,n,r){let o=await vE(e,t,n,r);return o||Hs(e,r)}async function vE(e,t,n,r){if(!e)return null;let o=CE(e.base,t,n);if(!o)return null;let i=await Hs(o.collectionSource,r);return i?mo(i,e.path,!0):null}function CE(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 Hs(e,t){if(!e)return null;let n=await Md(e.base,t);return n?mo(n,e.path,!1):null}async function Md(e,t){let n=t.paramSources.get(e);if(n)return $e(n);if(t.variableCache.has(e))return JE(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await RE(e,t);if(r)return t.variableCache.set(e,$e(r)),t.resolvingVariables.delete(e),r;let o=t.analysis.variables.get(e);if(o){let s=await be(o,t);return t.variableCache.set(e,s?$e(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await Kd(i,t);if(s){let a=Ys(s,t,{importDepth:t.importDepth+1}),c=Ud(i,s);if(c){let f=(await Xt(c,[],a)).returnSource;return t.variableCache.set(e,f?$e(f):null),t.resolvingVariables.delete(e),f}let l=s.variables.get(i.importedName);if(l){let u=await be(l,a);return t.variableCache.set(e,u?$e(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function RE(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];Td(t.analysis.ast,{CallExpression(o){if(k.isIdentifier(o.node.callee,{name:n})){let i=o.node.arguments[0];k.isExpression(i)&&r.push(i);return}o.node.arguments.some(i=>k.isIdentifier(i)&&i.name===n)&&r.push(o.node)}});for(let o of r){let i=await be(o,t);if(i)return i}return null}async function be(e,t){if(k.isIdentifier(e))return Md(e.name,t);if(k.isMemberExpression(e)){let n=vd(e,{file:t.file});if(n)return Dd(n);let r=await wE(e,t);if(!r)return null;let o=LE(e);return mo(r,o,!1)}if(k.isAwaitExpression(e))return k.isExpression(e.argument)?be(e.argument,t):null;if(k.isCallExpression(e))return Od(e,t);if(k.isConditionalExpression(e)){let n=await be(e.consequent,t),r=await be(e.alternate,t);return qn(n??r)}if(k.isLogicalExpression(e)){let n=await be(e.left,t),r=await be(e.right,t);return qn(r??n)}return k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e)?be(e.expression,t):null}async function wE(e,t){let n=e;for(;k.isMemberExpression(n);)n=n.object;return k.isExpression(n)?be(n,t):null}async function Od(e,t){let n=kd(e,{file:t.file});if(n)return Dd(n);if(Cd(e)){let l=e.arguments[0];if(l&&k.isExpression(l))return qn(await be(l,t))}let r=await PE(e,t);if(r)return r;let o=Sd(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 NE(e,t);if(i)return i;let s=await FE(e,t);if(s)return s;let a=await ME(e,t);if(a)return a;let c=await OE(e,t);if(c)return c;for(let l of e.arguments)if(k.isExpression(l)){let u=await be(l,t);if(u)return qn(u)}return null}async function PE(e,t){let n=it(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=TE(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await po(s.name,t);if(a)return(await Xt(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return fo(t.file,`${n} without static options`);let o=AE(r,"queryFn");if(!o)return fo(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await po(o.name,t);return i?(await Xt(i.node,[],i.context)).returnSource:fo(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await Xt(o,[],t)).returnSource:k.isCallExpression(o)?Od(o,t):null}function AE(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(_d(n)===t)return n.value}return null}function TE(e,t,n){return k.isStringLiteral(e)?{sourceKind:e.value.startsWith("/api/")?"site-api-route":"external-api",sourceType:"api-field",endpointPattern:e.value,confidence:"exact",readonly:!0,evidence:[{file:t,reason:n}]}:null}async function NE(e,t){if(!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=k.isExpression(e.callee.object)?await be(e.callee.object,t):null;if(!r)return null;if(n!=="map")return xn(r);let o=e.arguments[0];if(k.isIdentifier(o)){let i=await po(o.name,t);if(!i)return xn(r);let s=await Xt(i.node,[r],i.context);return{...xn(r),...s.objectReturnMap?{fieldMap:s.objectReturnMap}:{}}}if(k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)){let i=await Xt(o,[r],t);return{...xn(r),...i.objectReturnMap?{fieldMap:i.objectReturnMap}:{}}}return xn(r)}async function FE(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"json"})||!k.isExpression(e.callee.object)?null:be(e.callee.object,t)}async function ME(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:qn(await be(e.callee.object,t))}async function OE(e,t){if(!k.isIdentifier(e.callee))return null;let n=await po(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!k.isExpression(i)){r.push(fo(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await be(i,t);s&&r.push(s)}return(await Xt(n.node,r,n.context)).returnSource}async function po(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 Kd(r,t);if(!o)return null;let i=Ys(o,t,{importDepth:t.importDepth+1}),s=Ud(r,o);return s?{node:s,context:i}:null}async function Xt(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=Ys(n.analysis,n,{functionDepth:n.functionDepth+1});e.params.forEach((a,c)=>{k.isIdentifier(a)&&t[c]&&r.paramSources.set(a.name,jE(t[c]))});let o=_E(e),i=null,s;for(let a of o){if(k.isObjectExpression(a)){s={...s??{},...await DE(a,r)},i=i??BE(s,n.file);continue}let c=await be(a,r);c&&(i=i?$E(i,c):c)}return{returnSource:i,...s?{objectReturnMap:s}:{}}}function _E(e){if(k.isArrowFunctionExpression(e)&&k.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!k.isBlockStatement(n))return t;let r=o=>{if(k.isFunction(o)&&o!==e)return;if(k.isReturnStatement(o)){o.argument&&k.isExpression(o.argument)&&t.push(o.argument);return}let i=k.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)k.isNode(c)&&r(c);else k.isNode(a)&&r(a)}};return r(n),t}async function DE(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=_d(r);if(!o||!k.isExpression(r.value))continue;let i=await be(r.value,t);i&&(n[o]=i)}return n}function _d(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function LE(e){let t=[],n=e;for(;k.isMemberExpression(n);){let r=n.property;n.computed?k.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):k.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):k.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return k.isIdentifier(n),t}function mo(e,t,n){if(t.length===0)return $e(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return mo(e.fieldMap[r.name],t.slice(1),n);let o=$e(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=Qn(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=Qn(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=Qn(o.fieldPath,i.join(".")),o):(o.valuePath=Qn(o.valuePath,Rd(t)),o)}return o.valuePath=Qn(o.valuePath,Rd(t)),o}function Rd(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Qn(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function Dd(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 xn(e){let t=$e(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function jE(e){let t=$e(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function qn(e){return e?{...$e(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function $E(e,t){let n=$d(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function BE(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 fo(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function zs(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 Ld(e){let t=[...e].sort(jd),n=t[0];return{hasDynamicData:t.length>0,sourceKinds:[...new Set(t.map(r=>r.sourceKind))],...n?.endpointPattern?{primaryEndpoint:n.endpointPattern}:{},...n?.collection?{primaryCollection:n.collection}:{},...n?.fieldPath?{primaryFieldPath:n.fieldPath}:{}}}function KE(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 jd(e,t){return wd(e.targetKind)-wd(t.targetKind)||$d(e.confidence,t.confidence)||Pd(e.sourceKind)-Pd(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function wd(e){return{"repeat-region":0,text:1,richtext:2,attribute:3,"component-prop":4}[e]}function Pd(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function $d(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Bd(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=xE(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};return Td(o,{ImportDeclaration(s){let a=s.node.source.value;for(let c of s.node.specifiers)k.isImportSpecifier(c)&&k.isIdentifier(c.local)?i.imports.set(c.local.name,{source:a,importedName:k.isIdentifier(c.imported)?c.imported.name:c.imported.value,localName:c.local.name,isDefault:!1}):k.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){for(let a of En(s.node.id))i.variables.set(a,k.isExpression(s.node.init)?s.node.init:null);if(k.isArrayPattern(s.node.id)&&k.isCallExpression(s.node.init)&&it(s.node.init.callee)==="useState"){let[a,c]=s.node.id.elements;k.isIdentifier(a)&&k.isIdentifier(c)&&i.stateSetters.set(a.name,c.name)}k.isIdentifier(s.node.id)&&Ad(s.node.init)&&i.functions.set(s.node.id.name,s.node.init)},ExportNamedDeclaration(s){let a=s.node.declaration;if(k.isFunctionDeclaration(a)&&a.id?.name&&i.functions.set(a.id.name,a),k.isVariableDeclaration(a))for(let c of a.declarations)k.isIdentifier(c.id)&&Ad(c.init)&&i.functions.set(c.id.name,c.init)},ExportDefaultDeclaration(s){let a=s.node.declaration;if((k.isFunctionDeclaration(a)||k.isFunctionExpression(a)||k.isArrowFunctionExpression(a))&&i.functions.set("default",a),k.isIdentifier(a)){let c=i.functions.get(a.name);c&&i.functions.set("default",c)}}}),n.set(e,i),i}function En(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?En(t.value):En(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?En(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?En(e.left):k.isRestElement(e)?En(e.argument):[]}function Ad(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}async function Kd(e,t){let n=await UE(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Bd(n,r,t.fileCache)}function Ud(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function UE(e,t,n){if(!t.startsWith("."))return null;let r=e.split("/").slice(0,-1).join("/"),o=VE(`${r}/${t}`),i=[o,`${o}.ts`,`${o}.tsx`,`${o}.js`,`${o}.jsx`,`${o}/index.ts`,`${o}/index.tsx`,`${o}/index.js`,`${o}/index.jsx`];for(let s of i)if(await n(s))return s;return null}function VE(e){let t=[];for(let n of e.split("/"))if(!(!n||n===".")){if(n===".."){t.pop();continue}t.push(n)}return t.join("/")}function Ys(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}}function JE(e){return e?$e(e):null}function $e(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,$e(n)]))}:{}}}var XE=50,WE=8*1024*1024;function Wd(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??XE),s=Math.max(0,t.maxUndoBytes??WE);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:f};async function a(R){let _=[...R.steps].sort((H,q)=>H.order-q.order),D=_.filter(H=>H.type!=="invoke-external-adapter");if(D.length!==_.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let L=new Set(D.map(H=>H.file)),Z=await A(L),Q=new Map(Z.map(H=>[H.file,H.exists===!1?"":H.content])),me;for(let H of D){let q=Xd(H,Q.get(H.file)??"");if(!q.ok)return{ok:!1,errorCode:q.errorCode,reason:q.reason};Q.set(H.file,q.source),me=q.selectionRef??me}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...Q].map(([H,q])=>({operation:"upsert",file:H,content:q,baseContentHash:Z.find(he=>he.file===H)?.sha256??null}))},...me?{selectionRef:me}:{}}}async function c(R){let _=[...R.steps].sort((he,st)=>he.order-st.order),D=_.filter(he=>he.type!=="invoke-external-adapter"),L=_.filter(he=>he.type==="invoke-external-adapter"),Z=new Set(D.map(he=>he.file));if(D.length>0&&L.length>0)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(D.length===0)return v(R,L);let Q=await A(Z),me=new Map;for(let he of Q)me.set(he.file,he.exists===!1?"":he.content);let H;for(let he of D){let st=me.get(he.file)??"",mt=Xd(he,st);if(!mt.ok)return{ok:!1,operationId:R.operationId,errorCode:mt.errorCode,reason:mt.reason,rolledBack:!1};me.set(he.file,mt.source),mt.selectionRef&&(H=mt.selectionRef)}let q=await G([...me].map(([he,st])=>({file:he,content:st,exists:!0,version:0,sha256:ae(st)})),Q);return q.ok===!1?{ok:!1,operationId:R.operationId,errorCode:q.rolledBack?"writeback-failed":"rollback-failed",reason:q.reason,rolledBack:q.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:Q,postSnapshots:q.snapshots,plan:R}),p(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...q.snapshots.map(he=>he.version)),affectedFiles:[...Z],...H?{selectionRef:H}:{}})}async function l(R){let _=new Set(R.edits.map(q=>q.file)),D=await A(_),L=C(R,D);if(L)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:L.reason,affectedFiles:[L.file],rolledBack:!1};let Z=new Map(D.map(q=>[q.file,q])),Q=R.edits.find(q=>q.operation==="create-only"&&Z.get(q.file)?.exists!==!1);if(Q)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${Q.file}`,affectedFiles:[Q.file],rolledBack:!1};let me=R.edits.map(q=>q.operation==="delete"?{file:q.file,content:"",exists:!1,version:0}:{file:q.file,content:q.content,exists:!0,version:0,sha256:ae(q.content)}),H=await G(me,D,new Set(R.edits.filter(q=>q.operation==="create-only").map(q=>q.file)));return H.ok===!1?{ok:!1,operationId:R.operationId,errorCode:H.rolledBack?"writeback-failed":"rollback-failed",reason:H.reason,rolledBack:H.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:D,postSnapshots:H.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:D}}),p(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...H.snapshots.map(q=>q.version)),affectedFiles:[..._]})}async function u(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let _=await G(R.preSnapshots,R.postSnapshots);return _.ok===!1?{ok:!1,operationId:R.operationId,errorCode:_.rolledBack?"writeback-failed":"rollback-failed",reason:_.reason,rolledBack:_.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(..._.snapshots.map(D=>D.version)),affectedFiles:R.preSnapshots.map(D=>D.file)})}async function f(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let _=await G(R.postSnapshots,R.preSnapshots);return _.ok===!1?{ok:!1,operationId:R.operationId,errorCode:_.rolledBack?"writeback-failed":"rollback-failed",reason:_.reason,rolledBack:_.rolledBack}:(r.pop(),n.push(R),p(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(..._.snapshots.map(D=>D.version)),affectedFiles:R.postSnapshots.map(D=>D.file)})}function p(){for(;n.length>i;)n.shift();for(;n.length>0&&m()>s;)n.shift()}function m(){return n.reduce((R,_)=>R+S(_),0)}function S(R){return I(R.preSnapshots)+I(R.postSnapshots)}function I(R){return R.reduce((_,D)=>_+D.file.length+D.content.length,0)}async function v(R,_){let D=[];for(let L of _){let Z=L.capability??"write-text",Q=o.find(H=>H.sourceType===L.sourceType&&(L.adapterId===void 0||H.adapterId===L.adapterId)&&(H.capabilities===void 0||H.capabilities.includes(Z)));if(!Q)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${L.sourceType}`,rolledBack:!1};let me=await Q.execute(L);if(!me.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:me.reason??`External adapter failed for ${L.sourceType}`,rolledBack:!1};D.push(L.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:D}}function C(R,_){if(R.conflictPolicy!=="compare-and-swap")return null;let D=new Map(_.map(L=>[L.file,L]));for(let L of R.edits){if(L.operation==="create-only")continue;if(L.baseContentHash===void 0)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};let Z=D.get(L.file),Q=L.baseContentHash;if(Q===null){if(Z?.exists!==!1)return{file:L.file,reason:`Source file ${L.file} was created or changed before save.`};continue}if(!Q)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};if(Z?.exists===!1||Z?.sha256!==Q)return{file:L.file,reason:`Source file ${L.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function A(R){let _=[];for(let D of R)_.push(await T(D));return _}async function T(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let D=Math.max(1,e.getVersion(R)),L=await e.readFile(R);return{file:R,content:L,version:D,exists:!0,sha256:ae(L)}}async function G(R,_,D=new Set){let L=[];try{for(let Z of R){if(D.has(Z.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(Z.file,Z.content)}else await fe(Z);let Q=e.bumpVersion(Z.file);L.push(Z.file),Z.version=Q}}catch(Z){let Q=await ue(_.filter(H=>L.includes(H.file)));if(Q.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${Q.failedFiles.join(", ")}: ${Jd(Z)}`,rolledBack:!1,instanceConflict:Vd(Z)};let me=Vd(Z);return{ok:!1,reason:`${me?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Jd(Z)}`,rolledBack:!0,instanceConflict:me}}return{ok:!0,snapshots:R.map(zE)}}async function fe(R){if(R.exists===!1){await e.deleteFile(R.file);return}await e.writeFile(R.file,R.content)}async function ue(R){let _=[];for(let D of R)try{await fe(D),e.bumpVersion(D.file)}catch{_.push(D.file)}return _.length===0?{ok:!0}:{ok:!1,failedFiles:_}}}function Vd(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function zE(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ae(e.content)}:{}}}function Jd(e){return e instanceof Error?e.message:String(e)}function Xd(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 Pe(ln({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return Pe(un({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return Pe(rn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return Pe(sn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return Pe(Lr({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return Pe(_n({source:t,locator:e.locator,next:e.value}));case"update-array-item":return Pe(_n({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return Pe(Kr({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return Pe(jr({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return Pe(Ur({source:t,locator:e.locator,index:e.index}));case"move-array-item":return Pe(Vr({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return Pe(cn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return Pe($r({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 HE(e,t);case"set-props":{let n=e;return Pe(Br({source:t,locator:n.locator,props:n.props}))}default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function HE(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!zl(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};let r=n.oldAttrRange!==null&&n.oldAttrRaw!==null,o=n.openingElementRange.start,i=n.openingElementRange.end,s=t.slice(o,i);if(!(Number.isInteger(o)&&Number.isInteger(i)&&o>=0&&i>o&&i<=t.length&&s.startsWith("<")&&s.endsWith(">")&&!s.startsWith("</")&&(n.oldAttrRange===null||n.oldAttrRange.start>=o&&n.oldAttrRange.end<=i)))return{ok:!1,reason:"The opening element range changed before className save.",errorCode:"stale-version"};if(!r&&n.expectedVersion.contentHash!==ae(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:Wl({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function Pe(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"}}}function zd(){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 YE}from"node:crypto";import ho from"node:fs/promises";import Gs from"node:path";var GE={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)}};async function go(e,t,n=GE){let r=Gs.dirname(e),o=Gs.basename(e),i=Gs.join(r,`.${o}.${process.pid}.${YE()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await n.rename(i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import{randomBytes as uS}from"node:crypto";import er from"node:path";import{parse as dS}from"@babel/parser";import fS from"@babel/traverse";import{SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Yd,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as pS,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as mS,SiteEditMaterializationSchema as hS}from"@vcp-dev/contracts";var Hd=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,ZE=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,QE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,qE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,eS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,tS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,nS=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,rS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,oS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,iS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,sS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,aS=/\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,cS=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,lS=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Zs(e,t){let n=yo([...Be(e,QE),...Be(e,qE),...Be(e,eS),...Be(e,t.includeRgbBackgroundImage?tS:nS),...t.includeExtendedColorFunctions?[...Be(e,rS),...Be(e,oS)]:[]]),r=yo([...Be(e,iS),...Be(e,sS)]).filter(o=>t.colorMixPolicy==="always"||Hd.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...Be(e,aS).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...Be(e,lS).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:yo(Be(e,ZE)),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?yo(Be(e,cS)):[]}}function Be(e,t){return e.match(new RegExp(t.source,t.flags))??[]}function yo(e){return[...new Set(e)]}var ta="components/site/generated",Gd="{{$INSTANCE}}",xo=5,gS=/^[a-z][a-z0-9-]{0,48}$/,yS=/^[a-f0-9]{8}$/,xS=/\.tsx?$/,ES=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,SS=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Qs=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),qs=fS,bS=typeof qs=="function"?qs:qs.default;function IS(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Yd)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=FS(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=hS.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 ${ta}.`,path:e.generatedRoot}};if(!nf(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=qd(r.data.files),s=qd(e.controlledFiles);if(!MS(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Yd)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>pS)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>mS?{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 kS(e){let t=IS(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=nf(e.manifest.instanceBaseName),o=Math.max(1,Math.min(xo,e.maxAttempts??xo));for(let i=0;i<o;i+=1){let s=TS(e.instanceNameGenerator?.()??uS(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=of(n,a),l=vS({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 tf(e){let t=Math.max(1,Math.min(xo,e.maxAttempts??xo));for(let n=0;n<t;n+=1){let r=await kS({...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 vS(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=Zd({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=Zd({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 Zd(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=NS(t);return n?of(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)||ES.test(n)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab files must be .ts/.tsx source files and cannot be config, layout, provider, or global 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(u=>u.path)),s=new Map,a=new Map;for(let u of e){let f;try{f=dS(u.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:u.path}}}let p=Zs(u.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(p.hardCodedSurfaceHits.length>0||p.rawColorHits.length>0||p.privateTokenHits.length>0)return{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:u.path}};s.set(u.path,f),a.set(u.path,new Set)}for(let u of e){let f=s.get(u.path),p=null;if(bS(f,{ImportDeclaration(m){let S=Qd({importer:u.path,source:m.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});S.allowed?S.internalPath&&a.get(u.path).add(S.internalPath):(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:u.path},m.stop())},ExportAllDeclaration(m){p??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:u.path},m.stop()},ExportNamedDeclaration(m){if(m.node.source){let S=Qd({importer:u.path,source:m.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!S.allowed||!S.internalPath?(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:u.path},m.stop()):a.get(u.path).add(S.internalPath)}},CallExpression(m){if(m.node.callee.type==="Import"){p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:u.path},m.stop();return}m.node.callee.type==="Identifier"&&m.node.callee.name==="require"&&(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:u.path},m.stop())},NewExpression(m){m.node.callee.type==="Identifier"&&m.node.callee.name==="Function"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:u.path},m.stop())},MetaProperty(m){m.node.meta.type==="Identifier"&&m.node.meta.name==="import"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:u.path},m.stop())},MemberExpression(m){let S=ef(m.node);S&&Qs.has(S)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${S}.`,file:u.path},m.stop())},OptionalMemberExpression(m){let S=ef(m.node);S&&Qs.has(S)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${S}.`,file:u.path},m.stop())},Identifier(m){m.isReferencedIdentifier()&&Qs.has(m.node.name)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${m.node.name}.`,file:u.path},m.stop())},JSXAttribute(m){m.node.name.type==="JSXIdentifier"&&m.node.name.name==="style"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:u.path},m.stop())},JSXOpeningElement(m){m.node.name.type==="JSXIdentifier"&&m.node.name.name.toLowerCase()==="style"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:u.path},m.stop())}}),p)return{ok:!1,error:p}}let c=s.get(n);return c?wS(c,r)?PS(n,a).size!==e.length?ea("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:ta,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}:ea("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n):ea("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n)}function Qd(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=er.posix.normalize(er.posix.join(er.posix.dirname(e.importer),e.source));if(t===e.instanceRoot||!t.startsWith(`${e.instanceRoot}/`))return{allowed:!1};let r=[t,`${t}.ts`,`${t}.tsx`,...["ts","tsx"].map(o=>`${t}/index.${o}`)].find(o=>e.filePaths.has(o));return r?{allowed:!0,internalPath:r}:{allowed:!1}}function wS(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 ea(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function AS(e){let t=rf(e);return t===ta?t:null}function TS(e){let t=e.trim().toLowerCase();return yS.test(t)?t:null}function nf(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 rf(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=er.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function NS(e){let t=rf(e);return!t||t!==e?null:t}function of(...e){return er.posix.join(...e)}function qd(e){return new Set(e.map(t=>t.pathTemplate))}function FS(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 MS(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function ef(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}}function uf(e){let t=null,n=new WeakMap;async function r(){return t??=OS(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(lf(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);sf(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(sf(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(lf(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 sf(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 OS(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>af(e,o))),r=await Promise.all(t.redoIds.map(async o=>af(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function af(e,t){let n=await e.readEntry(t),r=_S(n);return{historyId:t,operationId:r.operationId,kind:r.kind,target:r.target,...r.selectionRef?{selectionRef:r.selectionRef}:{},preSnapshots:await cf(e,n,r.preSnapshots),postSnapshots:await cf(e,n,r.postSnapshots)}}async function cf(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(DS(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function lf(e){let t=[],n=(o,i)=>o.map((s,a)=>{let c={file:s.file,exists:s.exists!==!1,version:s.version,...s.sha256?{sha256:s.sha256}:{}};if(c.exists){let l=`${i}-${a}`;c.blobName=l,t.push({name:l,data:s.content})}return c}),r={operationId:e.operationId,kind:e.kind,target:e.target,...e.selectionRef?{selectionRef:e.selectionRef}:{},preSnapshots:n(e.preSnapshots,"pre"),postSnapshots:n(e.postSnapshots,"post")};return{kind:"site-edit-operation",manifest:JSON.parse(JSON.stringify(r)),blobs:t}}function _S(e){if(!LS(e.manifest))throw new Error("durable history manifest is not an object");return e.manifest}function DS(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function LS(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import df from"node:path";function ra(){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 pf(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=KS(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 Eo(e){let t=()=>jS(e);return e.mutex?e.mutex.runExclusive(t):t()}async function jS(e){let t=await pf(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=$S(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 na({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 na({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 na({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 ff("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return ff("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 $S(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 na(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:BS(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 ff(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function BS(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 KS(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)||df.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=df.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}}function oa(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function Sn(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function ia(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function sa(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 mf(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function US(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var tr=class extends Error{constructor(t){let n=t.map(mf);super(US(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function hf(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof tr?{routeId:e,message:n,diagnostics:t.diagnostics.map(mf)}:{routeId:e,message:n}}function aa(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function gf(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 YS=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,GS=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],yf=32,xf=256,Ef={maxEntries:50,maxBytes:8*1024*1024};function ZS(){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 go(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 QS(){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>Ef.maxEntries||qS(e)>Ef.maxBytes;)e.shift()}}function qS(e){return e.reduce((t,n)=>t+eb(n),0)}function eb(e){return Sf(e.preSnapshots)+Sf(e.postSnapshots)}function Sf(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function bf(e,t){return{routeId:e,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}}function tb(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Ke(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}}var Io=class extends Error{constructor(t){super(t.reason),this.result=t}},Wt=class extends Error{constructor(t){super(aa(t)),this.failedRoutes=t}};function If(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=Ke(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(Ke(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}var nb=/\.(?:[cm]?[jt]sx?)$/i,rb=/\.json$/i,ob=/\.(?:css|scss|sass)$/i,ib=/\.mdx$/i,sb=/\.ya?ml$/i;function ab(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 cb(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function lb(e,t){let n=new Map;for(let 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=db(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(ub(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 ub(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function db(e){return Array.isArray(e)?{files:e}:e}function fb(e){if(!XS(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!==zS||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=JS(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(nb.test(e.path)){let t=tt({source:e.content,profile:Ot({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(rb.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Me(t)}`,details:{path:e.path}}}if(ob.test(e.path)){let t=kf({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(ib.test(e.path)){let t=kf({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(sb.test(e.path))try{HS(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Me(t)}`,details:{path:e.path}}}return{ok:!0}}function kf({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 p=e[f]??"",m=e[f+1]??"";if(n==="mdx"&&l&&e.startsWith("```",f)){c=!c;let S=e.indexOf(`
5
- `,f);if(S===-1){l=!0;break}f=S,l=!0;continue}if(c){l=p===`
6
- `||p==="\r";continue}if(s){p==="*"&&m==="/"&&(s=!1,f+=1),l=p===`
1
+ import{SiteEditOperationRequestSchema as cb,SiteEditPatchPlanSchema as lb}from"@vcp-dev/contracts";function Ot(e){return{requestId:e.requestId,kind:e.kind,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function br(e,t){return{ok:!1,error:{code:"INVALID_PARAMS",message:t[0]??"Site edit operation request failed contract validation."},data:{requestId:e.id,kind:e.kind,target:e.target,resultVersion:e.documentVersion}}}function Ir(e,t){if(!e.pageComposition)throw new Error("RenderDocument is missing the required Page Composition projection.");return{siteId:t.siteId,snapshotId:t.snapshotId,routeId:e.routeId,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 kr(e){return{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:Yf(e.capabilities),provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,dynamicData:e.dynamicData,textSegments:e.textSegments.map(t=>({index:t.index,editable:t.editable,sourceKind:t.source?.kind??null})),boundaryKind:e.boundaryKind}}function vr(e,t){let n=new Date().toISOString();return e.type==="document-changed"?{type:"site-edit.document.changed",siteId:t.siteId,snapshotId:t.snapshotId,routeId:e.routeId,version:e.version,at:n}:e.type==="operation-completed"?{type:"site-edit.operation.completed",siteId:t.siteId,result:Ot(e.result),at:n}:e.type==="operation-failed"?{type:"site-edit.operation.failed",siteId:t.siteId,requestId:e.requestId,error:e.error,at:n}:e.type==="capability-changed"?{type:"site-edit.capability.changed",siteId:t.siteId,routeId:"",keys:e.keys,at:n}:null}function Yf(e){return{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{composeSiteEditRepeatInstanceKey as qE,getSiteEditSourceDeleteProtectionReason as eS,isSiteEditTextSourcePath as tS,parseSiteEditRepeatInstanceKey as nS,SITE_EDIT_SOURCE_DELETE_CAPABILITY as rS,stripSiteEditRepeatInstanceKeys as Ke}from"@vcp-dev/contracts";import{parse as oS}from"yaml";import ko from"node:path";function An(e,t,n){return`${e}::${t}::${n}`}var B={NODE_NOT_FOUND:"NODE_NOT_FOUND",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"};import ri from"@babel/traverse";import*as h from"@babel/types";import{createHash as np}from"node:crypto";import*as Ua from"@babel/parser";function _t(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function U(e,t,n,r,o){return{ok:!1,source:e,diagnostic:_t(t,n,r,o)}}function Zo(e,t,n,r,o){return{ok:!1,source:e,diagnostic:_t(t,n,r,o)}}var Gf={"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:Ua.parse(t,{sourceType:"module",plugins:Gf[n]})}}catch(r){return{ok:!1,source:t,diagnostic:_t("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Qo(e,t){return rt({source:e,profile:$a(t.kind)})}function qo(e,t){return rt({source:e,profile:$a(t)})}function $a(e){return"next-app-entry"}function Dt(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*as Zf from"@babel/parser";import*as en from"@babel/types";import*as gt from"node:path";var ei=[".tsx",".ts",".jsx",".js"],Qf=ei.map(e=>`/index${e}`);function Ka(e){let t=[];for(let n of e.program.body)en.isImportDeclaration(n)&&typeof n.source.value=="string"&&ct(n.source.value)&&t.push(n.source.value),en.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&ct(n.source.value)&&t.push(n.source.value),en.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&ct(n.source.value)&&t.push(n.source.value);return t}function ct(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function qf(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=gt.dirname(e);return gt.join(n,t).replace(/\\/g,"/")}async function ep(e,t){if(ei.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of ei){let r=`${e}${n}`;if(await t(r))return r}for(let n of Qf){let r=`${e}${n}`;if(await t(r))return r}return null}async function tn(e,t,n){let r=await Cr(e,t,n);return r.ok?r.path:null}async function Cr(e,t,n){let r=qf(e,t);try{if(!tp(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 ep(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 tp(e,t,n){if(!ct(t)||t.includes("\0")||t.includes("\\")||gt.posix.isAbsolute(n))return!1;let r=gt.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!gt.posix.isAbsolute(e)}var ti=(e,t)=>{let n=rt({source:t,profile:Dt({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${np("sha256").update(t).digest("hex")}`,ast:n.ast,imports:Ka(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};var Rr="components/ui";function Lt(e){if(!e)return!1;let t=ni(e);return t===Rr||t.startsWith(`${Rr}/`)||t.includes(`/${Rr}/`)||t.endsWith(`/${Rr}`)}function Nn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Lt(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Lt(ni(`${rp(t)}/${e}`)):Lt(e):!1}function ni(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 rp(e){let t=ni(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var op=typeof ri=="function"?ri:ri.default;function Re(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 ip(e){return/^[A-Z]/.test(e)}function li(e){let t=e.openingElement;return h.isJSXIdentifier(t.name)?t.name.name==="Fragment":h.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function rn(e){return h.isJSXFragment(e)}function Ha(e){return h.isJSXIdentifier(e.name)?e.name.name:h.isJSXMemberExpression(e.name)?za(e.name):h.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function za(e){return h.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:h.isJSXMemberExpression(e.object)?`${za(e.object)}.${e.property.name}`:e.property.name}function sp(e){return e.split(".")[0]??e}function ap(e){let t=e;for(;t;){let n=t.node;if(h.isFunctionDeclaration(n)&&n.id||h.isVariableDeclarator(n)&&h.isIdentifier(n.id))return n.id.name;if(h.isExportDefaultDeclaration(n)){let r=n.declaration;if(h.isFunctionDeclaration(r)&&r.id)return r.id.name;if(h.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function cp(){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 lp(e){let t=new Map;for(let n of e.program.body){if(!h.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(h.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(h.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(h.isImportSpecifier(o)){let i=h.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function lt(e,t=[]){if(h.isIdentifier(e))return t.push(e.name),t;if(h.isObjectPattern(e)){for(let n of e.properties)h.isObjectProperty(n)?lt(n.value,t):h.isRestElement(n)&&lt(n.argument,t);return t}if(h.isArrayPattern(e)){for(let n of e.elements)n&&(h.isRestElement(n)?lt(n.argument,t):lt(n,t));return t}return h.isAssignmentPattern(e)?(lt(e.left,t),t):(h.isRestElement(e)&&lt(e.argument,t),t)}function yt(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Pr(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 up(e,t,n){e.set(t,{resolved:!0,value:n})}function ui(e,t){e.set(t,{resolved:!1})}function Wa(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 Ce(e,t,n){if(h.isTSAsExpression(e)||h.isTSSatisfiesExpression(e)||h.isTSNonNullExpression(e)||h.isTypeCastExpression(e)||h.isParenthesizedExpression(e))return Ce(e.expression,t,n);if(h.isLogicalExpression(e))return oi([Ce(e.left,t,n),Ce(e.right,t,n)]);if(h.isConditionalExpression(e))return oi([Ce(e.consequent,t,n),Ce(e.alternate,t,n)]);if(h.isTemplateLiteral(e))return oi(e.expressions.filter(h.isExpression).map(i=>Ce(i,t,n)));if(h.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!h.isMemberExpression(e)&&!h.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;h.isMemberExpression(o)||h.isOptionalMemberExpression(o);){if(o.computed)if(h.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(h.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&h.isExpression(o.property)){let i=Bt(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(!h.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return h.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:yt(e,t),base:o.name,path:r}:null}function oi(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 Bt(e,t){if(h.isStringLiteral(e)||h.isNumericLiteral(e)||h.isBooleanLiteral(e))return e.value;if(h.isNullLiteral(e))return null;if(h.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(h.isIdentifier(e)){let n=Pr(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(h.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||h.isSpreadElement(r))return;let o=Bt(r,t);if(o===void 0)return;n.push(o)}return n}if(h.isObjectExpression(e)){let n={};for(let r of e.properties){if(!h.isObjectProperty(r)||r.computed||!h.isExpression(r.value))return;let o=null;if(h.isIdentifier(r.key)?o=r.key.name:h.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!h.isIdentifier(r.value))return;let s=Pr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Bt(r.value,t);if(i===void 0)return;n[o]=i}return n}if(h.isMemberExpression(e)){let n=Ce(e,"",t);if(!n)return;let r=Pr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Wa(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(h.isCallExpression(e))return Ga(e,t)??void 0}function Ya(e,t,n){let r=Ce(e,n,t);if(!r)return h.isMemberExpression(e)||h.isBinaryExpression(e)||h.isLogicalExpression(e)||h.isConditionalExpression(e)||h.isCallExpression(e)?{value:yt(e,n),source:null}:null;let o=Pr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Wa(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 ii(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:cp(),parentStack:[],valueScopes:i,importMap:o}}function ai(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of lt(o.id))ui(n,s);if(!h.isIdentifier(o.id)||!o.init||!h.isExpression(o.init))continue;let i=Bt(o.init,t);i!==void 0&&up(n,o.id.name,i)}}function dp(e){let t=[];for(let n of e){if(h.isVariableDeclaration(n)){t.push(n);continue}h.isExportNamedDeclaration(n)&&n.declaration&&h.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function fp(e,t,n){let r=[],o=0;for(let i of e)if(h.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Re(i),editable:!0,source:null})}else if(h.isJSXExpressionContainer(i)&&h.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Re(i),editable:!0,source:null});else if(h.isJSXExpressionContainer(i)&&h.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:Re(i),editable:!0,source:null}):r.push({index:o++,value:yt(s,n),sourceRange:Re(i),editable:!0,source:Ce(s,n,t)})}else if(h.isJSXExpressionContainer(i)&&h.isExpression(i.expression)){let s=Ya(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Re(i),editable:!0,source:s.source})}return r}function pp(e,t,n){let r=[];for(let o of e.attributes)if(!(!h.isJSXAttribute(o)||!h.isJSXIdentifier(o.name))){if(h.isStringLiteral(o.value)){r.push({name:o.name.name,value:o.value.value,sourceRange:Re(o),source:null});continue}if(h.isJSXExpressionContainer(o.value)&&h.isExpression(o.value.expression)){let i=Bt(o.value.expression,t);if(o.name.name==="className"){let a=typeof i=="string"?i:i===void 0?Ga(o.value.expression,t):null;if(a){r.push({name:o.name.name,value:a,sourceRange:Re(o),source:null,resolvedValue:a});continue}}let s=Ya(o.value.expression,t,n);if(i!==void 0&&typeof i!="string"&&typeof i!="number"){r.push({name:o.name.name,value:Ja(i),sourceRange:Re(o),source:Ce(o.value.expression,n,t),resolvedValue:i});continue}if(!s){i!==void 0&&r.push({name:o.name.name,value:Ja(i),sourceRange:Re(o),source:Ce(o.value.expression,n,t),resolvedValue:i});continue}r.push({name:o.name.name,value:s.value,sourceRange:Re(o),source:s.source})}}return r}function Ga(e,t){let n=nn(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function nn(e,t){if(h.isStringLiteral(e))return[e.value];if(h.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(h.isNullLiteral(e))return[];if(h.isBooleanLiteral(e))return e.value?null:[];if(h.isIdentifier(e)||h.isMemberExpression(e)){if(h.isIdentifier(e)&&e.name==="undefined")return[];let n=Bt(e,t);return typeof n=="string"?[n]:null}if(h.isConditionalExpression(e)){let n=nn(e.consequent,t),r=nn(e.alternate,t);return!n||!r?null:[...n,...r]}if(h.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Bt(e.left,t);return n===!1||n===null?[]:nn(e.right,t)}if(h.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||h.isSpreadElement(r))return null;let o=nn(r,t);if(!o)return null;n.push(...o)}return n}if(h.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!h.isObjectProperty(r))return null;let o=hp(r.key);if(!o)return null;n.push(o)}return n}if(h.isCallExpression(e)){let n=mp(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!h.isExpression(o))return null;let i=nn(o,t);if(!i)return null;r.push(...i)}return r}return null}function mp(e){return h.isIdentifier(e)?e.name:h.isMemberExpression(e)&&h.isIdentifier(e.property)?e.property.name:null}function hp(e){return h.isIdentifier(e)?e.name:h.isStringLiteral(e)?e.value:null}function gp(e,t){let n=e.attributes.find(r=>h.isJSXAttribute(r)&&h.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!h.isJSXAttribute(n)||!h.isJSXExpressionContainer(n.value)?null:n.value.expression}function yp(e,t){for(let n of t){let r=gp(e,n);if(r)return r}return null}function xp(e){return h.isJSXIdentifier(e.name)?e.name.name:null}function Ja(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function Ep(e){if(!h.isCallExpression(e)&&!h.isOptionalCallExpression(e))return null;let t=e.callee;return!h.isMemberExpression(t)&&!h.isOptionalMemberExpression(t)||!h.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!h.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function si(e){return h.isArrowFunctionExpression(e)||h.isFunctionExpression(e)}function Sp(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function bp(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function Xa(e,t,n,r){if(!e||!h.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:yt(e,n),collectionSource:Ce(e,n,r)};if(t){let i=t.params[0],s=t.params[1];h.isIdentifier(i)&&(o.itemParamName=i.name),h.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function xt(e,t,n){if(!e)return[];if(h.isJSXElement(e)){if(li(e))return Fr(e.children,t,n);let r=Nr(e,t,n);return r?[r]:[]}return rn(e)?Tr(e,t,n):h.isParenthesizedExpression(e)?xt(e.expression,t,n):h.isExpression(e)?Mr(e,t,n):[]}function wr(e,t,n){let r=new Map;for(let o of e.params)for(let i of lt(o))ui(r,i);t.valueScopes.push(r);try{if(!h.isBlockStatement(e.body))return xt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Za(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Za(e,t,n){let r=[];for(let o of e){if(h.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];i&&ai([o],t,i);continue}r.push(...ci(o,t,n))}return r}function ci(e,t,n){if(h.isReturnStatement(e))return e.argument?xt(e.argument,t,n):[];if(h.isBlockStatement(e))return jt(e.body,t,n);if(h.isIfStatement(e)){let r=h.isBlockStatement(e.consequent)?jt(e.consequent.body,t,n):ci(e.consequent,t,n),o=e.alternate?h.isBlockStatement(e.alternate)?jt(e.alternate.body,t,n):ci(e.alternate,t,n):[];return[...r,...o]}if(h.isSwitchStatement(e))return jt(e.cases.flatMap(r=>r.consequent),t,n);if(h.isTryStatement(e)){let r=jt(e.block.body,t,n);return e.handler&&r.push(...jt(e.handler.body.body,t,n)),e.finalizer&&r.push(...jt(e.finalizer.body,t,n)),r}return[]}function jt(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Za(e,t,n)}finally{t.valueScopes.pop()}}function Ar(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Re(r),sourceCandidates:i&&i.length>0?i:void 0})}function Ip(e,t,n,r){let o=yp(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Ha(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!h.isJSXAttribute(s))continue;let a=xp(s);if(!a||!h.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!h.isJSXEmptyExpression(c)){if(Sp(a)&&si(c)){let l=wr(c,n,r),u=Xa(o,c,r,n);Ar(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(bp(a)){let l=si(c)?wr(c,n,r):xt(c,n,r);Ar(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!h.isJSXExpressionContainer(s)||!si(s.expression))continue;let a=wr(s.expression,n,r),c=Xa(o,s.expression,r,n);Ar(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function Nr(e,t,n){let r=Ha(e.openingElement);if(r==="Fragment"||li(e))return Fr(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=ip(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=An(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},p=s?"component-boundary":null,m=fp(e.children,t,n),E=pp(e.openingElement,t,n),b,v,C=!1;if(s){let N=t.importMap.get(r)??t.importMap.get(sp(r));N&&(b=N.specifier,v=N.exportName,C=Nn(N.specifier,t.file))}let A={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Re(e),parentKey:i,childKeys:[],textSegments:m,attributes:E.length>0?E:void 0,boundaryKind:p,isOpaque:s,...C?{isPublicUiComponent:!0}:{},importedFrom:b,exportName:v};return t.elements.set(u,A),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),Ip(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),kp(e.children,t,n),t.parentStack.pop()),u}function Tr(e,t,n){return Fr(e.children,t,n)}function Fr(e,t,n){let r=[];for(let o of e)if(h.isJSXElement(o))if(li(o))r.push(...Fr(o.children,t,n));else{let i=Nr(o,t,n);i&&r.push(i)}else rn(o)?r.push(...Tr(o,t,n)):h.isJSXExpressionContainer(o)&&r.push(...Mr(o.expression,t,n));return r}function kp(e,t,n){for(let r of e)h.isJSXElement(r)?Nr(r,t,n):rn(r)?Tr(r,t,n):h.isJSXExpressionContainer(r)&&Mr(r.expression,t,n)}function vp(e){return e==="&&"||e==="||"||e==="??"}function Mr(e,t,n){if(h.isJSXEmptyExpression(e))return[];let r=Ep(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:yt(r.collection,n),collectionSource:Ce(r.collection,n,t)};if(h.isArrowFunctionExpression(a)||h.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];h.isIdentifier(u)&&(c.itemParamName=u.name),h.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Re(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(h.isArrowFunctionExpression(a)||h.isFunctionExpression(a))&&l.childKeys.push(...wr(a,t,n)),l.childKeys}if(h.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:yt(e.test,n),conditionSource:Ce(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Re(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...xt(e.consequent,t,n)),s.childKeys.push(...xt(e.alternate,t,n)),s.childKeys}if(h.isLogicalExpression(e)&&vp(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:yt(e.left,n),conditionSource:Ce(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Re(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...xt(e.right,t,n)),s.childKeys}if(h.isParenthesizedExpression(e))return Mr(e.expression,t,n);if(h.isJSXElement(e)){let o=Nr(e,t,n);return o?[o]:[]}return rn(e)?Tr(e,t,n):[]}function Cp(e){let t=e.argument;return t&&(h.isExpression(t)||rn(t))?t:null}function Tn(e,t){let n=[];for(let r of e){if(h.isReturnStatement(r)){let o=Cp(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(h.isIfStatement(r)){let o=h.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Tn(o,r.test)),r.alternate){let i=h.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Tn(i,r.test))}continue}if(h.isSwitchStatement(r))for(let o of r.cases){let i=o.test?h.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Tn(o.consequent,i))}}return n}function Qa(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(d=>d.specifier),i=new Map,s=[],a=[],c=new Map,l=lp(r);op(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(d){let p=ap(d);if(!p)return;let m=d.node,E=[];if(h.isArrowFunctionExpression(m))h.isExpression(m.body)||rn(m.body)?E=[{argument:m.body,statement:h.returnStatement(h.isExpression(m.body)?m.body:null)}]:h.isBlockStatement(m.body)&&(E=Tn(m.body.body));else{let G=m.body;h.isBlockStatement(G)&&(E=Tn(G.body))}if(E.length===0){d.skip();return}let b=new Map;ai(dp(r.program.body),ii(t,p,i,s,l,[b]),b);let v=new Map;for(let G of m.params)for(let fe of lt(G))ui(v,fe);let C=h.isBlockStatement(m.body)?m.body.body:[],A=E[0]?.statement??null;for(let G of C){if(A&&G===A)break;h.isVariableDeclaration(G)&&ai([G],ii(t,p,i,s,l,[b,v]),v)}let N=ii(t,p,i,s,l,[b,v]);for(let G of E){let fe=xt(G.argument,N,n);for(let ue of fe)a.includes(ue)||a.push(ue);if(G.condition){let ue={kind:"conditional-branch",conditionExpression:yt(G.condition,n),conditionSource:Ce(G.condition,n,N)};Ar(N,"conditional-region","",G.statement,fe,[ue])}}d.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 di(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Or(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function qa(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??ti,c=new Map,l=new Map,u=new Map,d=[],p=new Set,m=C=>{let A=`${C.path}\0${C.code}\0${C.message}\0${JSON.stringify(C.details??{})}`;p.has(A)||(p.add(A),d.push(C))},E=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(C=>({file:C.file,source:C.source,depth:0,diagnosticEntryFile:C.file,importStack:[]}))],b=new Set;for(;E.length>0;){let C=E.shift(),{file:A,source:N,depth:G,diagnosticEntryFile:fe,importStack:ue}=C;if(b.has(A))continue;b.add(A),c.set(A,N);let R=a(A,N);if(!R.ok){m(Or(R.diagnostic,fe,ue));continue}u.set(A,R.module);let{graph:_,localImports:D}=Qa(R.module);for(let L of _.elements.values())if(L.importedFrom&&ct(L.importedFrom)){let Z=L.importedFrom,Q=await Cr(A,Z,r);Q.ok?(L.importedFrom=Q.path,Lt(Q.path)&&(L.isPublicUiComponent=!0)):Nn(Z,A)||m(Or(Q.diagnostic,fe,di(ue,A,Z,Q.diagnostic.path)))}if(l.set(A,_),!(G>=i))for(let L of D){if(Rp(L))continue;let Z=await Cr(A,L,r);if(!Z.ok){Nn(L,A)||m(Or(Z.diagnostic,fe,di(ue,A,L,Z.diagnostic.path)));continue}let Q=Z.path;if(b.has(Q)||Lt(Q))continue;let he=di(ue,A,L,Q);try{let W=await n(Q);E.push({file:Q,source:W,depth:G+1,diagnosticEntryFile:fe,importStack:he})}catch(W){m(Or({path:Q,code:"import-read-failed",message:`Failed to read imported file: ${Q}`,details:{fromFile:A,specifier:L,reason:W instanceof Error?W.message:String(W)}},fe,he))}}}let v=Pp(e,l,s,(o.additionalEntries??[]).map(C=>C.file));return v.diagnostics=d,{graph:v,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function Rp(e){return/\.(?:css|scss|sass|less)(?:\?.*)?$/i.test(e)}function Pp(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,d]of l.elements)o.set(u,d);for(let u of l.regions)i.push(u);for(let[u,d]of l.fileIndex){let p=s.get(u)??[];s.set(u,[...p,...d])}if(c===e){a=l.rootKeys;continue}r.includes(c)&&(a=[...a,...l.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}function ec(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}),tc(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function tc(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}),tc(s,t,n,r,o))}}import{isSiteEditRuntimeContainerTag as wp,isSiteEditRuntimeVoidElementTag as Ap}from"@vcp-dev/contracts/site-edit-runtime-capability";function Np(e,t,n){let r=t.nodes.get(e),o=n.elements.get(e);if(!r||!o)return{key:e,canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1,constraints:[{kind:"opaque-region",message:"Node not found in graph"}]};let i=r.constraints.map(N=>({kind:N.kind,message:N.reason})),s=o.isOpaque,c=r.parentKey===null&&o.componentName==="Page",l=o.tag.toLowerCase(),u=o.tag!==l,d=!u&&Ap(l),p=u||wp(l),m=u&&o.childKeys.length>0&&!o.isPublicUiComponent,E=o.textSegments.length>0&&o.textSegments.some(N=>N.editable);d&&!i.some(N=>N.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' is void: children cannot be inserted`}),!d&&!p&&!i.some(N=>N.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' cannot contain structured children`});let b=E&&!s,v=!o.isPublicUiComponent&&!d&&p&&(!s||m);return{key:e,canUpdateText:b,canInsertChild:v,canMove:!c,canRemove:!c,constraints:i}}function nc(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,Np(r,e,t));return n}import{createHash as Li}from"node:crypto";import Ti from"@babel/traverse";function fi(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 nh}from"node:crypto";import _c from"node:path";import*as Gr from"@babel/parser";import Ri from"@babel/generator";import Pi from"@babel/traverse";import*as bt from"@babel/types";import pi from"@babel/traverse";var Et=typeof pi=="function"?pi:pi.default,_r=new WeakMap,rc=new WeakMap;function dt(e,t){let n=Qo(e,t);if(!n.ok)return Zo(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=te(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}}:Zo(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function te(e,t){return t.kind==="jsx-node"?ac(e,t):t.kind==="jsx-attribute"?Dp(e,t):t.kind==="value"?Lp(e,t):t.kind==="expression"?jp(e,t):t.kind==="directive"?Bp(e,t):t.kind==="export"?Vp(e,t):{ok:!1,diagnostic:_t("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function ac(e,t){return t.strategy==="source-range"?Tp(e,t):Fp(e,t)}function Tp(e,t){let n=null;if(Et(e,{JSXElement(o){if(!sn(o.node,t.sourceRange))return;let i=xe("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!sn(o.node,t.sourceRange))return;let i=xe("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!sn(o.node,t.sourceRange))return;let i=xe("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Ee("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!Zp(r.path,t.expectedIdentity)?Ee("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function Fp(e,t){if(t.structuralPath===""){let r=Op(e,t.component);if(r){let o=_p(r);if(o)return o}}let n=null;return Et(e,{JSXElement(r){if(Mn(r)!==t.component||hi(r)!==t.structuralPath)return;let i=xe("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Mn(r)!==t.component||hi(r)!==t.structuralPath)return;let i=xe("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Mp(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Ee("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Mp(e,t,n){let r=null;return Et(e,{JSXElement(o){if(Mn(o)!==t||!sn(o.node,n))return;let i=xe("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Mn(o)!==t||!sn(o.node,n))return;let i=xe("jsx-node",o);i&&(r=i,o.stop())}}),r}function Op(e,t){let n=null;return Et(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 _p(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 Ee("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Ee("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 Ee("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function Dp(e,t){let n=ac(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Qp(c,t.name));if(!s||!s.isJSXAttribute())return Ee("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=xe("jsx-attribute",s);return a?{ok:!0,match:a}:Ee("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function Lp(e,t){let n=Up(e,t);if(!n.ok)return n;let r=$p(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!ut(r.match.path.node.loc,t.expectedRange)?Ee("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function jp(e,t){let n=null;return Et(e,{Identifier(r){if(!zp(r))return;let o=ic(r);if(!o||!sc(o,t))return;let i=xe("expression",r);i&&(t.expectedRange&&!ut(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=ic(r);if(!o||!sc(o,t))return;let i=xe("expression",r);i&&(t.expectedRange&&!ut(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Ee("expression","locator-miss","Expression not found")}function Bp(e,t){let n=null;return Et(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=xe("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Ee("directive","locator-miss",`Directive '${t.value}' not found`)}function Vp(e,t){let n=null;return Et(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let p=xe("export",c);if(!p||t.expectedRange&&!ut(c.node.loc,t.expectedRange))return;n=p,r.stop();return}if(!c.isVariableDeclaration())return;let l=gi(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=xe("export",u);if(!d||t.expectedRange&&!ut(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=gi(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=xe("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=xe("export",o);i&&(t.expectedRange&&!ut(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Ee("export","export-not-found",`Export '${Gp(t)}' not found`)}function Up(e,t){let n=null;return Et(e,{Expression(r){if(n||t.root.kind!=="expression"||!sn(r.node,t.root.sourceRange))return;let o=xe("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let m=r.get("init");if(!m.node)return;let E=xe("value",m);if(!E)return;n=E,r.stop();return}if(t.root.kind!=="hook-state")return;let o=t.root,i=r.get("id"),s=r.get("init");if(!i.isArrayPattern()||!s.isCallExpression()||i.node.elements.findIndex(m=>m?.type==="Identifier"&&m.name===o.name)!==0)return;let c=s.node.callee;if((c.type==="Identifier"?c.name:c.type==="MemberExpression"&&c.property.type==="Identifier"?c.property.name:null)!==o.hook)return;let u=o.hook==="useReducer"?1:0,d=r.get(`init.arguments.${u}`);if(!d||Array.isArray(d)||!d.node)return;let p=xe("value",d);p&&(n=p,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=gi(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=xe("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=xe("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:Ee("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 $p(e,t){let n=mi(e);for(let o of t){if(n=mi(n),o.kind==="property"){if(!n.isObjectExpression())return Ee("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return Ee("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>qp(l,o.name));if(!c||!c.isObjectProperty())return Ee("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return Ee("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return Ee("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return Ee("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=mi(n);let r=xe("value",n);return r?{ok:!0,match:r}:Ee("value","locator-miss","Resolved value has no source range")}function mi(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function xe(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 sn(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 hi(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Dr(n.node)){let o=cc(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${oc(n,o)}`):t.unshift(`${o}#${oc(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Hp(n.parentPath))break;n=n.parentPath}return t.join("/")}function Dr(e){let t=e.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function oc(e,t){let n=Kp(e);if(!n)return 0;let r=_r.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=_r.get(n.node)?.get(t);if(!i){let s=_r.get(n.node);s||(s=new Map,_r.set(n.node,s)),i=new WeakMap,s.set(t,i)}for(let s of Fn(n))if(cc(s.node.openingElement)===t){if(i.set(s.node,o),s.node===e.node)return o;o++}return i.get(e.node)??0}function Kp(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Dr(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Fn(e){let t=rc.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(Dr(o.node)){n.push(...Fn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Fn(o));continue}o.isJSXExpressionContainer()&&n.push(...on(o.get("expression")))}return rc.set(e.node,n),n}function on(e){return e.isJSXElement()?Dr(e.node)?Fn(e):[e]:e.isJSXFragment()?Fn(e):e.isParenthesizedExpression()?on(e.get("expression")):e.isLogicalExpression()&&Jp(e.node.operator)?on(e.get("right")):e.isConditionalExpression()?[...on(e.get("consequent")),...on(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:on(t)):[]}function Jp(e){return e==="&&"||e==="||"||e==="??"}function cc(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Xp(e.name):null}function Xp(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 Mn(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 Hp(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function zp(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function ic(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 sc(e,t){return e.base===t.base&&Wp(e.path,t.path??[])}function Wp(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 Yp(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Gp(e){return e.exportKind==="named"?e.name:e.exportKind}function Ee(e,t,n,r){return{ok:!1,diagnostic:_t(t,n,e,r)}}function Zp(e,t){return Mn(e)!==t.component?!1:hi(e)===t.structuralPath}function Qp(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function gi(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function qp(e,t){return e.isObjectProperty()?Yp(e.node)===t:!1}import yi from"@babel/generator";var em=typeof yi=="function"?yi:yi.default;function tm(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 nm(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 rm(e,t){return e.split(`
3
+ `).map(r=>nm(r,t)).join(`
4
+ `)}function Lr(e){let{ast:t,source:n}=e;try{let r=tm(n),i=em(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=rm(i,r)),{ok:!0,source:i}}catch(r){return U(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}import*as uc from"@babel/parser";import{arrayExpression as om,booleanLiteral as im,identifier as sm,jsxAttribute as am,jsxExpressionContainer as cm,jsxIdentifier as lm,nullLiteral as um,numericLiteral as dm,objectExpression as fm,objectProperty as pm,stringLiteral as dc}from"@babel/types";function lc(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 On(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:lc(e),afterSourceHash:lc(t),inverse:n.inverse}}}function ce(e,t,n){let r=Lr({ast:e,source:t});return r.ok?On(t,r.source,n):r}function Se(e,t){let n=qo(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function jr(e,t){return Lr({ast:e,source:t})}function mm(e,t,n){let r=te(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function fc(e,t,n){let r=mm(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:U(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function pc(e,t){let n=te(e,t);return n.ok?{ok:!0,match:n.match}:n.diagnostic.code==="locator-miss"?{ok:!0,match:null}:{ok:!1,diagnostic:n.diagnostic}}function an(e){return typeof e=="string"?dc(e):typeof e=="number"?dm(e):typeof e=="boolean"?im(e):e===null?um():Array.isArray(e)?om(e.map(t=>an(t))):fm(Object.entries(e).map(([t,n])=>pm(sm(t),an(n))))}function hm(e){return typeof e=="string"?dc(e):cm(an(e))}function Br(e,t){return am(lm(e),hm(t))}function mc(e,t){try{let r=uc.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:U(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:U(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Vr(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=Se(t,"jsx-node");if(!i.ok)return i.result;let s=te(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=gm(s.match.path)[r];if(!c)return U(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=ym(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 ce(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function gm(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=xm(r.get("expression"));o.length>0&&t.push(...o)}}return t}function ym(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function xm(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 xi}from"@babel/types";function cn(e){let{source:t,locator:n}=e,r=Se(t,"jsx-node");if(!r.ok)return r.result;let o=te(r.ast,n);return o.ok?(Em(o.match.path),ce(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function Em(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(xi());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(xi());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(xi());return}e.remove()}import{cloneNode as Nm}from"@babel/types";import Ei from"@babel/traverse";import*as $ from"@babel/types";var Sm=typeof Ei=="function"?Ei:Ei.default;function Be(e,t,n,r){if(!e.ok)return e;let o=je(n);if(!o)return e;let i=bm(t,o,r);return i?{...e,selectionRef:i}:e}function bm(e,t,n){let r=Im(e,t);if(!r)return;let o=n.sourceLocator?hc(n.sourceLocator):void 0,i=n.targetParentLocator?hc(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??vm(r)??i?.component??o?.component;if(!(!s||!a))return{key:An(s,a,Cm(r))}}function hc(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Im(e,t){let n=null;return Sm(e,{JSXElement(r){r.node===t&&(n=r,r.stop())}}),n}function je(e){if(!e)return null;if($.isJSXElement(e))return ln(e)?gc(e.children):e;if($.isJSXFragment(e))return gc(e.children);if($.isJSXExpressionContainer(e)||$.isParenthesizedExpression(e)||$.isTSAsExpression(e)||$.isTSSatisfiesExpression(e)||$.isTSTypeAssertion(e)||$.isTSNonNullExpression(e))return je(e.expression);if($.isLogicalExpression(e))return je(e.right);if($.isConditionalExpression(e))return je(e.consequent)??je(e.alternate);if($.isCallExpression(e)||$.isOptionalCallExpression(e))return bc(e)?km(e.arguments[0]):null;if($.isArrayExpression(e))for(let t of e.elements){if(!t)continue;let n=je(t);if(n)return n}return null}function gc(e){for(let t of e){let n=je(t);if(n)return n}return null}function km(e){return!e||!$.isArrowFunctionExpression(e)&&!$.isFunctionExpression(e)?null:$.isBlockStatement(e.body)?_n(e.body.body):je(e.body)}function _n(e){for(let t of e){if($.isReturnStatement(t)){let n=je(t.argument);if(n)return n;continue}if($.isBlockStatement(t)){let n=_n(t.body);if(n)return n;continue}if($.isIfStatement(t)){let n=yc(t.consequent);if(n)return n;let r=t.alternate?yc(t.alternate):null;if(r)return r;continue}if($.isSwitchStatement(t))for(let n of t.cases){let r=_n(n.consequent);if(r)return r}}return null}function yc(e){return $.isBlockStatement(e)?_n(e.body):_n([e])}function vm(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($.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&$.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 xc=new WeakMap,Ec=new WeakMap,Si=new WeakMap;function Cm(e){let t=xc.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Rm(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return xc.set(e.node,o),o}function Rm(e){let t=bi(e.node.openingElement.name);return!t||ln(e.node)?null:/^[A-Z]/.test(t)?`component:${t}#${Sc(e,t)}`:`${t}#${Sc(e,t)}`}function Sc(e,t){let n=Pm(e);if(!n)return 0;let r=Si.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Si.get(n.node);o||(o=new Map,Si.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Vt(n))if(bi(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 Pm(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(ln(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Vt(e){let t=Ec.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(ln(o.node)){n.push(...Vt(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Vt(o));continue}o.isJSXExpressionContainer()&&n.push(...ft(o.get("expression")))}return Ec.set(e.node,n),n}function ft(e){if(e.isJSXElement())return ln(e.node)?Vt(e):[e];if(e.isJSXFragment())return Vt(e);if(e.isParenthesizedExpression())return ft(e.get("expression"));if(e.isLogicalExpression())return ft(e.get("right"));if(e.isConditionalExpression())return[...ft(e.get("consequent")),...ft(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:ft(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&bc(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?wm(n):[]}return[]}function wm(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return ln(t.node)?Vt(t):[t];if(t.isJSXFragment())return Vt(t);if(t.isParenthesizedExpression())return ft(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return ft(t);if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?ft(r):[]}return[]}function bc(e){let t=e.callee;return($.isMemberExpression(t)||$.isOptionalMemberExpression(t))&&$.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function ln(e){let t=bi(e.openingElement.name);return t==="Fragment"||t==="React.Fragment"}function bi(e){return $.isJSXIdentifier(e)?e.name:$.isJSXMemberExpression(e)?Ic(e):$.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Ic(e){return`${$.isJSXIdentifier(e.object)?e.object.name:Ic(e.object)}.${e.property.name}`}function St(e,t){if(t.parentPath===e&&t.listKey==="children"&&kc(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!kc(n))return null;let r=n;for(;r&&r!==e;){if(!Am(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function kc(e){return e.isJSXElement()||e.isJSXFragment()}function Am(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function un(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Se(t,"jsx-node");if(!a.ok)return a.result;let c=te(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return U(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 N=c.match.path.node;if(!N.closingElement||N.openingElement.selfClosing)return U(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=mc(t,r.jsx);if(!u.ok)return u.result;let d=Nm(u.node,!0),p=l.node.children,m={...s,targetParentLocator:n},E=N=>s?Be(N,a.ast,d,m):N;if(o==="append")return p.push(d),E(ce(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return p.unshift(d),E(ce(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return U(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let b=te(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let v=St(c.match.path,b.match.path);if(!v)return U(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=v;let C=l.node.children,A=C.findIndex(N=>N===b.match.path.node);return A===-1?U(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(C.splice(o==="before"?A:A+1,0,d),E(ce(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as vc from"@babel/parser";import{cloneNode as Tm}from"@babel/types";function Ur(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Se(t,"jsx-node");if(!a.ok)return a.result;let c=Fm(t,r);if(!c.ok)return c.result;let l=te(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return U(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let C=l.match.path.node;if(!C.closingElement||C.openingElement.selfClosing)return U(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let C=te(a.ast,i);if(!C.ok)return{ok:!1,source:t,diagnostic:C.diagnostic};let A=St(l.match.path,C.match.path);if(!A)return U(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=A,d=C.match.path.node}else if(o==="before"||o==="after")return U(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=Tm(c.node,!0),m=u.node.children,E={...s,targetParentLocator:n},b=C=>s?Be(C,a.ast,p,E):C;if(o==="append")return m.push(p),b(ce(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(p),b(ce(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let v=m.findIndex(C=>C===d);return v===-1?U(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(m.splice(o==="before"?v:v+1,0,p),b(ce(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function Fm(e,t){try{let r=vc.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:U(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:U(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as Mm,nullLiteral as Ii}from"@babel/types";import*as dn from"@babel/types";function fn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Se(t,"jsx-node");if(!a.ok)return a.result;let c=te(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=te(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return U(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 A=l.match.path.node;if(!A.closingElement||A.openingElement.selfClosing)return U(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let A=te(a.ast,i);if(!A.ok)return{ok:!1,source:t,diagnostic:A.diagnostic};let N=St(l.match.path,A.match.path);if(!N)return U(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=N,d=A.match.path}else if(o==="before"||o==="after")return U(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=d&&typeof d.key=="number"?d.key:-1;if(d&&p===-1)return U(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let m=Mm(c.match.path.node,!0);if(!dn.isJSXElement(m)&&!dn.isJSXExpressionContainer(m)&&!dn.isJSXFragment(m))return U(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let E=c.match.path.parentPath?.node===u.node&&typeof c.match.path.key=="number"?c.match.path.key:-1;if(d&&c.match.path.parentPath?.node===d.parentPath?.node&&c.match.path.key===d.key)return U(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");Om(c.match.path);let b=u.node.children,v={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return b.push(m),Be(jr(a.ast,t),a.ast,m,v);if(o==="prepend")return b.unshift(m),Be(jr(a.ast,t),a.ast,m,v);let C=p-(E!==-1&&E<p?1:0);return b.splice(o==="before"?C:C+1,0,m),Be(jr(a.ast,t),a.ast,m,v)}function Om(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ii());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ii());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ii());return}e.remove()}import*as Cc from"@babel/parser";import{cloneNode as _m,nullLiteral as ki}from"@babel/types";function $r(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=Se(t,"jsx-node");if(!c.ok)return c.result;let l=Dm(t,s);if(!l.ok)return l.result;let u=te(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=te(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return U(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let N=d.match.path.node;if(!N.closingElement||N.openingElement.selfClosing)return U(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let p=d.match.path,m=null;if(i){let N=te(c.ast,i);if(!N.ok)return{ok:!1,source:t,diagnostic:N.diagnostic};let G=St(d.match.path,N.match.path);if(!G)return U(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");p=G,m=N.match.path.node}else if(o==="before"||o==="after")return U(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return U(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let E=p.node,b=_m(l.node,!0);Lm(u.match.path);let v={...a,sourceLocator:n,targetParentLocator:r},C=E.children;if(o==="append")return C.push(b),Be(ce(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,v);if(o==="prepend")return C.unshift(b),Be(ce(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,v);let A=C.findIndex(N=>N===m);return A===-1?U(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(C.splice(o==="before"?A:A+1,0,b),Be(ce(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,v))}function Dm(e,t){try{let r=Cc.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:U(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:U(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Lm(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ki());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ki());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ki());return}e.remove()}function Kr(e){let{source:t,locator:n,props:r}=e,o=Se(t,"jsx-node");if(!o.ok)return o.result;let i=fc(o.ast,n,t);if(!i.ok)return i.result;let s=i.match.path.node.openingElement;for(let[a,c]of Object.entries(r)){if(c===void 0)continue;let l={kind:"jsx-attribute",element:n,name:a},u=pc(o.ast,l);if(u.ok&&u.match!==null){let d=u.match.path.node;d.value=c===""?Br(a,"").value:Br(a,c).value}else s.attributes.push(Br(a,c))}return ce(o.ast,t,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}import{getBindingIdentifiers as jm,identifier as Dn,importDeclaration as Bm,importDefaultSpecifier as Vm,importNamespaceSpecifier as Um,importSpecifier as $m,isImportDefaultSpecifier as Rc,isImportNamespaceSpecifier as Pc,isImportSpecifier as wc,stringLiteral as Km}from"@babel/types";function pn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(v=>!Qm(v));if(o!==-1){let v=r[o],C=v&&typeof v=="object"&&"kind"in v?v.kind:void 0;return U(t,"unsupported-syntax",`Unsupported import spec kind: ${String(C)}`)}let i=Ym(r);if(!i.ok)return U(t,"unsupported-syntax",i.message);let s=Se(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(v=>v.type==="ImportDeclaration"&&v.source.value===n),u=new Set(l.flatMap(v=>v.specifiers.flatMap(C=>{let A=qm(v,C);return A?[A]:[]}))),d=i.imports.filter(v=>!u.has(Oc(v)));if(d.length===0)return On(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let p=Gm(c.body),m=d.find(v=>p.has(vi(v)));if(m)return U(t,"unsupported-syntax",`Import local binding already exists: ${vi(m)}`);let E=Wm(d);if(E.reduce((v,C)=>v+C.length,0)!==d.length)return U(t,"unsupported-syntax","Unsupported import specifier grouping");for(let v of E){if(!Fc(Nc(v)))return U(t,"unsupported-syntax","Unsupported import specifier combination");let C=l.find(A=>Jm(A,v));if(C)Xm(C,v);else{let A=Bm(Ac(v),Km(n));Zm(c.body,A),l.push(A)}}return ce(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function Jm(e,t){return e.importKind==="type"?!1:Fc(zm(Hm(e),Nc(t)))}function Xm(e,t){let n=!1,r=new Set(e.specifiers.map(o=>Ci(o)));for(let o of Ac(t)){let i=Ci(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return Mc(e.specifiers),{changed:n}}function Ac(e){let t=e.map(n=>{switch(n.kind){case"named":return $m(n.local?Dn(n.local):Dn(n.imported),Dn(n.imported));case"default":return Vm(Dn(n.local));case"namespace":return Um(Dn(n.local));default:return n}});return Mc(t),t}function Nc(e){let t=Tc();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 Hm(e){let t=Tc();for(let n of e.specifiers)Rc(n)?t.defaultLocals.add(n.local.name):Pc(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Tc(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function zm(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Fc(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function Mc(e){let t=[...e.filter(n=>Rc(n)),...e.filter(n=>Pc(n)),...e.filter(n=>wc(n))];e.splice(0,e.length,...t)}function Wm(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 Ym(e){let t=new Map,n=new Map;for(let r of e){let o=Oc(r);if(t.has(o))continue;let i=vi(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 Gm(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(jm(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 Zm(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 Qm(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 Oc(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 vi(e){return e.kind==="named"?e.local??e.imported:e.local}function qm(e,t){return e.importKind==="type"||wc(t)&&t.importKind==="type"?null:Ci(t)}function Ci(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 mn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!th(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return U(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=Se(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 On(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),ce(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>eh(u,d))),l.specifiers.length===0&&a.body.splice(c,1),ce(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function eh(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 th(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 Ln(e){let{source:t,locator:n,next:r}=e,o=zr(t,n);return o.ok?(o.path.replaceWith(an(r)),ce(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Jr(e){let{source:t,locator:n,index:r,value:o}=e,i=zr(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?U(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?U(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,an(o)),ce(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):U(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function Xr(e){let{source:t,locator:n,index:r}=e,o=zr(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?U(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?U(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),ce(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):U(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function Hr(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=zr(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return U(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return U(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 U(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),ce(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function zr(e,t){let n=Se(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=te(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}}}var rh=typeof Ri=="function"?Ri:Ri.default;function Ai(e){let t=Uc(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Ni(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.containerSourceRange??n.container.sourceRange,i=r.placement;if((n.container.kind==="virtual-route-root"||n.container.kind==="starter-placeholder")&&(n.container.sourceRange===null||n.container.sourceKind==="jsx-element"||n.container.sourceKind==="atomic-expression"||n.container.kind==="starter-placeholder"))return n.container.sourceKind==="atomic-expression"?{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"An indirect page expression does not expose a safe return boundary.",diagnostics:[]}}:{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:i.placementUnitKey,importStep:Dc(e),returnStep:{kind:"insert-return",node:{jsx:`<${e.component.localName} />`},placement:i.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}};if(!o)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition does not expose a safe placement boundary.",diagnostics:[]}};let a={kind:"jsx-node",strategy:"source-range",sourceRange:o},c=dt(e.source,a);if(!c.ok||!c.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:c.ok===!1?c.diagnostic.message:"Route page composition anchor could not be resolved.",diagnostics:c.ok?[]:[Wr(c.diagnostic)]}};let l=Yr(e.source,c.match.node.start??null,c.match.node.end??null);if(sh(o,n.container.sourceRange)&&n.container.sourceHash&&l!==n.container.sourceHash)return{ok:!1,error:{code:"VERSION_STALE",message:"Route page composition container hash no longer matches the current source.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition container hash no longer matches the current source."}]}};let u=Dc(e);return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:r.placement.placementUnitKey,parentLocator:a,importStep:u,insertStep:{kind:"insert-child",parentLocator:a,node:{jsx:`<${e.component.localName} />`},placement:r.placement.relation,...r.placement.anchorSourceRange?{anchorLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:r.placement.anchorSourceRange}}:{}}}}}function Dc(e){let t=ih(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 Bc(e){let t;try{t=Gr.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(i){return{ok:!1,source:e.source,diagnostic:{message:i instanceof Error?i.message:String(i)}}}let n=Gr.parseExpression(e.jsx,{plugins:["jsx","typescript"]}),r=!1;return(typeof Pi=="function"?Pi:Pi.default)(t,{ExportDefaultDeclaration(i){let s=i.get("declaration"),a=oh(i,s);if(a){if(a.isArrowFunctionExpression()&&!a.get("body").isBlockStatement()){let c=a.get("body");c.replaceWith(Lc(c.node,n,e.placement,e.replaceOriginal===!0)),r=!0,i.stop();return}a.traverse({Function(c){c.node!==a.node&&c.skip()},ReturnStatement(c){if(r)return;let l=c.get("argument");l.node&&(l.replaceWith(Lc(l.node,n,e.placement,e.replaceOriginal===!0)),r=!0,c.stop())}}),r&&i.stop()}}}),r?{ok:!0,source:rh(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:"Route default return boundary could not be resolved."}}}function oh(e,t){if(t.isFunctionDeclaration()||t.isFunctionExpression()||t.isArrowFunctionExpression())return t;if(!t.isIdentifier())return null;let n=e.scope.getBinding(t.node.name);if(!n)return null;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression())return r;if(r.isVariableDeclarator()){let o=r.get("init");if(o.isArrowFunctionExpression()||o.isFunctionExpression())return o}return null}function Lc(e,t,n,r){if(bt.isNullLiteral(e)||r)return t;let s=n==="before"||n==="prepend"?[t,e]:[e,t];return bt.jsxFragment(bt.jsxOpeningFragment(),bt.jsxClosingFragment(),s)}function Vc(e){let t=Uc(e);if(t)return{ok:!1,error:t};let n=e.projection;if(n.container.sourceRange===null)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition does not expose a safe placement boundary.",diagnostics:[]}};let r=$c(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:[]}};let i=wi(o.sourceRange),s=dt(e.source,i);if(!s.ok||!s.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:s.ok===!1?s.diagnostic.message:"Route page composition source anchor could not be resolved.",diagnostics:s.ok?[]:[Wr(s.diagnostic)]}};if(Yr(e.source,s.match.node.start??null,s.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:i}}};if(!e.targetPlacement)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit move requires a target placement.",diagnostics:[]}};if(e.targetPlacement.routeId!==e.routeId)return{ok:!1,error:{code:"CROSS_PAGE_MOVE_UNSUPPORTED",message:"Page-unit move across routes is not supported.",diagnostics:[]}};if(e.targetPlacement.documentVersion!==e.expectedDocumentVersion)return{ok:!1,error:{code:"VERSION_STALE",message:"Page-unit target placement belongs to a different document version.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Page-unit target placement belongs to a different document version."}]}};let c=Ni(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!c.ok)return{ok:!1,error:{code:c.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:c.diagnostic.message,diagnostics:[c.diagnostic]}};let l=c.placement;if(l.placementUnitKey!==e.targetPlacement.placementUnitKey||l.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 u=l.containerSourceRange;if(!u||!l.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 d=wi(u),p=dt(e.source,d);if(!p.ok||!p.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:p.ok===!1?p.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:p.ok?[]:[Wr(p.diagnostic)]}};if(Yr(e.source,p.match.node.start??null,p.match.node.end??null)!==l.containerSourceHash)return jc("Route page composition target container hash no longer matches the current source.");if(l.relation==="before"||l.relation==="after"){let E=l.anchorSourceRange,b=l.anchorSourceHash;if(!E||!b)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let v=wi(E),C=dt(e.source,v);return!C.ok||!C.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:C.ok===!1?C.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:C.ok?[]:[Wr(C.diagnostic)]}}:Yr(e.source,C.match.node.start??null,C.match.node.end??null)!==b?jc("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:i,targetParentLocator:d,anchorLocator:v,placement:l.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:i,targetParentLocator:d,placement:l.relation}}}}function jc(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Wr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Uc(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.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 ih(e,t){let n=_c.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=_c.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function wi(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Yr(e,t,n){return t==null||n==null?null:`sha256:${nh("sha256").update(e.slice(t,n)).digest("hex")}`}function sh(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 ah=typeof Ti=="function"?Ti:Ti.default;function Jc(e){if(!e.ast)return ot(e,[Ae("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=hh(e.ast);if(!t)return ot(e,[Ae("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=yh(t);if(n.length===0)return ot(e,[Ae("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")]);if(n.length>1)return ot(e,[Ae("MULTIPLE_PAGE_RETURNS","Route default export contains multiple page-level return statements",{returnCount:n.length})]);let r=xh(n[0].argument);if(!r)return ot(e,[Ae("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})]);if(r.isNullLiteral())return Kc(e,t,"virtual-route-root");if(Eh(r,t))return ot(e,[Ae("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(Sh(r,t)||bh(r)&&!e.source.includes("DESIGN_PLAN_REPLACE_ME"))return ot(e,[Ae("UNSUPPORTED_PAGE_SHAPE","Route default export shape does not provide a single safe placement boundary",{reason:"ambiguous-placement"})]);if(r.isJSXFragment()){let i=kt(r);if(i.unsupported)return ot(e,[Ae("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=Fi({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-fragment",source:e.source,containerPath:r,members:i.members});return Zr(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-fragment"})}if(r.isJSXElement()&&!hn(r)){let i=_i(r),s=Fi({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[i]});return Zr(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-element"})}if(r.isJSXElement()){let i=kt(r);if(i.unsupported)return ot(e,[Ae("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=i.members;if(kh(e.source,r,s))return Kc(e,t,"starter-placeholder");let a=Fi({input:e,containerKind:"jsx-container",sourceKind:"jsx-element",source:e.source,containerPath:r,members:s});return Zr(e,t,a,{kind:"jsx-container",sourceKind:"jsx-element"})}if(Ih(r))return ot(e,[Ae("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let o=Ch({input:e,source:e.source,expression:r});return Zr(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"})}function Ni(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ae("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:Ae("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function $c(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ae("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:Ae("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Xc(e){return e.ok?ch(e.projection):lh(e.projection)}function ch(e){let t=new Map,n=[];for(let l of e.placements)l.members.length===0&&e.placements.length>1||l.members.length>0&&!l.anchorSourceRange||t.has(l.placementUnitKey)||t.set(l.placementUnitKey,l);let r=new Map,o=new Map;for(let[l,u]of t){let d=u.members.flatMap((b,v)=>Hc(e,u,b,v,e.container.placementKey)),p=d.filter(({member:b})=>b.isBusinessMember).map(({sourceMember:b})=>dh(l,b,u.independent)),m=d.length>0?d:[{sourceMember:{key:`source:${l}:empty`,kind:e.container.kind==="starter-placeholder"?"starter-placeholder":"null-return",containerKey:e.container.placementKey,label:"empty-page",sourceFile:e.entryFile,isAtomic:!0},member:null}];r.set(l,m.map(({sourceMember:b})=>b)),o.set(l,p);let E=m[0]?.sourceMember.key??l;n.push({key:l,containerKey:E,businessMemberKeys:p.map(b=>b.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,routeId:e.route,placementUnitKey:l.placementUnitKey,relation:l.relation}));return{status:"supported",version:e.version,routeId:e.route,container:uh(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function lh(e){let t=e.diagnostics.map(fh);return{status:"unsupported",version:e.version,routeId:e.route,reason:ph(e.diagnostics),diagnostics:t}}function uh(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 Hc(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)=>Hc(e,t,a,c,i))]}function dh(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function fh(e){return{code:mh(e),message:e.message}}function ph(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 mh(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 hh(e){let t=null;return ah(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=gh(o.path);i&&(t=i,n.stop())}}),t}function gh(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 yh(e){if(e.isArrowFunctionExpression()){let r=e.get("body");if(!r.isBlockStatement())return[{argument:r}]}let t=e.get("body");if(!t.isBlockStatement())return[];let n=[];return t.traverse({Function(r){r.node!==e.node&&r.skip()},ReturnStatement(r){n.push({argument:r.get("argument")})}}),n}function xh(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 Eh(e,t){if(e.isIdentifier())return Qr(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Qr(n.node.name,t)}return!1}function Sh(e,t){return e.isConditionalExpression()?It(e.get("consequent"),t)||It(e.get("alternate"),t):e.isLogicalExpression()?It(e.get("left"),t)||It(e.get("right"),t):!1}function bh(e){if(!e.isJSXElement()||!hn(e))return!1;let t=kt(e).members;if(t.length!==1)return!1;let n=t[0];return n.kind==="jsx-element"&&!n.isBusinessMember&&n.businessMemberCount>0}function It(e,t){if(e.isIdentifier())return Qr(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Qr(n.node.name,t)}return e.isConditionalExpression()?It(e.get("consequent"),t)||It(e.get("alternate"),t):e.isLogicalExpression()?It(e.get("left"),t)||It(e.get("right"),t):!1}function Qr(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 Ih(e){return e.isJSXSpreadChild()}function kh(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Oi(t)}function Oi(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(!Oi(t))return!1;continue}if(t.isJSXElement()&&!Oi(t))return!1}return!0}function kt(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Di(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:ze(r.node.loc),businessMemberCount:0,parentSourceRange:ze(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=kt(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=hn(o)?kt(o):null;n||=i?.unsupported??!1,t.push({..._i(o,i?.members),sourceRange:ze(r.node.loc),parentSourceRange:ze(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Di(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:ze(r.node.loc),businessMemberCount:1,parentSourceRange:ze(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&zc(r)){let o=kt(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=hn(r)?kt(r):null;n||=o?.unsupported??!1,t.push({..._i(r,o?.members),parentSourceRange:ze(e.node.loc)})}}return{members:t,unsupported:n}}function _i(e,t){let n=e.isJSXElement()&&hn(e)?t??kt(e).members:[],r=e.isJSXElement()&&!hn(e)&&!zc(e);return{memberKey:Di(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:ze(e.node.loc),businessMemberCount:r?1:Wc(n),parentSourceRange:ze(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:vh(e)}}function zc(e){if(e.isJSXFragment())return!0;let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name==="Fragment"||t.type==="JSXMemberExpression"&&t.object.type==="JSXIdentifier"&&t.object.name==="React"&&t.property.name==="Fragment"}function hn(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name!=="Fragment"&&t.name[0]===t.name[0]?.toLowerCase()}function vh(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 Wc(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function qr(e){return e.length===0?0:Math.max(1,Wc(e))}function Fi(e){let t=ze(e.containerPath.node.loc),n=Gc(e.source,e.containerPath.node.start,e.containerPath.node.end),r=Ve(e.input,e.containerKind,e.sourceKind,t),o=Ve(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:qr(e.members)<=1,memberCount:qr(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function Ch(e){let t=ze(e.expression.node.loc),n=Gc(e.source,e.expression.node.start,e.expression.node.end),r=Ve(e.input,"virtual-route-root","atomic-expression",t),o=Ve(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:Ve(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 Zr(e,t,n,r){let o=n.containerSourceRange??n.sourceRange,i=Rh(e,n,o),s=fi(i),a={status:"supported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Zc(t),container:{kind:r.kind,placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,version:e.version,isEmptyPage:n.memberCount===0,sourceKind:r.sourceKind,sourceRange:o,sourceHash:n.sourceHash},placements:i,diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map};return Object.defineProperties(a,{placementByKey:{value:s.placementByKey,enumerable:!1},unitByKey:{value:s.unitByKey,enumerable:!1},placementsByUnitKey:{value:s.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:s.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:a}}function Rh(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,p,m,E,b=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:qr(E)<=1,memberCount:qr(E),sourceRange:p,sourceHash:p?Mi(e.source,p):null,relation:l,containerSourceRange:b,containerSourceHash:b?Mi(e.source,b):null,anchorSourceRange:m,anchorSourceHash:m?Mi(e.source,m):null,members:E}),i=t.placementKey,s=t.members.map(l=>Ve(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",Ve(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=Ve(e,i,"placement-unit",l.sourceRange);r.push(o("before",Ve(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",Ve(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function Kc(e,t,n){let r=Ve(e,n,"empty-container",void 0),o=Ve(e,n,"empty-unit",void 0),i={placementKey:r,placementUnitKey:o,version:e.version,containerKey:r,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},s=fi([i]),a={status:"supported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Zc(t),container:{kind:n,placementKey:r,placementUnitKey:o,version:e.version,isEmptyPage:!0,sourceKind:n==="starter-placeholder"?"starter-placeholder":"jsx-fragment",sourceRange:null,sourceHash:null},placements:[i],diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map};return Object.defineProperties(a,{placementByKey:{value:s.placementByKey,enumerable:!1},unitByKey:{value:s.unitByKey,enumerable:!1},placementsByUnitKey:{value:s.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:s.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:a}}function ot(e,t){return{ok:!1,projection:{status:"unsupported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,diagnostics:t}}}function Ae(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function Ve(e,t,n,r){return Yc([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Di(e,t,n){return Yc(["member",e,String(t??-1),String(n??-1)])}function Yc(e){return`pc_${Li("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Gc(e,t,n){return t==null||n==null?null:`sha256:${Li("sha256").update(e.slice(t,n)).digest("hex")}`}function Mi(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:${Li("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function ze(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Zc(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}function wh(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var Ah=160;function Qc(e,t,n,r={}){let o=[];for(let[i,s]of e.elements){let a=n.get(i),c={canUpdateText:r.canUpdateTextByKey?.get(i)??a?.canUpdateText??!1,canInsertChild:a?.canInsertChild??!1,canMove:a?.canMove??!1,canRemove:a?.canRemove??!1};o.push({key:i,tag:s.tag,label:s.tag===s.componentName?s.tag:`${s.tag} (${s.componentName})`,parentKey:s.parentKey,childKeys:[...s.childKeys],operationSummary:c,...r.dynamicDataSummaryByKey?.get(i)?{dynamicDataSummary:r.dynamicDataSummaryByKey.get(i)}:{}})}return{routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:o}}function qc(e,t,n,r,o,i,s,a,c,l,u,d,p){let m=t.elements.get(e),E=n.nodes.get(e),b=r.get(e);if(!m||!E||!b)throw new Error(`Node not found: ${e}`);let v=ol(m.textSegments,s),C=il(e,t,m,b,v),A=v?Fh(v):void 0,N=Mh(i,v),G=m.textSegments.map(_=>({index:_.index,value:_.value,editable:sl(_,b,s?.get(_.index)??null),source:o.get(_.index)??null})),fe=nl(m,t),ue=m.childKeys.map(_=>{let D=t.elements.get(_);return D?{key:_,tag:D.tag,label:D.tag}:null}).filter(_=>_!==null),R=[];if(m.parentKey){let _=t.elements.get(m.parentKey);if(_)for(let D of _.childKeys){if(D===e)continue;let L=t.elements.get(D);L&&R.push({key:D,tag:L.tag,label:L.tag})}}return{key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:tl(m),label:m.tag,capabilities:C,writeTarget:i,effectiveWriteTarget:N,provenanceChain:A,componentSemantic:c,contentModel:l,mediaModel:u,styleSource:d,conditional:a,...p?{dynamicData:p}:{},textSegments:G,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:fe,children:ue,siblings:R}}function el(e,t,n,r,o,i,s){let a=t.elements.get(e),c=n.nodes.get(e),l=r.get(e);if(!a||!c||!l)throw new Error(`Node not found: ${e}`);let u=ol(a.textSegments,i);return{key:e,tag:a.tag,componentName:a.componentName,sourceFile:a.sourceFile,sourceLocator:tl(a),label:a.tag,capabilities:il(e,t,a,l,u),provenanceChain:u?{editMode:u.editMode,diagnostics:u.diagnostics.map(d=>({code:d.code,message:d.message}))}:void 0,...s?{dynamicData:s}:{},textSegments:a.textSegments.map(d=>{let p=o.get(d.index);return{index:d.index,editable:sl(d,l,i?.get(d.index)??null),source:p?{kind:p.kind}:null}}),boundaryKind:a.boundaryKind,isOpaque:a.isOpaque,ancestors:nl(a,t)}}function tl(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:Nh(e.sourceRange),structuralPath:e.identity.structuralPath,...Th(e.textSegments)}}function nl(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 Nh(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Th(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,Ah)}:{}}function rl(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 ol(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function il(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&&al(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 sl(e,t,n){return!e.editable||!t.canUpdateText?!1:n?al(n.editMode):!0}function al(e){return e==="direct"||e==="proxy"||e==="upstream"}function Fh(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 Mh(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}:wh(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}}function cl(e){let{key:t,element:n,graph:r,provenances:o}=e,i=_h(t,n,r),s=i?.tag??(Ut(n.tag)?n.tag:n.componentName),a=i?.identity.key??ll(n,r)??t,c=jh(i),l=Bh(t,n,r,o,i),u=Oh(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:Lh(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:u,impactScope:Vh(u),alternativeStrategies:Uh(u)}}function Oh(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return ji(e,n)?"instance":!Ut(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function ll(e,t){if(Ut(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&Dh(r,e.componentName));return n.length!==1?null:n[0].identity.key}function _h(e,t,n){if(Ut(t.tag))return t;let r=ji(e,n);if(r)return r;let o=ll(t,n);return o?n.elements.get(o)??null:null}function Dh(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function Lh(e,t){return Ut(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function jh(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 Bh(e,t,n,r,o){let i=new Set,s=ji(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&&Ut(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function ji(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Ut(r.tag))return r;n=r.parentKey}return null}function Ut(e){return/^[A-Z]/.test(e)}function Vh(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function Uh(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}var $h=new Set(["markdown","body","content","value","document"]),ul=[];function fl(e){if(!(!Xh(e.tag)||!e.attributes))for(let t of e.attributes){if(!$h.has(t.name))continue;if(Jh(t))return{kind:"markdown",field:t.name,schema:"markdown",valuePath:t.source?.expression,operationBoundary:ul};let n=Kh(t.resolvedValue);if(n==="prosemirror-doc"||n==="node-array")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:n,operationBoundary:ul};if(n==="unsupported-json-tree")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:"unsupported-json-tree",operationBoundary:[],diagnostics:[{code:"unsupported-schema",field:t.name,message:'Only top-level node arrays and { type: "doc", content: [] } rich-text JSON are editable in stage D'}]}}}function Kh(e){if(e){if(Array.isArray(e)&&e.every(t=>dl(t)))return"node-array";if(dl(e)){if(e.type==="doc"&&Array.isArray(e.content))return"prosemirror-doc";if(Array.isArray(e.content)||Array.isArray(e.children))return"unsupported-json-tree"}}}function dl(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null}function Jh(e){return e.name==="markdown"}function Xh(e){return/^[A-Z]/.test(e)}var Hh=["src","alt","poster","caption","width","height"];function pl(e){let t=e.attributes?.filter(i=>Hh.includes(i.name))??[];if(t.length===0)return;let n=t.map(i=>i.name),r=Object.fromEntries(t.filter(i=>i.source?.expression).map(i=>[i.name,i.source.expression])),o=Wh(t.map(i=>i.value));return{kind:zh(e.tag,n),sourceType:o,fields:n,editableFields:[],operationBoundary:[],...Object.keys(r).length>0?{valuePaths:r}:{}}}function zh(e,t){return e==="img"?"image":e==="video"||t.includes("poster")?"video":"media"}function Wh(e){return e.some(t=>t.startsWith("cms:"))?"cms-media-field":e.some(t=>/^(\.?\/|\/)/.test(t))?"local-file-reference":"asset-id"}var Bi=["set-class-name-source","apply-style-draft"];function ml(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Bi,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element"}]};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:Bi,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Bi}}import{createHash as Yh}from"node:crypto";var jn=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function ae(e){return`sha256:${Yh("sha256").update(e).digest("hex")}`}function yl(e){let t=e.route.graph.elements.get(e.key);if(!t)return{key:e.key,routeId:e.route.routeId,filePath:"",componentName:"",sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ae(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Gh(e.route.source,t);if(!n)return{key:e.key,routeId:e.route.routeId,filePath:t.sourceFile,componentName:t.componentName,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ae(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(c=>c.type==="JSXAttribute"&&c.name.type==="JSXIdentifier"&&c.name.name==="className"),i={key:e.key,routeId:e.route.routeId,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:gl(r),version:{documentVersion:e.route.graph.version,contentHash:ae(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:hl(e.route.source,o),valueRaw:s?hl(e.route.source,s):null,attrRange:gl(o),diagnostics:[]}}function xl(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 Gh(e,t){let n=rt({source:e,profile:Dt({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=te(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Zh(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function El(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 hl(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function gl(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 Zh(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}import*as ns from"@babel/parser";import Ji from"@babel/traverse";import*as x from"@babel/types";import*as mt from"node:path";import*as vl from"@babel/parser";import $i from"@babel/traverse";import*as gn from"@babel/types";import*as H from"@babel/types";function no(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?eo(n,t):null}if(e.isMemberExpression()){let n=rg(e.node),r=Qh(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?eo(o,[...r,...t]):null}return e.isAwaitExpression()||Ui(e.node)?vt(ig(e.node),t,"awaited or fetched expression"):null}function Qh(e){let t=[],n=e;for(;H.isMemberExpression(n);){if(n.computed)if(H.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(H.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(H.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return H.isIdentifier(n)?t:null}function eo(e,t=[]){let n=qh(e,t);if(n)return n;let r=eg(e,t);if(r)return r;let o=tg(e,t);return o||null}function Vn(e){return e?.kind==="api-source"}function qh(e,t){if(e.path.isVariableDeclarator()&&H.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Vi(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return vt(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&H.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>H.isObjectProperty(c)&&Il(c)==="data"&&Bn(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Vi(a.node))return vt(e.identifier.name,t,"query hook data binding")}let n=ng(e);if(!n||Il(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()||!Vi(i.node)?null:vt(e.identifier.name,t,"query hook data binding")}function eg(e,t){if(e.path.isVariableDeclarator()&&H.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!bl(a.node))return null;let[c,l]=e.path.node.id.elements;return!H.isIdentifier(c)||c.name!==e.identifier.name||!H.isIdentifier(l)?null:Sl(e,l.name)?vt(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()||!bl(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return H.isIdentifier(s)&&Sl(e,s.name)?vt(e.identifier.name,t,"state setter is updated by API data"):null}function tg(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()?vt(e.identifier.name,t,"awaited binding result"):Ui(r.node)?vt(e.identifier.name,t,"fetch-backed binding result"):null:null}function ng(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 Bn(e,t){return H.isIdentifier(e)?e.name===t:H.isAssignmentPattern(e)?Bn(e.left,t):H.isObjectPattern(e)?e.properties.some(n=>H.isObjectProperty(n)?Bn(n.value,t):Bn(n.argument,t)):H.isArrayPattern(e)?e.elements.some(n=>!!n&&Bn(H.isRestElement(n)?n.argument:n,t)):!1}function Sl(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Ui(i.node)&&(n=!0),(og(i.node.callee,t)||i.node.arguments.some(s=>H.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function Vi(e){let t=ro(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function bl(e){return ro(e.callee)==="useState"}function Ui(e){return to(e,t=>H.isCallExpression(t)&&ro(t.callee)==="fetch")}function rg(e){let t=e;for(;H.isMemberExpression(t);)t=t.object;return H.isIdentifier(t)?t.name:null}function Il(e){return e.computed?null:H.isIdentifier(e.key)?e.key.name:H.isStringLiteral(e.key)?e.key.value:null}function ro(e){return H.isIdentifier(e)?e.name:H.isMemberExpression(e)&&H.isIdentifier(e.property)?e.property.name:null}function og(e,t){return to(e,n=>H.isIdentifier(n)&&n.name===t)}function to(e,t){if(t(e))return!0;let n=H.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(H.isNode(i)&&to(i,t))return!0;continue}if(H.isNode(o)&&to(o,t))return!0}return!1}function ig(e){return H.isIdentifier(e)?e.name:H.isCallExpression(e)?ro(e.callee)??"api":H.isAwaitExpression(e)?"awaited-api":"api"}function vt(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:sg(e,t),reason:n}}function sg(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Cl=typeof $i=="function"?$i:$i.default;function Rl(e,t){let n=wl(e);if(!n)return{allowed:!0};let r=!1;return Cl(n,{CallExpression(o){if(!Al(o.node,t.sourceRange)||!ag(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||Vn(no(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Pl(e,t){let n=wl(e);if(!n)return{allowed:!0};let r=!1;return Cl(n,{JSXExpressionContainer(o){Al(o.node,t.sourceRange)&&(gn.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 wl(e){try{return vl.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ag(e){let t=e.callee;return gn.isMemberExpression(t)&&gn.isIdentifier(t.property)&&t.property.name==="map"}function Al(e,t){let n=e.loc;return n?kl({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&kl({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function kl(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}import*as ne from"@babel/types";function Nl(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 it(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return $t(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(ne.isObjectPattern(n)||ne.isArrayPattern(n))return $t(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(lg(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function $t(e,t,n=!1){return ne.isIdentifier(e)?e.name===t&&n:ne.isObjectPattern(e)?e.properties.some(r=>ne.isObjectProperty(r)?$t(r.value,t,n):$t(r.argument,t,n)):ne.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=ne.isRestElement(r)?r.argument:r;return $t(o,t,n)}):ne.isAssignmentPattern(e)?$t(e.left,t,!0):ne.isRestElement(e)?$t(e.argument,t,n):!1}function yn(e,t){if(e.path.isObjectPattern()){if(t){let r=We(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:it(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:it(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Tl(r),i=!1,s=o?o.initBinding&&Ki(o.initBinding)?(i=it(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=yn(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=We(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||it(e)}}}}let n=fg(e);if(n){let r=cg(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||it(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=ug(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:it(e)}}let i=Un(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:it(e)}:null}if(Ki(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:it(e)}}return null}function cg(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=Tl(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Ki(i)?(a=it(i),[...s]):(()=>{let u=yn(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=We(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||it(t)}:null}function Tl(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=pg(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Ki(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function lg(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function ug(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=We(i.node,t);if(a)return a}return null}function Fl(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=oo(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=Un(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=dg(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=Un(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 oo(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=Un(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&We(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=oo(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=oo(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=oo(r,t);if(o)return o}}return null}function We(e,t,n=[]){if(ne.isIdentifier(e))return e.name===t?n:null;if(ne.isObjectPattern(e)){for(let r of e.properties)if(ne.isObjectProperty(r)){let o=Un(r);if(!o)continue;let i=We(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(ne.isRestElement(r)){let o=We(r.argument,t,n);if(o)return o}}if(ne.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=ne.isRestElement(o)?o.argument:o,s=We(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return ne.isAssignmentPattern(e)?We(e.left,t,n):null}function dg(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function fg(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 Un(e){return e.computed?null:ne.isIdentifier(e.key)?e.key.name:ne.isStringLiteral(e.key)?e.key.value:null}function pg(e){let t=[],n=e;for(;ne.isMemberExpression(n);){if(n.computed)if(ne.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ne.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ne.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ne.isIdentifier(n)?{base:n.name,path:t}:null}var At=typeof Ji=="function"?Ji:Ji.default;function le(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 xn(e){return{file:e.file,component:e.component}}function mg(e){return e.target.kind==="node"?e.target.key:null}function hg(e){return"kind"in e}function io(e){return!hg(e)}function Gi(e,t){let n=mt.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=mt.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Xi(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=dt(n,le(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function rs(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 Ue(e){try{return ns.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function gg(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function yg(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 ie(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Xt(e,t){let n=ie(e);return!!(n&&Ye(t,n))}function Ye(e,t){return t.start>=e.start&&t.end<=e.end}function Wl(e){if(x.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(x.isJSXMemberExpression(e)){let t=e;for(;x.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function xg(e,t){let n=ie(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);if(!a||Xt(a.path.node,n))return;t.scope.getBinding(i)!==a&&r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Wl(i.node.name);s&&o(s,i)}}),[...r].sort()}function Ml(e,t,n){let r=Ue(e);if(!r)return{ok:!0};let o=te(r,le(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=te(r,le(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};if(lu(o.match.path,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let s=xg(o.match.path,i.match.path);return s.length>0?{ok:!1,bindingNames:s}:{ok:!0}}function Ol(e,t,n){let r=Ct(t,n);return r?pt(e,r):null}function Ct(e,t){let n=te(e,le(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:ts(e,t)}function pt(e,t){let n=t.findParent(b=>b.isArrowFunctionExpression()||b.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(b=>b===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"),d=lo(e,u.node),p=r.node.params.map(b=>lo(e,b)),m=ie(i.node),E=ie(r.node);return!d||p.some(b=>b.length===0)||!m||!E?null:{callStart:m.start,callEnd:m.end,callbackStart:E.start,callbackEnd:E.end,collectionExpression:d,callbackParams:p,mapOperator:x.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:as(u.node),callbackPath:r,collectionPath:u}}function lo(e,t){let n=ie(t);return n?e.slice(n.start,n.end):""}function so(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function Eg(e,t){let n=ie(e.node);return n?Sg(t).some(r=>{let o=ie(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function Sg(e){let t=e.callbackPath.node.body;return x.isBlockStatement(t)?Rt(t.body):wt(t)}function Rt(e){let t=[];for(let n of e){if(x.isReturnStatement(n)){n.argument&&t.push(...wt(n.argument));continue}if(x.isBlockStatement(n)){t.push(...Rt(n.body));continue}if(x.isIfStatement(n)){let r=x.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...Rt(r)),n.alternate){let o=x.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...Rt(o))}continue}if(x.isSwitchStatement(n)){for(let r of n.cases)t.push(...Rt(r.consequent));continue}x.isTryStatement(n)&&(t.push(...Rt(n.block.body)),n.handler&&t.push(...Rt(n.handler.body.body)),n.finalizer&&t.push(...Rt(n.finalizer.body)))}return t}function wt(e){return x.isJSXElement(e)?bg(e)?_l(e.children):[e]:x.isJSXFragment(e)?_l(e.children):x.isParenthesizedExpression(e)||x.isTSAsExpression(e)||x.isTSSatisfiesExpression(e)||x.isTSNonNullExpression(e)||x.isTSTypeAssertion(e)?wt(e.expression):x.isConditionalExpression(e)?[...wt(e.consequent),...wt(e.alternate)]:x.isLogicalExpression(e)&&du(e.operator)?wt(e.right):[]}function _l(e){return e.flatMap(t=>x.isJSXElement(t)||x.isJSXFragment(t)?wt(t):x.isJSXExpressionContainer(t)&&(x.isJSXElement(t.expression)||x.isJSXFragment(t.expression)||x.isConditionalExpression(t.expression)||x.isLogicalExpression(t.expression))?wt(t.expression):[])}function bg(e){let t=e.openingElement.name;return x.isJSXIdentifier(t)?t.name==="Fragment":x.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Ig(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Hi(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function Dl(e,t,n,r={}){if(!r.preserveConditionalBoundary&&lu(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=ie(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>ss(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);if(!u||Xt(u.path.node,o)||i.has(u.path.node))return;t.scope.getBinding(c)!==u&&s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Wl(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Ll(e,t,n){let r=ie(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>ss(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return os(e,s=>{let a=s.scope.getBinding(s.node.name);if(!a||Xt(a.path.node,r)||o.has(a.path.node))return;t.scope.getBinding(s.node.name)!==a&&i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function kg(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>ss(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);if(!l||n.has(l.path.node))return;t.scope.getBinding(a)!==l&&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(x.isIdentifier(l))o(l.name,c);else{let u=vg(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function vg(e){let t=e;for(;x.isTSQualifiedName(t);)t=t.left;return x.isIdentifier(t)?t.name:null}function Yl(e,t){let n=ie(e.node),r=new Set;return os(e,o=>{let i=o.scope.getBinding(o.node.name);if(!i||n&&Xt(i.path.node,n))return;t.scope.getBinding(o.node.name)!==i&&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 os(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Cg(e){let t=Rg(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=fu(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=Bg({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=cu(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?as(o):!0}}}function Rg(e,t,n){let r=Ql(e,t);if(ql(e,r),eu(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 At(e,{JSXElement(s){su(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:is(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 Pg(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=>Kn(a.file)));if(!t.has(Kn(e.sourceFile))||!t.has(Kn(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(Kn(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=Tg(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=wg(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Gl({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!Ge(s.file,e.targetFile)||is(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}}function wg(e,t){let n=new Map,r=i=>{let s=En(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 Ag(i,n))o=r(s)||o}return[...n.values()]}function Ag(e,t){let n=[],r=Ng(e,t);for(let o of e.ast.program.body){if(x.isExportDefaultDeclaration(o)&&x.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=Xn(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(x.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Hn(e.file,o.source.value);for(let s of o.specifiers){if(x.isExportNamespaceSpecifier(s)){let l=Pt(s.exported);for(let u of t.values())Ge(u.file,i)&&n.push({file:e.file,namespace:Zi(l,u.namespace),exportName:u.exportName});continue}if(!x.isExportSpecifier(s))continue;let a=Pt(s.local),c=[...t.values()].filter(l=>Ge(l.file,i)&&Kt(l.namespace,a));if(c.length>0){let l=Pt(s.exported);for(let u of c){let d=Xn(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(En({file:i,exportName:a}))&&n.push({file:e.file,exportName:Pt(s.exported)})}continue}if(x.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!x.isExportSpecifier(i))continue;let s=Pt(i.local),a=r.get(s)??[];if(a.length>0){let c=Pt(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=Xn(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(x.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Hn(e.file,o.source.value),s=o.exported;if(s){let a=Pt(s);for(let c of t.values())Ge(c.file,i)&&n.push({file:e.file,namespace:Zi(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())Ge(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Zi(e,t){return t?`${e}.${t}`:e}function Kt(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Xn(e,t,n){return!Kt(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function Ng(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(!x.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Hn(e.file,i.source.value);for(let a of i.specifiers){if(x.isImportDefaultSpecifier(a)){let c=t.get(En({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>Ge(u.file,s)&&Kt(u.namespace,"default"));for(let u of l){let d=Xn(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(x.isImportSpecifier(a)){let c=Pt(a.imported),l=[...t.values()].filter(d=>Ge(d.file,s)&&Kt(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(En({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(x.isImportNamespaceSpecifier(a))for(let c of t.values())Ge(c.file,s)&&r(a.local.name,{...c,namespace:Zi(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(x.isVariableDeclaration(i))for(let s of i.declarations){if(!x.isIdentifier(s.id)||!s.init)continue;let a=Sn(s.init);if(!a||!x.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(En));for(let d of c){let p=Xn(d.namespace,a.name,s.id.name),m=p?{...d,namespace:p}:d,E=En(m);u.has(E)||(r(s.id.name,m),u.add(E),o=!0)}}}return n}function En(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${qi(e.file)}#${t}`}function Pt(e){return x.isIdentifier(e)?e.name:e.value}function Tg(e,t){for(let n of e.program.body){if(x.isExportDefaultDeclaration(n)){let o=n.declaration;if((x.isFunctionDeclaration(o)||x.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(x.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!x.isExportNamedDeclaration(n))continue;let r=n.declaration;if((x.isFunctionDeclaration(r)||x.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(x.isVariableDeclaration(r)){for(let o of r.declarations)if(x.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!x.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:x.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Gl(e){let t=Fg(e),n=[],r=eu(e.ast,t);return At(e.ast,{JSXElement(o){Ge(e.file,e.sourceFile)&&is(o)===e.sourceComponent||su(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Zl(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Ql(e,t){let n=Zl();return At(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function Fg(e){let t=Zl();return Ge(e.file,e.sourceFile)&&Mg(t,Ql(e.ast,e.sourceComponent)),At(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Hn(e.file,o),s=e.componentIdentities.filter(a=>Ge(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(x.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),x.isImportDefaultSpecifier(a)){let l=s.filter(u=>Kt(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let p=Bl(d,"default");p&&u.add(p)}t.namespaceMembers.set(c,u)}continue}if(x.isImportSpecifier(a)){let l=x.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>Kt(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let p of u){let m=Bl(p,l);m&&d.add(m)}t.namespaceMembers.set(c,d);continue}s.some(d=>!d.namespace&&d.exportName===l)&&t.localBindings.add(c);continue}if(x.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,d=t.namespaceMembers.get(c)??new Set;d.add(u),t.namespaceMembers.set(c,d)}}}}}),ql(e.ast,t),t}function Mg(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 ql(e,t){At(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Sn(n.node.init);if(r){if(x.isIdentifier(n.node.id)){let o=Jt(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Qi(t,i,o);return}if(x.isObjectPattern(n.node.id)){let o=Jt(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&ru(n.node.id,o.namespaceMembers,t,n)}}}})}function eu(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return At(e,{ReferencedIdentifier(r){if(n){r.stop();return}Og(r)||!r.isIdentifier()||!tu(r,t)||_g(r,t)||Dg(r)||(n=!0,r.stop())}}),n}function Og(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 tu(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)&&Jt(r.node,t,r)?r:null}function _g(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!jl(e,r))return!1;let o=tu(e,t);if(!o)return!1;if(Sn(r.node)===o.node)return!!Jt(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&jl(e,a)&&!!Jt(a.node,t,a)}function Dg(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function jl(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Jt(e,t,n){let r=Sn(e);if(!r)return null;if(x.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(x.isObjectExpression(r))return Lg(r,t,n);let o=iu(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?nu(s,o.slice(1).join(".")):null}function Lg(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!x.isObjectProperty(i))continue;let s=ou(i);if(!s||!x.isExpression(i.value)){x.isExpression(i.value)&&(o||=Jt(i.value,t,n)!==null);continue}let a=Jt(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 nu(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 Qi(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 ru(e,t,n,r){for(let o of e.properties){if(x.isRestElement(o)){if(x.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Qi(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!x.isObjectProperty(o))continue;let i=ou(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=nu(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=x.isAssignmentPattern(o.value)?o.value.left:o.value;if(x.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Qi(n,c,s);continue}if(x.isObjectPattern(a)&&s.namespaceMembers.size>0){ru(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function ou(e){return e.computed?x.isStringLiteral(e.key)||x.isNumericLiteral(e.key)?String(e.key.value):null:jg(e.key)}function jg(e){return x.isIdentifier(e)?e.name:x.isStringLiteral(e)||x.isNumericLiteral(e)?String(e.value):null}function Sn(e){return x.isParenthesizedExpression(e)||x.isTSAsExpression(e)||x.isTSSatisfiesExpression(e)||x.isTSNonNullExpression(e)||x.isTSTypeAssertion(e)?Sn(e.expression):x.isExpression(e)?e:null}function iu(e){if(x.isIdentifier(e))return[e.name];if((x.isMemberExpression(e)||x.isOptionalMemberExpression(e))&&!e.computed&&x.isIdentifier(e.property)){let t=Sn(e.object),n=t?iu(t):null;return n?[...n,e.property.name]:null}return null}function Bl(e,t){if(!Kt(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 su(e,t){let n=e.node.openingElement.name;if(x.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=au(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 au(e){if(x.isJSXIdentifier(e))return[e.name];if(x.isJSXMemberExpression(e)){let t=au(e.object);return t?[...t,e.property.name]:null}return null}function is(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()&&x.isIdentifier(n.node.id))return n.node.id.name}return null}function Bg(e){let t=ie(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||Xt(a.path.node,t))return;let c=$g(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 u=Jg(e.callSitePath,c.propName,e.source);if(!u.ok){o=u.reason;return}let d=Vg(u.expression,c.remainingPath);if(!d){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let p=Yl(u.expressionPath,e.targetParentPath);if(!p.ok){o=p.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${p.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:d});return}e.targetParentPath.scope.getBinding(s.node.name)!==a&&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:Xg(e.source,t,[...n.values()])}}function Vg(e,t){if(t.length===0)return e;let n=cu(e);if(!n)return null;let r=as(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=Ug(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function Ug(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function $g(e,t,n){let r=Kg(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=yn(t,o);if(!i)return null;let s=r?.range??ie(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function Kg(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Xt(n.node,t)||n.node.computed||!x.isIdentifier(n.node.property))return null;let r=ie(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Jg(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()&&x.isJSXIdentifier(c.node.name)&&c.node.name.name===t);if(!o?.isJSXAttribute())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not passed explicitly`};let i=o.get("value");if(!i.isJSXExpressionContainer())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not an expression`};let s=i.get("expression");if(!s.isExpression())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not a usable expression`};let a=lo(n,s.node);return a?{ok:!0,expression:a,expressionPath:s}:{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' cannot be read`}}function Xg(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 cu(e){try{let n=ns.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=x.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&x.isExpression(r)?r:null}catch{return null}}function Hg(e){let t=ie(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||Xt(s.path.node,t))return;let a=Vl(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=Vl(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!zg(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 os(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 zg(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 Vl(e,t,n){let r=Wg(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Hn(t,i),a=i.startsWith(".")?Gi(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=x.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 Wg(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Hn(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?mt.normalize(mt.join(mt.dirname(e),t)).replace(/\\/g,"/"):t}function Ge(e,t){return qi(e)===qi(t)}function qi(e){let t=Kn(e);return t.endsWith("/index")?t.slice(0,-6):t}function Kn(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function ss(e){let t=[],n=r=>{if(r){if(x.isIdentifier(r)){t.push(r.name);return}if(x.isObjectPattern(r)){for(let o of r.properties){if(x.isRestElement(o)){n(o.argument);continue}x.isObjectProperty(o)&&n(o.value)}return}if(x.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(x.isAssignmentPattern(r)){n(r.left);return}if(x.isRestElement(r)){n(r.argument);return}x.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Yg(e){let t=[];for(let n of e.callbackPath.node.params){if(x.isIdentifier(n)){t.push(n.name);continue}if(x.isRestElement(n)&&x.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 Gg(e,t){return{...e,callbackParams:t}}function Ul(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function as(e){return!(x.isIdentifier(e)||x.isThisExpression(e)||x.isMemberExpression(e)||x.isOptionalMemberExpression(e)||x.isCallExpression(e)||x.isOptionalCallExpression(e))}function lu(e,t){return uu(e,t).length>0}function zi(e,t){let n=ie(e.node),r=ie(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()&&!Zg(o,n,r)))return!0;o=o.parentPath}return!1}function Zg(e,t,n){let r=ie(e.node.consequent);if(r&&Ye(r,t)&&!Ye(r,n))return!1;let o=e.node.alternate?ie(e.node.alternate):null;return!(o&&Ye(o,t)&&!Ye(o,n))}function uu(e,t){let n=ie(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=ie(o.node.consequent),a=ie(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()&&du(o.node.operator)){let s=ie(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 $l(e,t,n,r){let o=uu(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=lo(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=Qg(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${ey(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function Qg(e,t){return qg(e.node)?t:`(${t})`}function qg(e){return x.isIdentifier(e)||x.isThisExpression(e)||x.isSuper(e)||x.isMemberExpression(e)||x.isOptionalMemberExpression(e)||x.isCallExpression(e)||x.isOptionalCallExpression(e)||x.isBooleanLiteral(e)||x.isNumericLiteral(e)||x.isStringLiteral(e)||x.isNullLiteral(e)||x.isUnaryExpression(e)}function du(e){return e==="&&"||e==="||"||e==="??"}function ey(e){return e.trim().startsWith("<")?e:`(${e})`}function fu(e,t){let n=ie(e.node),r=ie(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=Kl(e),i=Kl(t);if(!o||!i||!ty(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=ny(s.node,n);if(a&&!Ye(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=ie(s.node.right);if(a&&Ye(a,n)&&!Ye(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())&&ry(s)){let a=ie(s.node.body)??ie(s.node);if(a&&!Ye(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 Kl(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?ie(t.node.argument):null;if(t.isArrowFunctionExpression()&&(x.isJSXElement(t.node.body)||x.isJSXFragment(t.node.body)||x.isConditionalExpression(t.node.body)||x.isLogicalExpression(t.node.body)))return ie(t.node.body);t=t.parentPath}return null}function ty(e,t){return e.start===t.start&&e.end===t.end}function ny(e,t){let n=ie(e.consequent);if(n&&Ye(n,t))return n;let r=ie(e.alternate);return r&&Ye(r,t)?r:null}function ry(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}var oy={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 ao(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=oy[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 iy(e,t){for(let n of e.program.body){if(!x.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>x.isImportDefaultSpecifier(o));if(r&&x.isImportDefaultSpecifier(r))return r.local.name}return null}function sy(e,t,n){for(let r of e.program.body){if(!x.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>x.isImportSpecifier(i)&&(x.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&x.isImportSpecifier(o))return o.local.name}return null}function Jl(e){let t=new Set;return At(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function Xl(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function ay(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=rs(e),o=Ue(t);if(n.exportName!=="default"){let a=o?sy(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?Xl(r,Jl(o)):r;return{localName:c,importStep:Wi(e,c)}}if(!o)return{localName:r,importStep:Wi(e,r)};let i=iy(o,n.source);if(i)return{localName:i};let s=Xl(r,Jl(o));return{localName:s,importStep:Wi(e,s)}}function cy(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??rs(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 ly(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?uy(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function uy(e){return Object.fromEntries(Object.entries(e).filter(t=>es(t[1])))}function es(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(es):typeof e=="object"?Object.values(e).every(es):!1}function dy(e,t){let n=Ue(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Gl({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 Wi(e,t=rs(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 Hl(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 fy(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function $n(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function cs(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Jn(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:cs(e,t.slice(0,n)),index:r.index}}return null}function Yi(e,t){return e.locator?e.collectionPathMap?.[t]?cs(e.locator,e.collectionPathMap[t]):Jn(e.locator)?my(e.locator,hy(t,e.collectionIndexMap)):null:null}function py(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:pu(o,t)}function pu(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=pu(r,t);return o===void 0?void 0:{[n.name]:o}}function co(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 my(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},cs(e,i)}return null}function hy(e,t){return t?.[e]??e}function zl(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 gy(e,t){return yy(e.root,t.root)&&Ey(e.path??[],t.path??[])}function yy(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&&xy(e.sourceRange,t.sourceRange)}}function xy(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function ts(e,t){let n=null;return At(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 Ey(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 uo=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:$n(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:$n(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:$n(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:$n(t.kind,t.params.kind)};let r=t;if(!io(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Hl(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:$n(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=mg(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.routeId&&n.routeId&&n.params.routeId!==n.routeId?{ok:!1,errorCode:"stale-version",reason:"The className source route changed before save."}: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.buildSetPropsSteps({initialOrder:0,node:r,props:n.params.props,request:n});return i.ok?this.buildPlan(t,n,i.steps,o):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.buildSetPropsSteps({initialOrder:s.length,node:r,props:n.params.props,request:n});if(!a.ok)return a;s.push(...a.steps)}return this.buildPlan(t,n,s,i)}async buildSetPropsSteps(t){let{initialOrder:n,node:r,props:o,request:i}=t,s=r.file,a=[],c={};for(let[l,u]of Object.entries(o)){if(u===void 0)continue;let d=await this.graph.getElementPropertyWriteTarget?.(r.key,l),p=r.attributes?.find(m=>m.name===l);if(!(typeof p?.resolvedValue=="string"&&p.resolvedValue===u||p?.source===null&&p.value===u)){if(d?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`set-props cannot overwrite readonly external property '${l}'`};if(d?.kind==="value-binding"&&d.locator){let m=d.locator;if(d.sourceKind==="repeat-template"&&typeof i.selectionRef?.instanceIndex=="number"){let E=Yi(d,i.selectionRef.instanceIndex);if(!E)return{ok:!1,errorCode:"invalid-params",reason:"set-props could not resolve the selected repeat item"};m=E}a.push({order:n+a.length,file:d.file,type:"update-value",locator:m,value:u});continue}c[l]=u}}return Object.keys(c).length>0&&a.push({order:n+a.length,file:s,type:"set-props",locator:le(r),props:c}),{ok:!0,steps:a}}buildTextRewriteSteps(t,n,r,o,i){if(o?.kind==="value-binding"&&o.locator){if(o.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let a=Yi(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:le(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=te(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!gg(a.match.path))return{ok:!0,value:r};let c=yg(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=Yi(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=te(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){if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let s=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return s.ok?this.buildPlan(t,n,s.steps,o):s}async planRemoveNode(t,n,r,o){if(!o.canRemove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot remove this node"};let i=await this.graph.getTextWriteTarget(r.key,0);if(i?.kind==="external-entry")return this.buildPlan(t,n,[{order:0,file:`external:${i.sourceId}`,type:"invoke-external-adapter",sourceType:i.sourceType,sourceId:i.sourceId,adapterId:i.adapterId,capability:"remove-node",value:{operation:"remove-node"}}],o);if(r.isRepeatItemRoot){let d=i;if(d?.kind==="value-binding"&&d.locator){let p=Jn(d.locator);if(p)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:p.locator,index:p.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=co(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:le(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||dy(n,t)>1)return null;let r=Gi(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(!io(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=co(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let d=await this.planRepeatBackedInsertChild(t,n,r,o);if(d)return d;let p=this.getRepeatBackedTemplateStructureReason(r);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let m=Rl(this.graph.getFileContent(r.file),r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot insert child into this node"};let E=ao(r,n.params.node);if(E)return{ok:!1,errorCode:"unsupported-operation",reason:E};let b=[],v=0,C=n.params.node.kind==="component-call"?ay(n.params.node,this.graph.getFileContent(r.file)):void 0,A=C?.importStep;return A&&b.push({order:v++,file:r.file,type:"add-import",moduleSpecifier:A.moduleSpecifier,imports:A.imports}),b.push({order:v++,file:r.file,type:"insert-child",parentLocator:le(r),node:{jsx:cy(n.params.node,C?.localName)},placement:n.params.position.relation,anchorLocator:i?le(i):void 0}),this.buildPlan(t,n,b,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!io(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:ly(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(!io(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.position.relation!=="append"&&n.params.position.relation!=="prepend")return null;let i=n.params.node;if(i.kind!=="native-tag"||i.text===void 0||!this.graph.getChildNodes)return null;let s=this.graph.getChildNodes(r.key).find(d=>d.isRepeatItemRoot&&d.tag?.toLowerCase()===i.tag.toLowerCase());if(!s)return null;let a=await this.graph.getTextWriteTarget(s.key,0);if(!a||a.kind!=="value-binding"||!a.locator)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires a writable value target"};let c=Jn(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=py(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"?zl(0,a.collectionIndexMap):zl(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=co(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 this.isRepeatTemplateRootNode(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:")||this.isInsideMapCallback(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}isRepeatTemplateRootNode(t){let n=Ue(this.graph.getFileContent(t.file));if(!n)return t.isRepeatItemRoot===!0;let r=te(n,le(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ts(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=pt(this.graph.getFileContent(t.file),o);return i?Eg(o,i):t.isRepeatItemRoot===!0}isInsideMapCallback(t){let n=Ue(this.graph.getFileContent(t.file));if(!n)return!1;let r=te(n,le(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ts(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}planRepeatTemplateInternalMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Ue(c);if(!l)return null;let u=Ct(l,r),d=Ct(l,o);if(!u||!d)return null;let p=pt(c,u),m=pt(c,d);if(!so(p,m))return null;if(a&&(s==="before"||s==="after")){let b=Ct(l,a),v=b?pt(c,b):null;if(!so(p,v))return null}if(zi(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let E=Ml(c,r,o);return E.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:le(r),targetParentLocator:le(o),placement:s,anchorLocator:a?le(a):void 0,selectionContext:xn(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move node because it depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Ue(c);if(!l)return null;let u=Ct(l,r),d=Ct(l,o);if(!u||!d)return null;let p=pt(c,u);if(!p)return null;let m=pt(c,d);if(so(p,m))return null;if(m&&!Ig(m,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let N=Ol(c,l,a);if(m&&!so(m,N)||!m&&N)return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"}}if(r.tag&&r.tag.toLowerCase()===r.tag){let N=ao(o,{kind:"native-tag",tag:r.tag});if(N)return{ok:!1,errorCode:"unsupported-operation",reason:N}}let E=Xi(this.graph,r);if(!E)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(zi(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=$l(c,u,d,E);for(let N of b.conditionPaths){let G=Ll(N,d,p);if(!G.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${G.bindingNames.join(", ")}`}}let v=Dl(u,d,p,{preserveConditionalBoundary:b.conditionPaths.length>0});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${v.bindingNames.join(", ")}`};let C=kg(p,d);if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${C.bindingNames.join(", ")}`};let A=p;if(r.component!==o.component){let N=Cg({source:c,ast:l,sourceContext:p,sourceNode:r,targetParent:o,targetParentPath:d});if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:N.reason};A=N.context}else{let N=Yl(p.collectionPath,d);if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:N.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${N.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:le(r),targetParentLocator:le(o),placement:s,anchorLocator:a?le(a):void 0,repeatExpression:Ul(A,b.sourceJsx),selectionContext:xn(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),u=Ue(c),d=Ue(l);if(!u||!d)return null;let p=Pg({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let m=Ct(u,r),E=Ct(d,o);if(!m||!E)return null;let b=fu(p.callSitePath,E);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason};let v=pt(c,m);if(!v)return null;if(pt(l,E))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Ol(l,d,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let D=ao(o,{kind:"native-tag",tag:r.tag});if(D)return{ok:!1,errorCode:"unsupported-operation",reason:D}}let A=Xi(this.graph,r);if(!A)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(zi(m,E))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let N=$l(c,m,E,A);for(let D of N.conditionPaths){let L=Ll(D,E,v);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 G=Dl(m,E,v,{preserveConditionalBoundary:N.conditionPaths.length>0});if(!G.ok)return{ok:!1,errorCode:"unsupported-operation",reason:G.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${G.bindingNames.join(", ")}`};let fe=Hg({sourceFile:r.file,targetFile:o.file,sourceContext:v,targetParentPath:E});if(!fe.ok)return{ok:!1,errorCode:"unsupported-operation",reason:fe.reason};let ue=Yg(v);if(!ue.ok)return{ok:!1,errorCode:"unsupported-operation",reason:ue.reason};let R=Gg(v,ue.callbackParams),_=[{order:0,file:r.file,type:"remove-node",locator:le(r),removeWhitespace:!0}];for(let D of fe.imports)_.push({order:_.length,file:o.file,type:"add-import",moduleSpecifier:D.moduleSpecifier,imports:D.imports});return _.push({order:_.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:le(o),expression:Ul(R,N.sourceJsx),placement:s,anchorLocator:a?le(a):void 0,selectionContext:xn(o)}),this.buildPlan(t,n,_,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};let i=Hl(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(fy(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 C=n.params.target.relation,A=i.anchorNode&&(C==="before"||C==="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:C,anchorSourceId:A?.kind==="external-entry"?A.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,d=co(r,a,this.graph.getTextProvenance?.(r.key,0)??null);if(d&&!Hi(d))return{ok:!1,errorCode:"unsupported-operation",reason:d};if(r.isRepeatItemRoot&&u?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===u.repeatOwnerKey&&(l==="before"||l==="after")){let C=a,A=await this.graph.getTextWriteTarget(u.key,0);if(C?.kind==="value-binding"&&A?.kind==="value-binding"&&C.locator&&A.locator){let N=Jn(C.locator),G=Jn(A.locator);if(N&&G&&C.file===A.file&&gy(N.locator,G.locator)){let fe=N.index,ue=G.index,R=l==="before"?ue-(fe<ue?1:0):ue+(fe<ue?0:1);return this.buildPlan(t,n,[{order:0,file:C.file,type:"move-array-item",locator:N.locator,fromIndex:fe,toIndex:R}],o)}}}if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let p=this.getRepeatBackedTemplateStructureReason(r),m=Hi(d)?d:p;if(m&&Hi(m)){let C=this.planRepeatTemplateInternalMove(t,n,r,s,o,l,u);if(C)return C;let A=this.planRepeatTemplateHoistMove(t,n,r,s,o,l,u);if(A)return A;let N=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,l,u);return N||{ok:!1,errorCode:"unsupported-operation",reason:m}}if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let E=await this.getUpstreamBackedDescendantReason(r);if(E)return{ok:!1,errorCode:"unsupported-operation",reason:E};if(r.tag&&r.tag.toLowerCase()===r.tag){let C=ao(s,{kind:"native-tag",tag:r.tag});if(C)return{ok:!1,errorCode:"unsupported-operation",reason:C}}if(c)return this.planCrossFileMove(t,n,r,s,o,l,u);let b=Ml(this.graph.getFileContent(r.file),r,s);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move node because it depends on bindings outside the target scope: ${b.bindingNames.join(", ")}`};let v=[{order:0,file:r.file,type:"move-node",locator:le(r),targetParentLocator:le(s),placement:l,anchorLocator:u?le(u):void 0,selectionContext:xn(s)}];return this.buildPlan(t,n,v,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=Xi(this.graph,r)??`<${r.component} />`,p=Pl(u,r);if(!p.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:le(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let E=r.tag??r.component,v={moduleSpecifier:Gi(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:E}]:[{kind:"named",imported:r.exportName,local:E===r.exportName?void 0:E}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:v.moduleSpecifier,imports:v.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:le(o),node:{jsx:d},placement:s,anchorLocator:a?le(a):void 0,selectionContext:xn(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:le(o),node:{jsx:d},placement:s,anchorLocator:a?le(a):void 0,selectionContext:xn(o)});let m=this.buildRemoveComponentImportStep(r,u);return m&&c.push({...m,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:ae(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};import zn from"node:path";import*as vu from"@babel/parser";import ls from"@babel/traverse";import*as S from"@babel/types";var Cu=typeof ls=="function"?ls:ls.default;function Ru(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var mu=new WeakMap;function hu(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 Pu(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=bs(s,t,n);if(!a)return null;let c=Is(a,r.sourceRange);if(!c)return null;let l=r.source??await qe({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await As({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});if(!m)return null;if(m.kind==="external")return{kind:"external-entry",file:m.file,sourceType:m.sourceType,sourceId:m.sourceId,adapterId:m.adapterId,displayExpression:m.displayPath};let E={kind:"value",root:m.root,path:m.path.length>0?m.path:[]};return{kind:"value-binding",file:m.file,locator:E,root:m.root,path:m.path,displayExpression:m.displayExpression??Gn(c.node,n),sourceKind:m.sourceKind,...m.collectionIndexMap?{collectionIndexMap:m.collectionIndexMap}:{},...m.collectionPathMap?{collectionPathMap:m.collectionPathMap}:{}}}let u=new Set,d=await zy({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});if(!d)return null;if(d.kind==="external")return{kind:"external-entry",file:d.file,sourceType:d.sourceType,sourceId:d.sourceId,adapterId:d.adapterId,displayExpression:d.displayPath};let p={kind:"value",root:d.root,path:d.path.length>0?d.path:[]};return{kind:"value-binding",file:d.file,locator:p,root:d.root,path:d.path,displayExpression:d.displayExpression??l.expression,sourceKind:d.sourceKind,...d.collectionIndexMap?{collectionIndexMap:d.collectionIndexMap}:{},...d.collectionPathMap?{collectionPathMap:d.collectionPathMap}:{}}}async function wu(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=bs(i,t,n);if(!s)return null;let a=e.expression!==void 0?(e.sourceRange?Fu(s,n,e.expression,e.sourceRange):null)??Cs(s,n,e.expression):e.sourceRange?Is(s,e.sourceRange):null;if(!a)return null;let c=ky(a),l=new Set,u=e.sourceInfo??await qe({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await Oe({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 ax({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 Iy(d,e.expression??Gn(c.node,n))}async function Ss(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=bs(i,t,n);if(!s)return Me("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?vy({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}):Cy({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}function Au(e){try{return vu.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function bs(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Au(n);return e.set(t,{source:n,ast:o}),o}function Is(e,t){let n=null,r=-1;for(let o of Yn(e).expressions){let i=o.node.loc;if(!i||!ks(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function Sy(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of Yn(e).expressions){if(!by(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function Nu(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of Yn(e).jsxElements){let i=o.node.loc;if(!i||!ks(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function Yn(e){let t=mu.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return Cu(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),mu.set(e,n),n}function by(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 ks(e,t){let n=gu({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=gu({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function Tu(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 gu(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}async function qe(e){if(S.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!S.isMemberExpression(e.expression))return null;let t=await Ku(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:Gn(e.expression,e.source),base:t.base,path:t.path}:null}function Iy(e,t){if(!e)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}:{}}}function ky(e){if(e.isLogicalExpression()&&(e.node.operator==="||"||e.node.operator==="??")){let t=e.get("left");if(!Array.isArray(t)&&t.isExpression())return t}return e}function Gn(e,t){if(t)return vs(e,t);let n=gx(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function vs(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Cs(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of Yn(e).expressions){if(vs(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function Fu(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of Yn(e).expressions){if(vs(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!ks(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}async function vy(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Is(r,o.sourceRange),u=o.source??(l?await qe({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null);if(!u){if(!l)return Ry(t,o.value);let p=await As({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return p?p.kind==="external"?bu(t,p):hs(t,Gn(l.node,n),p):Py({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Me("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await Oe({currentFile:t,expressionPath:l,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!d){let p=ms(l.node);if(p)return Me(p.code,p.message);let m=l.scope.getBinding(u.base);if(m?.path.isVariableDeclarator()){let E=ms(m.path.node.init);if(E)return Me(E.code,E.message)}return m?.path.isVariableDeclarator()&&S.isCallExpression(m.path.node.init)?wy("unsupported-expression",Lu(m.path.node.init,e.functionCallContracts)):Me("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?bu(t,d):hs(t,u.expression,d)}async function Cy(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Me("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Cs(r,n,o.conditionExpression);if(!l)return Me("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await Oe({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 Me("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Me("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=hs(t,o.conditionExpression,u);return d.finalSource?{...d,finalSource:{...d.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...d.chain,{kind:"conditional-branch",file:u.file,displayName:o.conditionExpression,canEditHere:!0}]}:d}function Ry(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 Py(e){let t=await Ou(e);if(t.length===0)return Me("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(Ay(e.expression))return Mu(t);if(Du(e.expression))return Me("unsupported-expression","i18n helpers require a static message id string");if(S.isMemberExpression(e.expression)&&e.expression.computed&&!S.isNumericLiteral(e.expression.property)&&!S.isStringLiteral(e.expression.property))return Me("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Me(n.code,n.message)}function Me(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function wy(e,t){return Mu([{code:e,message:t}])}function Mu(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function Ay(e){return S.isCallExpression(e)||S.isConditionalExpression(e)||S.isLogicalExpression(e)||S.isBinaryExpression(e)}function Wn(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 Ou(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=ms(t);if(l)return[l];if(S.isCallExpression(t))return[{code:"unsupported-expression",message:Lu(t,c)}];if(S.isMemberExpression(t)&&t.computed){let u=t.property;if(!S.isNumericLiteral(u)&&!S.isStringLiteral(u)){if(!S.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let p=await et(u,n,r,o,i,s,a);if(typeof p!="string"&&!Number.isInteger(p))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return S.isBinaryExpression(t)?Wn([...await us(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):S.isLogicalExpression(t)?Wn([...await us(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"}]):S.isConditionalExpression(t)?Wn([...await us(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 ms(e){return Du(e)?yu("i18n helpers require a static message id string"):Oy(e)?yu("CMS helpers require static entry id and field path string arguments"):null}async function us(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Ou({...t,expression:o}));return r}function Ny(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:[Ty(e.sourceType)]}}async function Rs(e){for(let n of jy){if(!xu(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Su(Eu(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(!xu(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Su(Eu(r),e.externalAdapters)}return null}function Ty(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function Fy(e){return{code:"external-source-readonly",message:e}}function yu(e){return{code:"unsupported-expression",message:e}}function Ps(e){return!e||!S.isCallExpression(e)?null:S.isIdentifier(e.callee)?e.callee.name:S.isMemberExpression(e.callee)&&!e.callee.computed&&S.isIdentifier(e.callee.object)&&S.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function xu(e,t){if(!t||t.length===0)return!0;let n=Ps(e.node);return n?t.includes(n):!1}function Eu(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Wn(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Su(e,t){let n=Ny(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:Wn([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function My(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!S.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!S.isStringLiteral(n)||!S.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 Oy(e){return!!e&&S.isCallExpression(e)&&S.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!S.isStringLiteral(e.arguments[0])||!S.isStringLiteral(e.arguments[1]))}function _u(e){if(!(!e||!S.isCallExpression(e))){if(S.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&S.isStringLiteral(t)?t.value:null}if(S.isMemberExpression(e.callee)&&!e.callee.computed&&S.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&S.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!S.isObjectExpression(t))return null;for(let n of t.properties)if(S.isObjectProperty(n)&&!n.computed&&(S.isIdentifier(n.key)&&n.key.name==="id"||S.isStringLiteral(n.key)&&n.key.value==="id")&&S.isStringLiteral(n.value))return n.value.value;return null}}}function Du(e){return _u(e)===null}async function _y(e,t,n){let r=new Set,o=zn.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=zn.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"]:[zn.posix.join(i,"locales"),zn.posix.join(i,"messages")];for(let a of s){let c=zn.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function Dy(e){let t=_u(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await _y(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function Ly(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!S.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!S.isExpression(n))return null;let o=await et(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:[Fy("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var jy=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>My(e)},{helperNames:["apiField"],resolve:e=>Ly(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>Dy({currentFile:e,expressionPath:t,exists:n})}];function bu(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 hs(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=Hy(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:!0}):n.sourceKind==="imported-binding"?c.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:!0}):n.sourceKind==="repeat-template"&&c.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:!0}),n.path.length>0&&n.sourceKind!=="repeat-template"&&c.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:!0}),i&&c.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:!0}),{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:c,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var By=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function ws(e,t){let n=[...By,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function Lu(e,t){let n=e.callee;return S.isIdentifier(n)&&ws(n.name,t)?.purity==="side-effect"?`Helper "${n.name}" is registered as side-effectful and remains readonly`:"Function calls are recognized but remain readonly until a pure-call strategy is registered"}async function As(e){let t=await Rs(e);if(t)return t;let n=await ju({...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 qe({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 Oe({...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 Jy(e)}async function ju(e){let t=await Ze({...e,allowComposed:!1});return t?.kind==="source"?t.provenance:null}async function Ze(e){let t=Vy(e.expressionPath),n=Ky(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 qe({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 Oe({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 qe({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 Oe({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 Ze({...e,expressionPath:r,allowComposed:!0}),a=await Ze({...e,expressionPath:o,allowComposed:!1}),c=await Ze({...e,expressionPath:i,allowComposed:!1});return ds(s,a,c)}if(t.isCallExpression())return Uy({...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 Ze({...e,expressionPath:r,allowComposed:!0}),s=await Ze({...e,expressionPath:o,allowComposed:!0});return ds(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 Ze({...e,expressionPath:r,allowComposed:!0}),s=await Ze({...e,expressionPath:o,allowComposed:!0});return ds(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Ze({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Vy(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 Uy(e){let t=Ps(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:Ze({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(S.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Ze({...e,expressionPath:o,allowComposed:!1})}}return null}function ds(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!$y(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function $y(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 Ky(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function Jy(e){if(!e.expressionPath.isCallExpression())return null;let t=Ps(e.expressionPath.node);if(!t)return null;let n=ws(t,e.functionCallContracts);if(!n||n.purity!=="pure")return null;let r=n.sourceArgIndex??0,o=e.expressionPath.get(`arguments.${r}`);return!o||Array.isArray(o)||!o.isExpression()?null:await Bu({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})}async function Bu(e){let t=await Rs({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 qe({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 Oe({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 As({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 Xy(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!S.isCallExpression(t))return null;let n=t.callee;if(!S.isIdentifier(n))return null;let r=ws(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}`);return!s||Array.isArray(s)||!s.isExpression()?null:await Bu({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})}function Hy(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=po(t,e.path);return{sourceId:o,displayPath:o}}async function zy(e){let t=e.segment.source;return t?Oe({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 Oe(e){let t=e.sourceInfo,n=Vu(e.expressionPath,t.base);if(n){let l=await Uu({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 b=Yy(n.callPath,[...n.basePath,...t.path]);return Vn(b)?hu(e.currentFile,b.sourceId,b.displayPath):null}let u=yx(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,p=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],m=[{kind:"index",index:0},...n.basePath,...t.path];return Qe(l.value,m)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??p,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],u=r.path.parentPath;if(!l||l.kind!=="property"||!u?.isImportDeclaration())return null;let d=await tn(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let p=await fo({file:d,exportName:l.name,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!p||p.kind==="external")return null;let m=t.path.slice(1);return Qe(p.value,m)===void 0?null:{kind:"value",file:p.file,root:p.root,path:m,sourceKind:"imported-binding",collectionIndexMap:p.collectionIndexMap}}let o=Nl(r);if(o){let l=o.expressionPath,u=await qe({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let d=await Oe({...e,expressionPath:l,sourceInfo:{...u,expression:po(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}if(t.path.length===0){let d=await ju({currentFile:e.currentFile,expressionPath:l,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(d)return d}}if(r.kind==="param")return fx({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 Xy({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=eo(r,t.path);if(Vn(s))return hu(e.currentFile,s.sourceId,s.displayPath);let a=await zt({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}function Vu(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=We(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!Wy(s,r)?null:{callPath:s,basePath:i}}function Wy(e,t){let n=e.node.callee;return!S.isMemberExpression(n)||!S.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}async function Uu(e){let{currentFile:t,callPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.node.callee;if(!S.isMemberExpression(a)||!S.isIdentifier(a.property)||a.property.name!=="map")return null;let c=n.get("callee");if(!c.isMemberExpression())return null;let l=c.get("object");if(Array.isArray(l)||!l.isExpression())return null;let u=await Zn({currentFile:t,expressionPath:l,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return!u||!Array.isArray(u.value)||u.value.length===0?null:u}function Yy(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:no(r,t)}async function Zn(e){let{currentFile:t,expressionPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e;if(n.isIdentifier()){let a=n.scope.getBinding(n.node.name);if(!a)return null;let c=await zt({currentFile:t,binding:a,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return c?.kind==="static"?c:null}if(n.isCallExpression())return $u({currentFile:t,callPath:n,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(n.isTSAsExpression()||n.isTSSatisfiesExpression()||n.isTSNonNullExpression()){let a=n.get("expression");if(!Array.isArray(a)&&a.isExpression())return Zn({...e,expressionPath:a})}if(n.isArrayExpression()){let a=Tu(n.node);if(!a)return null;let c=await et(n.node,n.scope,t,r,o,i,s);return Array.isArray(c)?{kind:"static",file:t,root:{kind:"expression",sourceRange:a},value:c,sourceKind:"binding"}:null}if(n.isMemberExpression()){let a=await qe({expression:n.node,scope:n.scope,currentFile:t,readFile:r,exists:o,fileCache:i,visited:s});if(!a)return null;let c=await Oe({currentFile:t,expressionPath:n,sourceInfo:a,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(!c||c.kind==="external")return null;let l=await Gy({currentFile:t,expressionPath:n,provenance:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(!l||l.kind!=="static")return null;if(c.collectionPathMap?.length){let d=xx(l.value,c.collectionPathMap);if(d)return{kind:"static",file:c.file,root:c.root,value:d.value,sourceKind:c.sourceKind,collectionPathMap:d.collectionPathMap}}let u=Qe(l.value,c.path);return Array.isArray(u)?{kind:"static",file:c.file,root:c.root,value:u,sourceKind:c.sourceKind,pathPrefix:c.path,collectionIndexMap:c.collectionIndexMap,collectionPathMap:c.collectionPathMap}:null}return null}async function Gy(e){let{provenance:t}=e;if(t.root.kind==="binding"){let i=e.expressionPath.scope.getBinding(t.root.name);if(!i&&t.file!==e.currentFile){let s=await Nt(t.file,e.readFile,e.fileCache);i=s.ast?xs(s.ast).getBinding(t.root.name):void 0}return i?await zt({currentFile:t.file,binding:i,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}if(t.root.kind!=="expression")return null;let n=await Nt(t.file,e.readFile,e.fileCache);if(!n.ast)return null;let r=Sy(n.ast,t.root.sourceRange);if(!r)return null;let o=await et(r.node,r.scope,t.file,e.readFile,e.exists,e.fileCache,e.visited);return o===void 0?null:{kind:"static",file:t.file,root:t.root,value:o,sourceKind:t.sourceKind}}async function $u(e){return await Zy(e)??await Qy(e)??await qy(e)}async function Zy(e){let{callPath:t}=e,n=t.node.callee;if(!S.isMemberExpression(n)||!S.isIdentifier(n.property)||n.property.name!=="filter")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await Zn({currentFile:e.currentFile,expressionPath: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});if(!i||!Array.isArray(i.value))return null;let[s]=t.node.arguments;if(!S.isArrowFunctionExpression(s)&&!S.isFunctionExpression(s))return null;let a=s.params[0];if(!S.isIdentifier(a))return null;let c=ex(s);if(!c)return null;let l=[],u=[],d=[];for(let[p,m]of i.value.entries()){let E=tx(c,a.name,m);if(typeof E!="boolean")return null;if(E){l.push(m),u.push(i.collectionIndexMap?.[p]??p);let b=i.collectionPathMap?.[p];b&&d.push(b)}}return{...i,value:l,pathPrefix:i.pathPrefix,collectionIndexMap:u,...d.length>0?{collectionPathMap:d}:{}}}async function Qy(e){let{callPath:t}=e,n=t.node.callee;if(!S.isMemberExpression(n)||!S.isIdentifier(n.property)||n.property.name!=="slice")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await Zn({currentFile:e.currentFile,expressionPath: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});if(!i||!Array.isArray(i.value))return null;let[s,a]=t.node.arguments,c=Iu(s,0),l=Iu(a,i.value.length);if(c===null||l===null)return null;let u=Math.max(0,c<0?i.value.length+c:c),d=Math.max(0,l<0?i.value.length+l:l),p=i.value.map((E,b)=>i.collectionIndexMap?.[b]??b).slice(u,d),m=i.collectionPathMap?.slice(u,d);return{...i,value:i.value.slice(u,d),pathPrefix:i.pathPrefix,collectionIndexMap:p,...m?{collectionPathMap:m}:{}}}function Iu(e,t){return e?S.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}async function qy(e){let{callPath:t}=e,n=t.node.callee;if(!S.isMemberExpression(n)||!S.isIdentifier(n.property)||n.property.name!=="sort"&&n.property.name!=="toSorted")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await Zn({currentFile:e.currentFile,expressionPath: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});if(!i||!Array.isArray(i.value))return null;let[s]=t.node.arguments;if(!S.isArrowFunctionExpression(s)&&!S.isFunctionExpression(s))return null;let[a,c]=s.params;if(!S.isIdentifier(a)||!S.isIdentifier(c))return null;let l=i.value.map((d,p)=>({value:d,sourceIndex:i.collectionIndexMap?.[p]??p,originalIndex:p})),u=[...l];for(let d of l)for(let p of l)if(ku(s,a.name,c.name,d.value,p.value)===void 0)return null;return u.sort((d,p)=>{let m=ku(s,a.name,c.name,d.value,p.value)??0;return m===0?d.originalIndex-p.originalIndex:m}),{...i,value:u.map(d=>d.value),pathPrefix:i.pathPrefix,collectionIndexMap:u.map(d=>d.sourceIndex),...i.collectionPathMap?{collectionPathMap:u.map(d=>i.collectionPathMap?.[d.originalIndex]).filter(d=>!!d)}:{}}}function ku(e,t,n,r,o){let i=S.isExpression(e.body)?e.body:e.body.body.find(a=>S.isReturnStatement(a))?.argument;if(!i||!S.isExpression(i))return;let s=gs(i,t,n,r,o);return typeof s=="number"?s:void 0}function gs(e,t,n,r,o){if(S.isNumericLiteral(e)||S.isStringLiteral(e)||S.isBooleanLiteral(e))return e.value;if(S.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(S.isMemberExpression(e)){let i=ys(e,t);if(i)return Qe(r,i);let s=ys(e,n);return s?Qe(o,s):void 0}if(S.isBinaryExpression(e)&&e.operator==="-"){let i=S.isExpression(e.left)?gs(e.left,t,n,r,o):void 0,s=S.isExpression(e.right)?gs(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function ex(e){if(S.isExpression(e.body))return e.body;for(let t of e.body.body)if(S.isReturnStatement(t)&&t.argument&&S.isExpression(t.argument))return t.argument;return null}function tx(e,t,n){let r=Ht(e,t,n);return typeof r=="boolean"?r:void 0}function Ht(e,t,n){if(S.isStringLiteral(e)||S.isNumericLiteral(e)||S.isBooleanLiteral(e))return e.value;if(S.isNullLiteral(e))return null;if(S.isIdentifier(e))return e.name===t?n:void 0;if(S.isMemberExpression(e)){let r=ys(e,t);return r?Qe(n,r):void 0}if(S.isUnaryExpression(e)&&e.operator==="!"){let r=Ht(e.argument,t,n);return r===void 0?void 0:!r}if(S.isLogicalExpression(e)){let r=Ht(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&Ht(e.right,t,n);if(e.operator==="||")return r||Ht(e.right,t,n)}if(S.isBinaryExpression(e)){let r=S.isExpression(e.left)?Ht(e.left,t,n):void 0,o=S.isExpression(e.right)?Ht(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 ys(e,t){let n=[],r=e;for(;S.isMemberExpression(r);){if(r.computed)if(S.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(S.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!S.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!S.isIdentifier(r)||r.name!==t?null:n}async function zt(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=`${t}::${n.kind}::${n.identifier.name}`;if(s.has(a))return null;s.add(a);try{let c=await nx({currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s});if(c)return c;if(n.path.isImportSpecifier()||n.path.isImportDefaultSpecifier())return await hx({currentFile:t,binding:n,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:i,visited:s});if(n.kind==="param")return null;if(n.path.isVariableDeclarator()){let l=n.path.node.init;if(!l||!S.isExpression(l))return null;let u=n.path.get("init");if(u&&!Array.isArray(u)&&u.isExpression()){let p=await Rs({currentFile:t,expressionPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(p)return p;if(u.isCallExpression()){let m=await $u({currentFile:t,callPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(m)return m}}let d=await et(l,n.path.scope,t,r,o,i,s);return d===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:d,sourceKind:"binding"}}if(n.path.isIdentifier()&&n.path.parentPath?.isExportDefaultDeclaration()){let l=n.path.parentPath.node.declaration;if(!S.isExpression(l))return null;let u=await et(l,n.path.scope,t,r,o,i,s);return u===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:u,sourceKind:"binding"}}return null}finally{s.delete(a)}}async function nx(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e;if(!n.path.isVariableDeclarator()||!n.path.get("id").isArrayPattern())return null;let a=n.path,c=a.node.init;if(!c||!S.isCallExpression(c))return null;let l=rx(c);if(!l||!S.isArrayPattern(a.node.id)||a.node.id.elements.findIndex(E=>S.isIdentifier(E)&&E.name===n.identifier.name)!==0)return null;let d=l==="useReducer"?1:0,p=c.arguments[d];if(!p||!S.isExpression(p))return null;let m=await et(p,a.scope,t,r,o,i,s);return m===void 0?null:{kind:"static",file:t,root:{kind:"hook-state",name:n.identifier.name,hook:l},value:m,sourceKind:"binding"}}function rx(e){return S.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:S.isMemberExpression(e.callee)&&S.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function ox(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()||!S.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 ix(e,t){let n=ox(e.path);if(!n)return null;let r=yn(e,t);return r?{...n,...r}:null}function po(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function sx(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}async function ax(e){let t=lx(e.expressionPath.node);if(!t||!ux(t.segments))return null;let n=await Oe({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 cx({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:Gn(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function cx(e){let t=null,n,r=[];for(let i of e.segments){if(i.kind!=="dynamic")continue;let s=await qe({expression:i.expression,scope:e.expressionPath.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!s)return null;let a=Vu(e.expressionPath,s.base);if(!a)return null;let c=await Uu({currentFile:e.currentFile,callPath:a.callPath,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(!c||!Array.isArray(c.value))return null;let l=c.value.map((u,d)=>{let p=Qe(c.value,[{kind:"index",index:d},...a.basePath,...s.path]);return dx(p)});if(l.some(u=>u===null)||t!==null&&t!==l.length)return null;t=l.length,n??=c.collectionIndexMap,r.push(l)}if(t===null||t===0)return null;let o=[];for(let i=0;i<t;i+=1){let s=[...e.rootPath],a=0;for(let c of e.segments){if(c.kind==="dynamic"){let l=r[a]?.[i];if(!l)return null;s.push(l),a+=1;continue}s.push({...c})}o.push(s)}return{...n?{collectionIndexMap:n}:{},collectionPathMap:o}}function lx(e){let t=[],n=e;for(;S.isMemberExpression(n)||S.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(S.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(S.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(S.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(S.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return S.isIdentifier(n)?{base:n.name,segments:t}:null}function ux(e){return e.some(t=>t.kind==="dynamic")}function dx(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}async function fx(e){let t=ix(e.binding,e.sourceInfo);if(!t||!e.graph)return null;let n=[...e.graph.elements.values()].filter(l=>sx(l,e.currentFile,t.componentName,t.exportName));if(n.length!==1)return null;let r=n[0],o=r.attributes?.find(l=>l.name===t.propName);if(o&&!o.source){let l=await px({caller:r,propName:t.propName,remainingPath:t.remainingPath,readFile:e.readFile,fileCache:e.fileCache});if(l)return fs(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile})}if(!o?.source){let l=await mx({caller:r,propName:t.propName,remainingPath:t.remainingPath,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(l)return fs(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile});let u=Fl(e.binding,t.componentName,t.propName);if(!u||u.propName!==t.propName)return null;let d=await et(u.expressionPath.node,u.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(d===void 0)return null;let p=t.remainingPath;return p.length>0&&Qe(d,p)===void 0?null:{kind:"value",file:e.currentFile,root:{kind:"binding",name:t.propName},path:p,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.displayPath,chainPrefix:[{kind:"component-prop",file:e.currentFile,displayName:u.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let i=await Nt(r.sourceFile,e.readFile,e.fileCache);if(!i.ast)return null;let s=Fu(i.ast,i.source,o.source.expression,o.sourceRange)??Cs(i.ast,i.source,o.source.expression);if(!s)return null;let a={...o.source,expression:po(o.source.expression,t.remainingPath),path:[...o.source.path,...t.remainingPath]},c=await Oe({currentFile:r.sourceFile,expressionPath:s,sourceInfo:a,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 c?fs(c.kind==="external"?c:{...c,displayExpression:a.expression},{componentName:t.componentName,propName:t.propName,file:r.sourceFile}):null}async function px(e){let t=await Nt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=Nu(t.ast,e.caller.sourceRange);if(!n)return null;let r=n.get("openingElement").get("attributes").find(a=>a.isJSXAttribute()&&a.node.name.type==="JSXIdentifier"&&a.node.name.name===e.propName);if(!r?.isJSXAttribute())return null;let o=r.get("value"),i=o.isStringLiteral()?o:o.isJSXExpressionContainer()?o.get("expression"):null;if(!i?.isExpression())return null;let s=Tu(i.node);return s?{kind:"value",file:e.caller.sourceFile,root:{kind:"expression",sourceRange:s},path:e.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:e.propName,editMode:"upstream",diagnostics:[]}:null}async function mx(e){let t=await Nt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=Nu(t.ast,e.caller.sourceRange);if(!n)return null;let r=n.get("openingElement");for(let o of r.get("attributes")){if(!o.isJSXSpreadAttribute())continue;let i=o.get("argument");if(!i.isExpression())continue;let s=await qe({expression:i.node,scope:i.scope,source:t.source,currentFile:e.caller.sourceFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!s)continue;let a=[{kind:"property",name:e.propName},...e.remainingPath],c={...s,expression:po(s.expression,a),path:[...s.path,...a]},l=await Oe({currentFile:e.caller.sourceFile,expressionPath:i,sourceInfo:c,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(l)return l.kind==="external"?l:{...l,displayExpression:c.expression}}return null}function fs(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"}}async function hx(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.path.parentPath;if(!a||!a.isImportDeclaration())return null;let c=a.node.source.value;if(typeof c!="string")return null;let l=await tn(t,c,o);if(!l)return null;if(n.path.isImportDefaultSpecifier()){let b=await Nt(l,r,i),v=b.ast?Es(b.ast,"default"):null,C=await fo({file:l,exportName:"default",readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return!C||C.kind!=="static"?null:{kind:"static",file:v?.kind==="default-expression"?C.file:l,root:v?.kind==="default-expression"?C.root:{kind:"default-export"},value:C.value,sourceKind:"imported-binding"}}if(!n.path.isImportSpecifier())return null;let u=n.path.node.imported,d=S.isIdentifier(u)?u.name:u.value,p=await Nt(l,r,i),m=p.ast?Es(p.ast,d):null,E=await fo({file:l,exportName:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return E?E.kind==="external"?E:{kind:"static",file:m?.kind==="re-export"?E.file:l,root:m?.kind==="re-export"?E.root:{kind:"named-export",name:d},value:E.value,sourceKind:"imported-binding"}:null}async function fo(e){let{file:t,exportName:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=`export::${t}::${n}`;if(!s.has(a)){s.add(a);try{let c=await Nt(t,r,i);if(!c.ast)return;let l=Es(c.ast,n);if(!l)return;if(l.kind==="default-expression"){let m=l.expression;if(!m||!S.isIdentifier(m))return;let E=xs(c.ast).getBinding(m.name);return E?await zt({currentFile:t,binding:E,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s})??void 0:void 0}if(l.kind==="re-export"){if(!l.source||!l.name)return;let m=await tn(t,l.source,o);return m?fo({...e,file:m,exportName:l.name}):void 0}let u=l.name;if(!u)return;let d=xs(c.ast).getBinding(u);return d?await zt({currentFile:t,binding:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s})??void 0:void 0}finally{s.delete(a)}}}function xs(e){let t=null;if(Cu(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}function Es(e,t){for(let n of e.program.body){if(t==="default"&&S.isExportDefaultDeclaration(n))return S.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(S.isFunctionDeclaration(n.declaration)||S.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(S.isExportNamedDeclaration(n)){if(n.declaration){if(S.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(S.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((S.isFunctionDeclaration(n.declaration)||S.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((S.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&S.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}async function et(e,t,n,r,o,i,s){if(S.isStringLiteral(e)||S.isNumericLiteral(e)||S.isBooleanLiteral(e))return e.value;if(S.isNullLiteral(e))return null;if(S.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(S.isTSAsExpression(e)||S.isTSSatisfiesExpression(e)||S.isTSNonNullExpression(e))return await et(e.expression,t,n,r,o,i,s);if(S.isIdentifier(e)){let a=t.getBinding(e.name);if(!a)return;let c=await zt({currentFile:n,binding:a,readFile:r,exists:o,fileCache:i,visited:s});return c?.kind==="static"?c.value:void 0}if(S.isArrayExpression(e)){let a=[];for(let c of e.elements){if(!c||S.isSpreadElement(c))return;let l=await ps(c,t,n,r,o,i,s);if(l===void 0)return;a.push(l)}return a}if(S.isObjectExpression(e)){let a={};for(let c of e.properties){if(!S.isObjectProperty(c)||c.computed)return;let l=null;if(S.isIdentifier(c.key)?l=c.key.name:S.isStringLiteral(c.key)&&(l=c.key.value),!l)return;if(c.shorthand){if(!S.isIdentifier(c.value))return;let d=await ps(c.value,t,n,r,o,i,s);if(d===void 0)return;a[l]=d;continue}if(!S.isExpression(c.value))return;let u=await ps(c.value,t,n,r,o,i,s);u!==void 0&&(a[l]=u)}return a}if(S.isMemberExpression(e)){let a=await Ku(e,t,n,r,o,i,s);if(!a)return;let c=t.getBinding(a.base);if(!c)return;let l=await zt({currentFile:n,binding:c,readFile:r,exists:o,fileCache:i,visited:s});return!l||l.kind!=="static"?void 0:Qe(l.value,a.path)}}async function ps(e,t,n,r,o,i,s){if(!S.isSpreadElement(e))return await et(e,t,n,r,o,i,s)}async function Ku(e,t,n,r,o,i,s){if(S.isIdentifier(e))return{base:e.name,path:[]};if(!S.isMemberExpression(e))return null;let a=[],c=e;for(;S.isMemberExpression(c);){if(c.computed){let l=c.property;if(S.isNumericLiteral(l))a.unshift({kind:"index",index:l.value});else if(S.isStringLiteral(l))a.unshift({kind:"property",name:l.value});else{let u=S.isExpression(l)?await et(l,t,n,r,o,i,s):void 0;if(typeof u=="string")a.unshift({kind:"property",name:u});else if(Number.isInteger(u))a.unshift({kind:"index",index:u});else return null}}else{if(!S.isIdentifier(c.property))return null;a.unshift({kind:"property",name:c.property.name})}c=c.object}return S.isIdentifier(c)?{base:c.name,path:a}:null}function gx(e){if(S.isIdentifier(e))return{base:e.name,path:[]};if(!S.isMemberExpression(e))return null;let t=[],n=e;for(;S.isMemberExpression(n);){if(n.computed)if(S.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(S.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!S.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return S.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 yx(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 xx(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}}async function Nt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Au(o),s={source:o,ast:i};return n.set(e,s),s}import Os from"@babel/generator";import{parse as Nx}from"@babel/parser";import _s from"@babel/traverse";import*as k from"@babel/types";import*as zu from"@babel/types";import Ns from"@babel/generator";import*as re from"@babel/types";var Ex=typeof Ns=="function"?Ns:Ns.default,Sx=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,bx=/^((?:https?:)?\/\/)[^/@\s]+@/i,Ix=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Xu(e,t){let n=st(e.callee);if(!n)return null;if(n==="fetch")return Ts(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Ju(r))return Ts(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Ju(r))return Ts(e.arguments[0],r,t,["ky client contract"])}return null}function Ts(e,t,n,r){if(!e||re.isSpreadElement(e)||re.isJSXNamespacedName(e))return Rx(t,n,r,"missing url argument");let o=Qn(e);return{sourceKind:Cx(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 Qn(e){if(re.isStringLiteral(e))return mo(e.value);if(re.isTemplateLiteral(e))return mo(kx(e));if(re.isBinaryExpression(e)&&e.operator==="+"){let t=Qn(e.left),n=Qn(e.right);return!t&&!n?void 0:mo(`${t??Fs(e.left)}${n??Fs(e.right)}`)}if(re.isMemberExpression(e)){let t=Hu(e);if(t)return`env:${t}`}if(!(re.isCallExpression(e)&&st(e.callee)==="new URL")){if(re.isNewExpression(e)&&re.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!re.isSpreadElement(t)?Qn(t):void 0,o=n&&!re.isSpreadElement(n)?Qn(n):void 0;return o&&r?mo(`${o} + ${r}`):r??o}if(re.isIdentifier(e))return`:${e.name}`}}function kx(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+=Fs(r))}return t}function Fs(e){if(re.isIdentifier(e))return`:${e.name}`;if(re.isMemberExpression(e)){let t=Hu(e);if(t)return`env:${t}`}return`:${vx(e)}`}function vx(e){return Ex(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function mo(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(bx,"$1<redacted>@").replace(Ix,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?Sx.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function Cx(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 Rx(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function Ju(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Hu(e){return!re.isMemberExpression(e.object)||!re.isIdentifier(e.object.object,{name:"process"})||!Px(e.object.property,"env")?null:re.isIdentifier(e.property)?e.property.name:re.isStringLiteral(e.property)?e.property.value:null}function Px(e,t){return re.isIdentifier(e)&&e.name===t}function st(e){if(re.isIdentifier(e))return e.name;if(re.isMemberExpression(e)){let t=st(e.object),n=re.isIdentifier(e.property)?e.property.name:re.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var wx=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),Ax=new Set(["getConfig","submit"]);function Wu(e,t){let n=st(e.callee);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!wx.has(i))return null;let s=Ms(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(!Ax.has(i))return null;let s=Ms(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=Ms(e,0)??"/cms/:path";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:n,endpointPattern:i,confidence:i==="/cms/:path"?"partial":"safe-derived",evidence:[{file:t.file,symbol:n,reason:"VCP CMS fetch helper"}]}}return null}function Yu(e,t){let n=st(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 Gu(e){let t=st(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function Ms(e,t){let n=e.arguments[t];return zu.isStringLiteral(n)?n.value:null}var js=typeof _s=="function"?_s:_s.default,iC=typeof Os=="function"?Os:Os.default,Tx={maxFunctionDepth:8,maxImportDepth:6},Fx=new Set(["src","href","alt","poster","content","title","aria-label"]);async function nd(e){let t=e.fileCache??new Map,n=$s(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...Tx,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:gd(n,e.element.componentName)};await rd(e.element.componentName,e.graph,r);let o=[];o.push(...await Lx(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await jx(s,e.element,e.graph,r);a&&o.push(Ls(a,"text","children"))}for(let s of e.element.attributes??[]){let a=Dx(s);if(!a)continue;let c=await sd(s.source,e.element,e.graph,r);c&&o.push(Ls(c,a,s.name))}let i=qx(o).sort(md);return{hasDynamicData:i.length>0,bindings:i}}async function rd(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 od(l.importedFrom,l.exportName,n.file,n))&&s.push(l)}if(s.length===0)return;let a=new Map;for(let l of s){let u=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let d=await id(l.sourceFile,n);if(!d)continue;let p=yo(d,n,{importDepth:n.importDepth+1});p.paramSources.clear(),p.scopeVariables=gd(d,l.componentName),await rd(l.componentName,t,p);let m=await Mx(l,p);for(let[E,b]of m){if(!b)continue;let v=a.get(E)??[];v.push(b),a.set(E,v)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=fd(u);d.length===1&&c.set(l,d[0])}_x(o,c,n)}async function od(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 id(e,r))?.imports.get(t);if(!s||!ct(s.source))return!1;let a=await Ed(e,s.source,r.exists);return a?a===n?!0:od(a,s.importedName,n,r,o):!1}async function Mx(e,t){let n=new Map;js(t.analysis.ast,{JSXElement(o){if(Ox(o.node,e.sourceRange)){for(let i of o.node.openingElement.attributes)!k.isJSXAttribute(i)||!k.isJSXIdentifier(i.name)||!k.isJSXExpressionContainer(i.value)||!k.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 be(i,t);s&&r.set(o,s)}return r}function Ox(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 id(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 $s(e,r,t.fileCache)}function _x(e,t,n){if(k.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Us(Object.fromEntries(t),n.file));return}if(k.isObjectPattern(e))for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=k.isAssignmentPattern(r.value)?r.value.left:r.value;k.isIdentifier(i)&&n.paramSources.set(i.name,ve(o))}}function Dx(e){return e.name==="dangerouslySetInnerHTML"?"richtext":Fx.has(e.name)?"attribute":null}async function Lx(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 Bs(i.collectionSource,n);s&&r.push(Ls(bn(s),"repeat-region",i.collectionExpression))}return r}async function jx(e,t,n,r){return sd(e.source,t,n,r)}async function sd(e,t,n,r){let o=await Bx(e,t,n,r);return o||Bs(e,r)}async function Bx(e,t,n,r){if(!e)return null;let o=Vx(e.base,t,n);if(!o)return null;let i=await Bs(o.collectionSource,r);return i?nr(i,e.path,!0):null}function Vx(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 Bs(e,t){if(!e)return null;let n=await ad(e.base,t);return n?nr(n,e.path,!1):null}async function ad(e,t){let n=t.paramSources.get(e);if(n)return ve(n);if(t.variableCache.has(e))return eE(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await Ux(e,t);if(r)return t.variableCache.set(e,ve(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=await be(o,t);return t.variableCache.set(e,s?ve(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await yd(i,t);if(s){let a=yo(s,t,{importDepth:t.importDepth+1}),c=xd(i,s);if(c){let d=(await Wt(c,[],a)).returnSource;return t.variableCache.set(e,d?ve(d):null),t.resolvingVariables.delete(e),d}let l=s.variables.get(i.importedName);if(l){let u=await be(l,a);return t.variableCache.set(e,u?ve(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function Ux(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];js(t.analysis.ast,{CallExpression(o){if(k.isIdentifier(o.node.callee,{name:n})){let i=o.node.arguments[0];k.isExpression(i)&&r.push(i);return}o.node.arguments.some(i=>k.isIdentifier(i)&&i.name===n)&&r.push(o.node)}});for(let o of r){let i=await be(o,t);if(i)return i}return null}async function be(e,t){if(k.isIdentifier(e))return ad(e.name,t);if(k.isMemberExpression(e)||k.isOptionalMemberExpression(e)){let n=k.isMemberExpression(e)?Yu(e,{file:t.file}):null;if(n)return dd(n);let r=await $x(e,t);if(!r)return null;let o=Zx(e);return nr(r,o,!1)}if(k.isAwaitExpression(e))return k.isExpression(e.argument)?be(e.argument,t):null;if(k.isCallExpression(e))return cd(e,t);if(k.isObjectExpression(e)){let n=await ld(e,t);return Object.keys(n).length>0?Us(n,t.file):null}if(k.isConditionalExpression(e)){let n=await be(e.consequent,t),r=await be(e.alternate,t);return tr(Qu(n,r))}if(k.isLogicalExpression(e)){let n=await be(e.left,t),r=await be(e.right,t);return tr(Qu(n,r))}return k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e)?be(e.expression,t):null}async function $x(e,t){let n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);)n=n.object;return k.isExpression(n)?be(n,t):null}async function cd(e,t){let n=Wu(e,{file:t.file});if(n)return dd(n);if(Gu(e)){let d=e.arguments[0];if(d&&k.isExpression(d))return tr(await be(d,t))}let r=await Kx(e,t);if(r)return r;let o=Xu(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 Hx(e,t);if(i)return i;let s=await zx(e,t);if(s)return s;let a=await Wx(e,t);if(a)return a;let c=await Yx(e,t);if(c)return c;let l=[];for(let d of e.arguments)if(k.isExpression(d)){let p=await be(d,t);p&&l.push(p)}let u=fd(l);return u.length===1?tr(u[0]):null}async function Kx(e,t){let n=st(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=Xx(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await er(s.name,t);if(a)return(await Wt(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return ho(t.file,`${n} without static options`);let o=Jx(r,"queryFn");if(!o)return ho(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await er(o.name,t);return i?(await Wt(i.node,[],i.context)).returnSource:ho(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await Wt(o,[],t)).returnSource:k.isCallExpression(o)?cd(o,t):null}function Jx(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(ud(n)===t)return n.value}return null}function Xx(e,t,n){return k.isStringLiteral(e)?{sourceKind:e.value.startsWith("/api/")?"site-api-route":"external-api",sourceType:"api-field",endpointPattern:e.value,confidence:"exact",readonly:!0,evidence:[{file:t,reason:n}]}:null}async function Hx(e,t){if(!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=k.isExpression(e.callee.object)?await be(e.callee.object,t):null;if(!r)return null;if(n!=="map")return bn(r);let o=e.arguments[0];if(k.isIdentifier(o)){let i=await er(o.name,t);if(!i)return bn(r);let s=await Wt(i.node,[r],i.context);return{...bn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)){let i=await Wt(o,[r],t);return{...bn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return bn(r)}async function zx(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"json"})||!k.isExpression(e.callee.object)?null:be(e.callee.object,t)}async function Wx(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:tr(await be(e.callee.object,t))}async function Yx(e,t){if(!k.isIdentifier(e.callee))return null;let n=await er(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!k.isExpression(i)){r.push(ho(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await be(i,t);r.push(s)}return(await Wt(n.node,r,n.context)).returnSource}async function er(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 yd(r,t);if(!o)return null;let i=yo(o,t,{importDepth:t.importDepth+1}),s=xd(r,o);return s?{node:s,context:i}:er(r.importedName,i)}async function Wt(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=yo(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let u=t[l];u&&Ds(c,Qx(u),r)});let o=Gx(e),i=null,s,a=!1;for(let c of o){if(k.isObjectExpression(c)){s={...s??{},...await ld(c,r)},i=i??Us(s,n.file);continue}let l=await be(c,r);if(l){if(!i){i=l;continue}let u=Vs(i,l);if(!u){a=!0,i=null;continue}i=u}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function Ds(e,t,n){if(k.isIdentifier(e)){n.paramSources.set(e.name,ve(t));return}if(k.isAssignmentPattern(e)){Ds(e.left,t,n);return}if(k.isObjectPattern(e))for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isIdentifier(r.key))continue;let o=nr(t,[{kind:"property",name:r.key.name}],!0),i=k.isAssignmentPattern(r.value)?r.value.left:r.value;Ds(i,o,n)}}function Gx(e){if(k.isArrowFunctionExpression(e)&&k.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!k.isBlockStatement(n))return t;let r=o=>{if(k.isFunction(o)&&o!==e)return;if(k.isReturnStatement(o)){o.argument&&k.isExpression(o.argument)&&t.push(o.argument);return}let i=k.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)k.isNode(c)&&r(c);else k.isNode(a)&&r(a)}};return r(n),t}async function ld(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=ud(r);if(!o||!k.isExpression(r.value))continue;let i=await be(r.value,t);i&&(n[o]=i)}return n}function ud(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function Zx(e){let t=[],n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);){let r=n.property;n.computed?k.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):k.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):k.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return k.isIdentifier(n),t}function nr(e,t,n){if(t.length===0)return ve(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return nr(e.fieldMap[r.name],t.slice(1),n);let o=ve(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=qn(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=qn(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=qn(o.fieldPath,i.join(".")),o):(o.valuePath=qn(o.valuePath,Zu(t)),o)}return o.valuePath=qn(o.valuePath,Zu(t)),o}function Zu(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function qn(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function dd(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 bn(e){let t=ve(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function Qx(e){let t=ve(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function tr(e){return e?{...ve(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function Qu(e,t){return e?t?Vs(e,t):ve(e):t?ve(t):null}function Vs(e,t){if(go(e)!==go(t))return null;let n=hd(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function fd(e){let t=new Map;for(let n of e){let r=go(n),o=t.get(r);t.set(r,o?Vs(o,n):ve(n))}return[...t.values()]}function go(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,go(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 Us(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 ho(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Ls(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 pd(e){let t=[...e].sort(md),n=t[0];return{hasDynamicData:t.length>0,sourceKinds:[...new Set(t.map(r=>r.sourceKind))],...n?.endpointPattern?{primaryEndpoint:n.endpointPattern}:{},...n?.collection?{primaryCollection:n.collection}:{},...n?.fieldPath?{primaryFieldPath:n.fieldPath}:{}}}function qx(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 md(e,t){return qu(e.targetKind)-qu(t.targetKind)||hd(e.confidence,t.confidence)||ed(e.sourceKind)-ed(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function qu(e){return{"repeat-region":0,text:1,richtext:2,attribute:3,"component-prop":4}[e]}function ed(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function hd(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function $s(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=Nx(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 js(o,{ImportDeclaration(s){let a=s.node.source.value;for(let c of s.node.specifiers)k.isImportSpecifier(c)&&k.isIdentifier(c.local)?i.imports.set(c.local.name,{source:a,importedName:k.isIdentifier(c.imported)?c.imported.name:c.imported.value,localName:c.local.name,isDefault:!1}):k.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&&(k.isFunctionDeclaration(a.node)||k.isFunctionExpression(a.node)||k.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 In(s.node.id))l.set(u,k.isExpression(s.node.init)?s.node.init:null);if(k.isArrayPattern(s.node.id)&&k.isCallExpression(s.node.init)&&st(s.node.init.callee)==="useState"){let[u,d]=s.node.id.elements;k.isIdentifier(u)&&k.isIdentifier(d)&&i.stateSetters.set(u.name,d.name)}k.isIdentifier(s.node.id)&&td(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(!k.isExportSpecifier(l))continue;let u=k.isIdentifier(l.exported)?l.exported.name:l.exported.value,d=l.local.name;i.imports.set(u,{source:c,importedName:d,localName:u,isDefault:d==="default"})}if(k.isFunctionDeclaration(a)&&a.id?.name&&i.functions.set(a.id.name,a),k.isVariableDeclaration(a))for(let l of a.declarations)k.isIdentifier(l.id)&&td(l.init)&&i.functions.set(l.id.name,l.init)},ExportDefaultDeclaration(s){let a=s.node.declaration;if((k.isFunctionDeclaration(a)||k.isFunctionExpression(a)||k.isArrowFunctionExpression(a))&&i.functions.set("default",a),k.isIdentifier(a)){let c=i.functions.get(a.name);c&&i.functions.set("default",c)}}}),n.set(e,i),i}function In(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?In(t.value):In(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?In(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?In(e.left):k.isRestElement(e)?In(e.argument):[]}function td(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}function gd(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function yd(e,t){let n=await Ed(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return $s(n,r,t.fileCache)}function xd(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Ed(e,t,n){return ct(t)?tn(e,t,n):null}function yo(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 eE(e){return e?ve(e):null}function ve(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,ve(n)]))}:{}}}var tE=50,nE=8*1024*1024;function kd(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??tE),s=Math.max(0,t.maxUndoBytes??nE);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(R){let _=[...R.steps].sort((W,q)=>W.order-q.order),D=_.filter(W=>W.type!=="invoke-external-adapter");if(D.length!==_.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let L=new Set(D.map(W=>W.file)),Z=await A(L),Q=new Map(Z.map(W=>[W.file,W.exists===!1?"":W.content])),he;for(let W of D){let q=Id(W,Q.get(W.file)??"");if(!q.ok)return{ok:!1,errorCode:q.errorCode,reason:q.reason};Q.set(W.file,q.source),he=q.selectionRef??he}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...Q].map(([W,q])=>({operation:"upsert",file:W,content:q,baseContentHash:Z.find(ge=>ge.file===W)?.sha256??null}))},...he?{selectionRef:he}:{}}}async function c(R){let _=[...R.steps].sort((ge,at)=>ge.order-at.order),D=_.filter(ge=>ge.type!=="invoke-external-adapter"),L=_.filter(ge=>ge.type==="invoke-external-adapter"),Z=new Set(D.map(ge=>ge.file));if(D.length>0&&L.length>0)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(D.length===0)return v(R,L);let Q=await A(Z),he=new Map;for(let ge of Q)he.set(ge.file,ge.exists===!1?"":ge.content);let W;for(let ge of D){let at=he.get(ge.file)??"",ht=Id(ge,at);if(!ht.ok)return{ok:!1,operationId:R.operationId,errorCode:ht.errorCode,reason:ht.reason,rolledBack:!1};he.set(ge.file,ht.source),ht.selectionRef&&(W=ht.selectionRef)}let q=await G([...he].map(([ge,at])=>({file:ge,content:at,exists:!0,version:0,sha256:ae(at)})),Q);return q.ok===!1?{ok:!1,operationId:R.operationId,errorCode:q.rolledBack?"writeback-failed":"rollback-failed",reason:q.reason,rolledBack:q.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:Q,postSnapshots:q.snapshots,plan:R}),p(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...q.snapshots.map(ge=>ge.version)),affectedFiles:[...Z],...W?{selectionRef:W}:{}})}async function l(R){let _=new Set(R.edits.map(q=>q.file)),D=await A(_),L=C(R,D);if(L)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:L.reason,affectedFiles:[L.file],rolledBack:!1};let Z=new Map(D.map(q=>[q.file,q])),Q=R.edits.find(q=>q.operation==="create-only"&&Z.get(q.file)?.exists!==!1);if(Q)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${Q.file}`,affectedFiles:[Q.file],rolledBack:!1};let he=R.edits.map(q=>q.operation==="delete"?{file:q.file,content:"",exists:!1,version:0}:{file:q.file,content:q.content,exists:!0,version:0,sha256:ae(q.content)}),W=await G(he,D,new Set(R.edits.filter(q=>q.operation==="create-only").map(q=>q.file)));return W.ok===!1?{ok:!1,operationId:R.operationId,errorCode:W.rolledBack?"writeback-failed":"rollback-failed",reason:W.reason,rolledBack:W.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:D,postSnapshots:W.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:D}}),p(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...W.snapshots.map(q=>q.version)),affectedFiles:[..._]})}async function u(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let _=await G(R.preSnapshots,R.postSnapshots);return _.ok===!1?{ok:!1,operationId:R.operationId,errorCode:_.rolledBack?"writeback-failed":"rollback-failed",reason:_.reason,rolledBack:_.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(..._.snapshots.map(D=>D.version)),affectedFiles:R.preSnapshots.map(D=>D.file)})}async function d(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let _=await G(R.postSnapshots,R.preSnapshots);return _.ok===!1?{ok:!1,operationId:R.operationId,errorCode:_.rolledBack?"writeback-failed":"rollback-failed",reason:_.reason,rolledBack:_.rolledBack}:(r.pop(),n.push(R),p(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(..._.snapshots.map(D=>D.version)),affectedFiles:R.postSnapshots.map(D=>D.file)})}function p(){for(;n.length>i;)n.shift();for(;n.length>0&&m()>s;)n.shift()}function m(){return n.reduce((R,_)=>R+E(_),0)}function E(R){return b(R.preSnapshots)+b(R.postSnapshots)}function b(R){return R.reduce((_,D)=>_+D.file.length+D.content.length,0)}async function v(R,_){let D=[];for(let L of _){let Z=L.capability??"write-text",Q=o.find(W=>W.sourceType===L.sourceType&&(L.adapterId===void 0||W.adapterId===L.adapterId)&&(W.capabilities===void 0||W.capabilities.includes(Z)));if(!Q)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${L.sourceType}`,rolledBack:!1};let he=await Q.execute(L);if(!he.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:he.reason??`External adapter failed for ${L.sourceType}`,rolledBack:!1};D.push(L.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:D}}function C(R,_){if(R.conflictPolicy!=="compare-and-swap")return null;let D=new Map(_.map(L=>[L.file,L]));for(let L of R.edits){if(L.operation==="create-only")continue;if(L.baseContentHash===void 0)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};let Z=D.get(L.file),Q=L.baseContentHash;if(Q===null){if(Z?.exists!==!1)return{file:L.file,reason:`Source file ${L.file} was created or changed before save.`};continue}if(!Q)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};if(Z?.exists===!1||Z?.sha256!==Q)return{file:L.file,reason:`Source file ${L.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function A(R){let _=[];for(let D of R)_.push(await N(D));return _}async function N(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let D=Math.max(1,e.getVersion(R)),L=await e.readFile(R);return{file:R,content:L,version:D,exists:!0,sha256:ae(L)}}async function G(R,_,D=new Set){let L=[];try{for(let Z of R){if(D.has(Z.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(Z.file,Z.content)}else await fe(Z);let Q=e.bumpVersion(Z.file);L.push(Z.file),Z.version=Q}}catch(Z){let Q=await ue(_.filter(W=>L.includes(W.file)));if(Q.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${Q.failedFiles.join(", ")}: ${bd(Z)}`,rolledBack:!1,instanceConflict:Sd(Z)};let he=Sd(Z);return{ok:!1,reason:`${he?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${bd(Z)}`,rolledBack:!0,instanceConflict:he}}return{ok:!0,snapshots:R.map(rE)}}async function fe(R){if(R.exists===!1){await e.deleteFile(R.file);return}await e.writeFile(R.file,R.content)}async function ue(R){let _=[];for(let D of R)try{await fe(D),e.bumpVersion(D.file)}catch{_.push(D.file)}return _.length===0?{ok:!0}:{ok:!1,failedFiles:_}}}function Sd(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function rE(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ae(e.content)}:{}}}function bd(e){return e instanceof Error?e.message:String(e)}function Id(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 Ne(pn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return Ne(mn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return Ne(cn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return Ne(un({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return Ne(Vr({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return Ne(Ln({source:t,locator:e.locator,next:e.value}));case"update-array-item":return Ne(Ln({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return Ne(Jr({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return Ne(Ur({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return Ne(Xr({source:t,locator:e.locator,index:e.index}));case"move-array-item":return Ne(Hr({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return Ne(fn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return Ne($r({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 oE(e,t);case"set-props":{let n=e;return Ne(Kr({source:t,locator:n.locator,props:n.props}))}default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function oE(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!El(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};let r=n.oldAttrRange!==null&&n.oldAttrRaw!==null,o=n.openingElementRange.start,i=n.openingElementRange.end,s=t.slice(o,i);if(!(Number.isInteger(o)&&Number.isInteger(i)&&o>=0&&i>o&&i<=t.length&&s.startsWith("<")&&s.endsWith(">")&&!s.startsWith("</")&&(n.oldAttrRange===null||n.oldAttrRange.start>=o&&n.oldAttrRange.end<=i)))return{ok:!1,reason:"The opening element range changed before className save.",errorCode:"stale-version"};if(!r&&n.expectedVersion.contentHash!==ae(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:xl({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function Ne(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"}}}function vd(){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 iE}from"node:crypto";import xo from"node:fs/promises";import Ks from"node:path";var sE={async mkdir(e,t){await xo.mkdir(e,t)},async writeFile(e,t,n){await xo.writeFile(e,t,n)},async rename(e,t){await xo.rename(e,t)},async rm(e,t){await xo.rm(e,t)}};async function Eo(e,t,n=sE){let r=Ks.dirname(e),o=Ks.basename(e),i=Ks.join(r,`.${o}.${process.pid}.${iE()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await n.rename(i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import{randomBytes as SE}from"node:crypto";import rr from"node:path";import{parse as bE}from"@babel/parser";import IE from"@babel/traverse";import{SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Rd,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as kE,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as vE,SiteEditMaterializationSchema as CE}from"@vcp-dev/contracts";var Cd=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,aE=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,cE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,lE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,uE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,dE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,fE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,pE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,mE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,hE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,gE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,yE=/\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,xE=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,EE=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Js(e,t){let n=So([...$e(e,cE),...$e(e,lE),...$e(e,uE),...$e(e,t.includeRgbBackgroundImage?dE:fE),...t.includeExtendedColorFunctions?[...$e(e,pE),...$e(e,mE)]:[]]),r=So([...$e(e,hE),...$e(e,gE)]).filter(o=>t.colorMixPolicy==="always"||Cd.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...$e(e,yE).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...$e(e,EE).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:So($e(e,aE)),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?So($e(e,xE)):[]}}function $e(e,t){return e.match(new RegExp(t.source,t.flags))??[]}function So(e){return[...new Set(e)]}var Ws="components/site/generated",Pd="{{$INSTANCE}}",bo=5,RE=/^[a-z][a-z0-9-]{0,48}$/,PE=/^[a-f0-9]{8}$/,wE=/\.tsx?$/,AE=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,NE=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Xs=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Hs=IE,TE=typeof Hs=="function"?Hs:Hs.default;function FE(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Rd)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=$E(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=CE.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=BE(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Ws}.`,path:e.generatedRoot}};if(!Md(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=Nd(r.data.files),s=Nd(e.controlledFiles);if(!KE(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Rd)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>kE)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>vE?{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 ME(e){let t=FE(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=Md(e.manifest.instanceBaseName),o=Math.max(1,Math.min(bo,e.maxAttempts??bo));for(let i=0;i<o;i+=1){let s=VE(e.instanceNameGenerator?.()??SE(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=_d(n,a),l=OE({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,allowedExternalImports:e.allowedExternalImports??NE});if(!l.ok)return l;if(!await _E(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(bo,e.maxAttempts??bo));for(let n=0;n<t;n+=1){let r=await ME({...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 OE(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=wd({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=wd({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=DE(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 _E(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function wd(e){if(e.pathTemplate.split(Pd).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(Pd,e.instanceName),n=UE(t);return n?_d(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||!wE.test(n)||AE.test(n)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab files must be .ts/.tsx source files and cannot be config, layout, provider, or global 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 DE(e,t,n,r,o){let i=new Set(e.map(u=>u.path)),s=new Map,a=new Map;for(let u of e){let d;try{d=bE(u.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:u.path}}}let p=Js(u.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(p.hardCodedSurfaceHits.length>0||p.rawColorHits.length>0||p.privateTokenHits.length>0)return{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:u.path}};s.set(u.path,d),a.set(u.path,new Set)}for(let u of e){let d=s.get(u.path),p=null;if(TE(d,{ImportDeclaration(m){let E=Ad({importer:u.path,source:m.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});E.allowed?E.internalPath&&a.get(u.path).add(E.internalPath):(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:u.path},m.stop())},ExportAllDeclaration(m){p??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:u.path},m.stop()},ExportNamedDeclaration(m){if(m.node.source){let E=Ad({importer:u.path,source:m.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!E.allowed||!E.internalPath?(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:u.path},m.stop()):a.get(u.path).add(E.internalPath)}},CallExpression(m){if(m.node.callee.type==="Import"){p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:u.path},m.stop();return}m.node.callee.type==="Identifier"&&m.node.callee.name==="require"&&(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:u.path},m.stop())},NewExpression(m){m.node.callee.type==="Identifier"&&m.node.callee.name==="Function"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:u.path},m.stop())},MetaProperty(m){m.node.meta.type==="Identifier"&&m.node.meta.name==="import"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:u.path},m.stop())},MemberExpression(m){let E=Td(m.node);E&&Xs.has(E)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${E}.`,file:u.path},m.stop())},OptionalMemberExpression(m){let E=Td(m.node);E&&Xs.has(E)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${E}.`,file:u.path},m.stop())},Identifier(m){m.isReferencedIdentifier()&&Xs.has(m.node.name)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${m.node.name}.`,file:u.path},m.stop())},JSXAttribute(m){m.node.name.type==="JSXIdentifier"&&m.node.name.name==="style"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:u.path},m.stop())},JSXOpeningElement(m){m.node.name.type==="JSXIdentifier"&&m.node.name.name.toLowerCase()==="style"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:u.path},m.stop())}}),p)return{ok:!1,error:p}}let c=s.get(n);return c?LE(c,r)?jE(n,a).size!==e.length?zs("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:Ws,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}:zs("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n):zs("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n)}function Ad(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=rr.posix.normalize(rr.posix.join(rr.posix.dirname(e.importer),e.source));if(t===e.instanceRoot||!t.startsWith(`${e.instanceRoot}/`))return{allowed:!1};let r=[t,`${t}.ts`,`${t}.tsx`,...["ts","tsx"].map(o=>`${t}/index.${o}`)].find(o=>e.filePaths.has(o));return r?{allowed:!0,internalPath:r}:{allowed:!1}}function LE(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 jE(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 zs(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function BE(e){let t=Od(e);return t===Ws?t:null}function VE(e){let t=e.trim().toLowerCase();return PE.test(t)?t:null}function Md(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 RE.test(t)?t:null}function Od(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=rr.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function UE(e){let t=Od(e);return!t||t!==e?null:t}function _d(...e){return rr.posix.join(...e)}function Nd(e){return new Set(e.map(t=>t.pathTemplate))}function $E(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 KE(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Td(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}}function Vd(e){let t=null,n=new WeakMap;async function r(){return t??=JE(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(Bd(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);Dd(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(Dd(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(Bd(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 Dd(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 JE(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>Ld(e,o))),r=await Promise.all(t.redoIds.map(async o=>Ld(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function Ld(e,t){let n=await e.readEntry(t),r=XE(n);return{historyId:t,operationId:r.operationId,kind:r.kind,target:r.target,...r.selectionRef?{selectionRef:r.selectionRef}:{},preSnapshots:await jd(e,n,r.preSnapshots),postSnapshots:await jd(e,n,r.postSnapshots)}}async function jd(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(HE(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Bd(e){let t=[],n=(o,i)=>o.map((s,a)=>{let c={file:s.file,exists:s.exists!==!1,version:s.version,...s.sha256?{sha256:s.sha256}:{}};if(c.exists){let l=`${i}-${a}`;c.blobName=l,t.push({name:l,data:s.content})}return c}),r={operationId:e.operationId,kind:e.kind,target:e.target,...e.selectionRef?{selectionRef:e.selectionRef}:{},preSnapshots:n(e.preSnapshots,"pre"),postSnapshots:n(e.postSnapshots,"post")};return{kind:"site-edit-operation",manifest:JSON.parse(JSON.stringify(r)),blobs:t}}function XE(e){if(!zE(e.manifest))throw new Error("durable history manifest is not an object");return e.manifest}function HE(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function zE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import Ud from"node:path";function Gs(){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 Kd(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=ZE(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 Io(e){let t=()=>WE(e);return e.mutex?e.mutex.runExclusive(t):t()}async function WE(e){let t=await Kd(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=YE(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 Ys({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 Ys({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 Ys({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 $d("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return $d("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 YE(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 Ys(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:GE(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 $d(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function GE(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 ZE(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)||Ud.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Ud.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}}function Zs(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function kn(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Qs(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function qs(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 Jd(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function QE(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var or=class extends Error{constructor(t){let n=t.map(Jd);super(QE(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Xd(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof or?{routeId:e,message:n,diagnostics:t.diagnostics.map(Jd)}:{routeId:e,message:n}}function ea(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Hd(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 iS=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,sS=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],zd=32,Wd=256,Yd={maxEntries:50,maxBytes:8*1024*1024};function aS(){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 Eo(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 cS(){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>Yd.maxEntries||lS(e)>Yd.maxBytes;)e.shift()}}function lS(e){return e.reduce((t,n)=>t+uS(n),0)}function uS(e){return Gd(e.preSnapshots)+Gd(e.postSnapshots)}function Gd(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function Zd(e,t){return{routeId:e,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}}function dS(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Ke(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}}var Co=class extends Error{constructor(t){super(t.reason),this.result=t}},Yt=class extends Error{constructor(t){super(ea(t)),this.failedRoutes=t}};function Qd(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=Ke(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(Ke(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}var fS=/\.(?:[cm]?[jt]sx?)$/i,pS=/\.json$/i,mS=/\.(?:css|scss|sass)$/i,hS=/\.mdx$/i,gS=/\.ya?ml$/i;function yS(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 xS(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function ES(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=bS(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(SS(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 SS(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function bS(e){return Array.isArray(e)?{files:e}:e}function IS(e){if(!tS(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!==rS||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=eS(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(fS.test(e.path)){let t=rt({source:e.content,profile:Dt({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(pS.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${_e(t)}`,details:{path:e.path}}}if(mS.test(e.path)){let t=qd({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(hS.test(e.path)){let t=qd({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(gS.test(e.path))try{oS(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${_e(t)}`,details:{path:e.path}}}return{ok:!0}}function qd({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let d=0;d<e.length;d+=1){let p=e[d]??"",m=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let E=e.indexOf(`
5
+ `,d);if(E===-1){l=!0;break}d=E,l=!0;continue}if(c){l=p===`
6
+ `||p==="\r";continue}if(s){p==="*"&&m==="/"&&(s=!1,d+=1),l=p===`
7
7
  `||p==="\r";continue}if(a){p===`
8
8
  `||p==="\r"?(a=!1,l=!0):l=!1;continue}if(o){if(i)i=!1;else if(p==="\\")i=!0;else if(p===o)o=null;else if(n==="css"&&(p===`
9
- `||p==="\r"))return bn(t,`Unterminated string literal in ${t}.`);l=p===`
10
- `||p==="\r";continue}if(p==="/"&&m==="*"){s=!0,f+=1,l=!1;continue}if(n==="mdx"&&p==="/"&&m==="/"){a=!0,f+=1,l=!1;continue}if(p==="'"||p==='"'||n==="mdx"&&p==="`"){o=p,l=!1;continue}if(p==="{"||p==="("||p==="["){r.push({char:p,offset:f}),l=!1;continue}if(p==="}"||p===")"||p==="]"){let S=p==="}"?"{":p===")"?"(":"[",I=r.pop();if(!I||I.char!==S)return bn(t,`Unexpected closing token "${p}" in ${t}.`);l=!1;continue}l=p===`
11
- `||p==="\r"}if(s)return bn(t,`Unterminated block comment in ${t}.`);if(o)return bn(t,`Unterminated string literal in ${t}.`);if(c)return bn(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?bn(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function bn(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function rr(e){let t="idle",n=e.fileSystem??ZS(),r=zd(),o=new Map,i=new Map,s=null,a=new Set,c=null,l=e.history??(e.historyStore?uf(e.historyStore):QS()),u=Wd(n,{externalAdapters:e.externalAdapters}),f=new Map,p=Math.max(0,e.initialDocumentVersion??0),m=0,S=e.historyStore?.recoveryRequired??!1,I=ra(),v=G();function C(d){return(So.isAbsolute(d)?So.relative(e.projectRoot,d):d).replace(/\\/g,"/").replace(/^\.\//,"")}function A(d,g){let h=So.posix.dirname(d),b=g.replace(/\.(?:tsx?|jsx?)$/i,""),w=So.posix.relative(h,b);return w.startsWith(".")?w:`./${w}`}function T(d,g){return d.startLine===g.startLine&&d.startColumn===g.startColumn&&d.endLine===g.endLine&&d.endColumn===g.endColumn}async function G(){let d=e.historyStore;if(d)try{let g=await d.readTransactionJournal();if(!g)return;let h=await d.readIndex(),b=await Promise.all(g.files.map(async N=>await n.exists(N.path)?ae(await n.readFile(N.path)):null));if(gf({journal:g,index:h,observedFileDigests:b})!=="ambiguous"){await d.clearTransactionJournal(g.transactionId);let N=await d.readStatus();N.recoveryRequired||(await d.cleanupTmp(),N=await d.readStatus()),S=N.recoveryRequired;return}await d.markRecoveryRequired(`Ambiguous transaction journal ${g.transactionId} at phase ${g.phase}`),S=!0}catch(g){S=!0,await d.markRecoveryRequired(`Transaction journal recovery failed: ${Me(g)}`).catch(()=>{})}}function fe(){return t==="disposed"}if(e.onEvent&&r.subscribe(e.onEvent),e.routes)for(let d of e.routes){let g=bf(d.routeId,d.entryFile);o.set(d.routeId,g),ue(g,g.dependencyFiles)}function ue(d,g){let h=new Set(g);R(d),d.dependencyFiles=h;for(let b of d.dependencyFiles){let w=i.get(b);w||(w=new Set,i.set(b,w)),w.add(d.routeId)}}function R(d){for(let g of d.dependencyFiles){let h=i.get(g);h&&(h.delete(d.routeId),h.size===0&&i.delete(g))}d.dependencyFiles.clear()}function _(d){let g=new Set;for(let h of d)for(let b of i.get(h)??[])g.add(b);return g}function D(d){for(let g of d)if(!i.has(g))return!1;return!0}async function L(d,g,h,b,w){let N=new Map,j=td(w.values()),M=new Map,F=typeof n.exists=="function"?B=>n.exists(B):async()=>!1;for(let[B,X]of d.elements){let Y=g.nodes.get(B);if(!Y)continue;let ee=h.get(X.sourceFile)??b.get(X.sourceFile),P=new Map,O=new Map,z=new Map,pe=[];for(let de of X.textSegments){if(!ee){P.set(de.index,null);continue}let Cn=await nd({file:X.sourceFile,source:ee,segment:de,readFile:Je=>n.readFile(Je),exists:F,graph:d,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Je,adapterId:Jo,capabilities:Xo})=>({sourceType:Je,adapterId:Jo,capabilities:Xo})),functionCallContracts:e.functionCallContracts,fileCache:j}),ke=await Ns({file:X.sourceFile,source:ee,target:{kind:"text-segment",segment:de},readFile:Je=>n.readFile(Je),exists:F,graph:d,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Je,adapterId:Jo,capabilities:Xo})=>({sourceType:Je,adapterId:Jo,capabilities:Xo})),functionCallContracts:e.functionCallContracts,fileCache:j}),Gt=ab(Cn);P.set(de.index,Gt),O.set(de.index,Cn),z.set(de.index,ke),pe.push({editable:de.editable,source:Gt})}let se=new Map;if(ee)for(let de of X.attributes??[]){let Cn=await rd({file:X.sourceFile,source:ee,sourceRange:de.sourceRange,expression:de.source?.expression??de.value,sourceInfo:de.source,readFile:ke=>n.readFile(ke),exists:F,graph:d,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ke,adapterId:Gt,capabilities:Je})=>({sourceType:ke,adapterId:Gt,capabilities:Je})),functionCallContracts:e.functionCallContracts,fileCache:j});se.set(de.name,Cn)}let ye=hl(cb(Y.writeTarget),pe),mr=Sl({key:B,element:X,graph:d,provenances:z}),Re=vl(X),hr=Cl(X),gr=Bl(X),Yt=ee?await Nd({element:X,graph:d,file:X.sourceFile,source:ee,readFile:de=>n.readFile(de),exists:F,fileCache:M}):void 0,Nt=d.regions.find(de=>de.kind==="conditional-region"&&de.childKeys.includes(B)),Te,vn=Nt?.sourceCandidates?.[0];if(ee&&Nt&&vn?.kind==="conditional-branch"){let de=await Ns({file:X.sourceFile,source:ee,target:{kind:"conditional-branch",candidate:vn},readFile:ke=>n.readFile(ke),exists:F,graph:d,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ke,adapterId:Gt,capabilities:Je})=>({sourceType:ke,adapterId:Gt,capabilities:Je})),functionCallContracts:e.functionCallContracts,fileCache:j});Te={currentBranch:Nt.childKeys.indexOf(B)<=0?"then":"else",availableBranches:Nt.childKeys.length>1?["then","else"]:["then"],conditionExpression:vn.conditionExpression,provenance:{finalSource:de.finalSource?{kind:de.finalSource.kind,file:de.finalSource.file,displayPath:de.finalSource.displayPath}:null,chain:de.chain.map(ke=>({kind:ke.kind,file:ke.file,displayName:ke.displayName,canEditHere:ke.canEditHere})),confidence:de.confidence,editMode:de.editMode,diagnostics:de.diagnostics.map(ke=>({code:ke.code,message:ke.message}))}}}N.set(B,{textSources:P,textTargets:O,elementPropertyTargets:se,provenances:z,writeTarget:ye,componentSemantic:mr,contentModel:Re,mediaModel:hr,styleSource:gr,conditional:Te,dynamicData:Yt})}return N}function Z(d){return typeof n.getVersion=="function"?n.getVersion(d):0}function Q(d,g){let h=1;for(let b of g.values())h=Math.max(h,b);return Math.max(h,d.graph?.version??0)}async function me(d,g,h={}){let b=o.get(d);if(!b)return null;let w=h.sourceCache??oa(f,[]),N=await H(b.entryFile),{graph:j,allSources:M,diagnostics:F,parsedModules:B,entryModule:X}=await dc(b.entryFile,g,Te=>n.readFile(Te),typeof n.exists=="function"?Te=>n.exists(Te):async()=>!1,{additionalEntries:N,version:b.graph?.version??1});if(F.length>0)throw new tr(F);let Y=new Map;for(let Te of M.keys())Y.set(Te,Z(Te));let ee=Math.max(Q(b,Y),h.minimumVersion??0,p);h.changed&&ee<=(b.graph?.version??0)&&(ee=(b.graph?.version??0)+1),j.version=ee;for(let[Te,vn]of M)sa(w,Te,vn,xf);let P=await q(b.entryFile,M,w);j.routeId=d;let O=fc(j),z=mc(O,j),pe=await L(j,O,M,w,B),se=rp(j,z,pe),ye=mt(pe),mr=kb(ul(j,O,z,{canUpdateTextByKey:se,dynamicDataSummaryByKey:ye}),j,pe),Re=nl({route:d,entryFile:b.entryFile,version:ee,source:g,ast:X?.ast}),hr=rl(Re);Re.ok&&pb(mr,j,Re.projection);let gr={...mr,...P?{styleContext:P}:{},pageComposition:hr},Yt=new Set([b.entryFile,...M.keys()]);if(P){Yt.add(P.entryCss.path);for(let Te of P.stylesheets)Yt.add(Te.path)}let Nt={...b,dependencyFiles:Yt,graph:j,topology:O,capabilities:z,document:gr,pageComposition:hr,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:tb(gr),detailProjections:pe,fileVersions:Y,styleContext:P};return h.publish===!1?Nt:(Sn(f,w),p=Math.max(p,ee),ue(b,Yt),Object.assign(b,Nt),b)}async function H(d){let g=[];for(let h of yb(d))typeof n.exists=="function"&&await n.exists(h)&&g.push({file:h,source:await n.readFile(h)});return g}async function q(d,g,h){let b=[];for(let[F,B]of g){if(la(F)){b.push(F);continue}for(let X of Eb(B)){let Y=Rf(F,X);Y&&b.push(Y)}}if(!b.length){for(let F of xb(d))if(await st(F)){b.push(F);break}}let w=new Map,N=Tf(b).slice(0,yf);for(;N.length>0&&w.size<yf;){let F=N.shift();if(w.has(F)||!la(F))continue;let B=await he(F,h);if(B!==null){w.set(F,{path:F,content:B});for(let X of Sb(B)){let Y=Rf(F,X);Y&&!w.has(Y)&&!N.includes(Y)&&N.push(Y)}}}let j=[...w.values()].map(F=>({...F,hash:ae(F.content)})),M=j[0];return M?{revision:ae(JSON.stringify(j.map(({path:F,hash:B})=>({path:F,hash:B})))),entryCss:M,stylesheets:j.slice(1)}:null}async function he(d,g){let h=g.get(d);if(h!==void 0)return h;if(!await st(d))return null;let b=await n.readFile(d);return sa(g,d,b,xf),b}async function st(d){return typeof n.exists=="function"?n.exists(d):!1}function mt(d){let g=new Map;for(let[h,b]of d)b.dynamicData?.bindings.length&&g.set(h,Ld(b.dynamicData.bindings));return g}function rp(d,g,h){let b=new Map;for(let[w,N]of d.elements){if(!g.get(w)?.canUpdateText){b.set(w,!1);continue}let M=h.get(w),F=N.textSegments.some(B=>{if(!B.editable)return!1;let X=M?.provenances.get(B.index)??null;return!X||op(X)});b.set(w,F)}return b}function op(d){return d.editMode==="direct"||d.editMode==="proxy"||d.editMode==="upstream"}async function ur(d,g={}){let h=[...new Set(d)],b=_(h);if(b.size===0||!D(h))for(let M of o.values())La(M,h)&&b.add(M.routeId);let w=b.size===0&&h.some(Cf),N=g.publish===!1?oa(f,h):void 0,j={rebuiltRoutes:[],failedRoutes:[],...g.publish===!1?{candidateRouteStates:[],candidateSourceCache:N}:{}};for(let M of o.values())if(b.has(M.routeId)||w)try{let B=!!M.graph,X=await n.readFile(M.entryFile),Y=await me(M.routeId,X,{...g,...N?{sourceCache:N}:{}});Y?.graph&&(j.rebuiltRoutes.push({documentChanged:B,routeId:M.routeId,version:Y.graph.version}),j.candidateRouteStates?.push({routeId:M.routeId,state:Y}))}catch(B){j.failedRoutes.push(hf(M.routeId,B))}return j}function Da(d){let g=[...new Set(d)],h=_(g);if(h.size>0&&D(g))return[...h];for(let b of o.values())La(b,g)&&h.add(b.routeId);return[...h]}function jo(d,g){r.emit({type:"operation-completed",result:d});for(let{routeId:h,version:b}of g.rebuiltRoutes)r.emit({type:"document-changed",routeId:h,version:b});for(let{routeId:h,message:b}of g.failedRoutes)r.emit({type:"graph-error",routeId:h,message:b})}function La(d,g){return g.some(h=>d.dependencyFiles.has(h)||d.entryFile===h||d.graph?.fileIndex.has(h))}function ja(d){for(let g of d)a.add(g);c||fe()||(c=(async()=>{t="building";let g=!1;try{for(;a.size>0;){if(fe())return;await ip();let h=[...a];a.clear();let b=await $a(h);if(b.length===0)continue;let w=Da(b);for(let M of w)r.emit({type:"graph-invalidated",routeId:M});let{rebuiltRoutes:N,failedRoutes:j}=await ur(b,{changed:!0});for(let{documentChanged:M,routeId:F,version:B}of N)r.emit({type:"graph-ready",routeId:F,version:B}),M&&r.emit({type:"document-changed",routeId:F,version:B});for(let{routeId:M,message:F}of j)g=!0,r.emit({type:"graph-error",routeId:M,message:F})}}finally{if(c=null,t!=="disposed"){let h=s?o.get(s):null;t=!g&&h?.graph?"ready":"idle"}a.size>0&&ja([])}})())}async function ip(){for(;m>0;)await new Promise(d=>setTimeout(d,0))}async function $a(d){let g=[];for(let h of new Set(d)){let b=f.get(h);if(b===void 0){g.push(h);continue}try{await n.readFile(h)!==b&&g.push(h)}catch{g.push(h)}}return g}async function Ba(d){let g=await $a(d);if(g.length===0)return;let h=Da(g);for(let N of h)r.emit({type:"graph-invalidated",routeId:N});let{rebuiltRoutes:b,failedRoutes:w}=await ur(g,{changed:!0});for(let{documentChanged:N,routeId:j,version:M}of b)r.emit({type:"graph-ready",routeId:j,version:M}),N&&r.emit({type:"document-changed",routeId:j,version:M});for(let{routeId:N,message:j}of w)r.emit({type:"graph-error",routeId:N,message:j})}async function sp(d,g){let h=kn(d,g);if(!h?.graph)return;let b=Ke(d)??d,w=h.graph.elements.get(b);w&&await Ba([w.sourceFile])}async function Ka(d){let g=new Set;if(d.target.kind==="node"){let h=kn(d.target.key,d.routeId),b=Ke(d.target.key)??d.target.key,w=h?.graph?.elements.get(b);w&&g.add(w.sourceFile)}else if(d.target.kind==="route"){let h=o.get(d.target.routeId);h&&g.add(h.entryFile)}else if(d.target.kind==="page-unit"){let h=o.get(d.target.routeId);h&&g.add(h.entryFile)}else if(d.target.kind==="source-file")g.add(d.target.path);else if(d.target.kind==="source-batch")for(let h of d.target.paths)g.add(h);await Ba(g)}async function ap(d){if(d.params.kind!=="source-edit")return $o(d,"invalid-params","source-edit requires source-edit params");for(let g of d.params.edits){let h=fb(g);if(!h.ok)return $o(d,h.errorCode,h.message,h.details)}m+=1;try{let g=await dp(d.params.edits);if(!g.ok)return $o(d,g.errorCode,g.message,g.details);let h={operationId:d.id,kind:"source-edit",target:d.target,documentVersion:d.documentVersion,conflictPolicy:d.params.conflictPolicy,edits:d.params.edits.map(b=>b.operation==="delete"?{operation:"delete",file:b.path,baseContentHash:b.baseContentHash??null}:{operation:"upsert",file:b.path,baseContentHash:b.baseContentHash??null,content:b.content})};return await dr({request:d,filePlan:h})}catch(g){return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:$.INTERNAL_ERROR,message:Me(g)}}}finally{m-=1}}async function cp(d,g){if(d.kind!=="insert-child"||d.params.kind!=="insert-child")return oe(d,$.UNSUPPORTED_OPERATION,"Only page-unit insert-child is currently supported by the page composition transaction.");if(!("kind"in d.params.position)||d.params.position.kind!=="page-composition")return oe(d,$.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(d.params.position.documentVersion!==d.documentVersion)return oe(d,$.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.");let h=g.document,b=g.pageCompositionProjection;if(!h||h.pageComposition?.status!=="supported"||!b||b.status!=="supported")return oe(d,$.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(d.documentVersion!==h.version||b.documentVersion!==h.version)return oe(d,$.VERSION_STALE,`Document version ${d.documentVersion} is stale (current: ${h.version}).`);let w=d.params.node.kind==="component-call"?d.params.node.materialization:void 0;if(!w)return oe(d,$.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let N=d.params.position,j=await tf({manifest:w,generatedRoot:"components/site/generated",controlledFiles:w.files.map(M=>({pathTemplate:M.pathTemplate})),exists:M=>n.exists(M),commit:async M=>{let F=await n.readFile(g.entryFile),B=g.document,X=g.pageCompositionProjection;if(!B||B.pageComposition?.status!=="supported"||B.version!==d.documentVersion||!X||X.status!=="supported"||X.documentVersion!==B.version)return{ok:!0,data:oe(d,$.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Y=M.entry.path,ee=xp(M.instanceName),P=Ii({routeId:g.routeId,entryFile:g.entryFile,currentDocumentVersion:B.version,expectedDocumentVersion:d.documentVersion,source:F,projection:X,placementKey:N.placementKey,component:{source:Y,exportName:M.entry.export.kind==="default"?"default":M.entry.export.name,localName:ee}});if(!P.ok)return{ok:!0,data:oe(d,Ya(P.error.code),P.error.message,{diagnostics:P.error.diagnostics})};let O=P.plan.returnStep?Zc({source:F,jsx:P.plan.returnStep.node.jsx,placement:P.plan.returnStep.placement,...P.plan.returnStep.replaceOriginal?{replaceOriginal:!0}:{}}):P.plan.insertStep?.parentLocator?sn({source:F,locator:P.plan.insertStep.parentLocator,node:P.plan.insertStep.node,placement:P.plan.insertStep.placement,...P.plan.insertStep.anchorLocator?{anchorLocator:P.plan.insertStep.anchorLocator}:{}}):{ok:!1,source:F,diagnostic:{code:"unsupported-syntax",message:"Route composition rewrite has no insertion step."}};if(!O.ok)return{ok:!0,data:oe(d,$.AST_PARSE_ERROR,O.diagnostic.message)};let z=ln({source:O.source,moduleSpecifier:P.plan.importStep.moduleSpecifier,imports:P.plan.importStep.imports});if(!z.ok)return{ok:!0,data:oe(d,$.AST_PARSE_ERROR,z.diagnostic.message)};let pe=M.files.map(ye=>({operation:"create-only",file:ye.path,content:ye.content})),se=[{operation:"upsert",file:g.entryFile,content:z.source,baseContentHash:ae(F)},...pe];m+=1;try{let ye=await dr({request:d,filePlan:{operationId:d.id,kind:"source-edit",target:{kind:"source-file",path:g.entryFile},documentVersion:d.documentVersion,conflictPolicy:"compare-and-swap",edits:se}});return!ye.ok&&ye.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:ye.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:ye}}finally{m-=1}}});return j.ok?j.data:oe(d,$.VERSION_STALE,j.error.message,{materializationCode:j.error.code})}async function lp(d,g){if(d.kind!=="move-node"&&d.kind!=="remove-node")return oe(d,$.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let h=g.document,b=g.pageCompositionProjection;if(!h||h.pageComposition?.status!=="supported"||!b||b.status!=="supported")return oe(d,$.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(d.documentVersion!==h.version||b.documentVersion!==h.version)return oe(d,$.VERSION_STALE,`Document version ${d.documentVersion} is stale (current: ${h.version}).`);let w=await n.readFile(g.entryFile),N=Qc({routeId:g.routeId,entryFile:g.entryFile,currentDocumentVersion:h.version,expectedDocumentVersion:d.documentVersion,source:w,projection:b,placementUnitKey:d.target.placementUnitKey,operation:d.kind,targetPlacement:d.kind==="move-node"&&d.params.kind==="move-node"&&"kind"in d.params.target&&d.params.target.kind==="page-composition"?d.params.target:void 0});if(!N.ok)return oe(d,Ya(N.error.code),N.error.message,{diagnostics:N.error.diagnostics});let j=N.plan.rewriteStep.kind==="move-node"?cn({source:w,locator:N.plan.rewriteStep.locator,targetParentLocator:N.plan.rewriteStep.targetParentLocator,placement:N.plan.rewriteStep.placement,...N.plan.rewriteStep.anchorLocator?{anchorLocator:N.plan.rewriteStep.anchorLocator}:{}}):rn({source:w,locator:N.plan.rewriteStep.locator});if(!j.ok)return oe(d,$.AST_PARSE_ERROR,j.diagnostic.message);let M=j.source,F=[];if(d.kind==="remove-node"){let X=await up({routeState:g,placementUnitKey:d.target.placementUnitKey,source:w,mutatedSource:M});M=X.source,F=await Promise.all(X.files.map(async Y=>({operation:"delete",file:Y,baseContentHash:ae(await n.readFile(Y))})))}let B=[{operation:"upsert",file:g.entryFile,content:M,baseContentHash:ae(w)},...F];m+=1;try{return await dr({request:d,filePlan:{operationId:d.id,kind:"source-edit",target:{kind:"source-file",path:g.entryFile},documentVersion:d.documentVersion,conflictPolicy:"compare-and-swap",edits:B}})}finally{m-=1}}async function up(d){let g={source:d.mutatedSource,files:[]},h=d.routeState.graph,b=d.routeState.pageCompositionProjection;if(!h||!b||b.status!=="supported"||!n.listFiles)return g;let N=b.placementUnitByKey.get(d.placementUnitKey)?.sourceRange;if(!N)return g;let j=[...h.elements.values()].find(se=>se.sourceFile===d.routeState.entryFile&&se.importedFrom&&T(se.sourceRange,N));if(!j?.importedFrom||!j.exportName)return g;let M=C(j.importedFrom),F="components/site/generated/";if(!M.startsWith(F))return g;let B=M.slice(F.length).split("/")[0];if(!B||!/-[0-9a-f]{8}$/i.test(B))return g;let X=`${F}${B}`;if([...h.elements.values()].filter(se=>se.sourceFile===d.routeState.entryFile&&C(se.importedFrom??"")===M).length!==1)return g;let ee=await n.listFiles({maxFiles:5e3,maxDepth:32}),P=Array.isArray(ee)?ee:ee.files;if(!Array.isArray(ee)&&ee.truncated)return g;let O=P.map(({path:se})=>se).filter(se=>se===X||se.startsWith(`${X}/`));if(O.length===0||!O.includes(M))return g;for(let{path:se}of P)if(!(se===d.routeState.entryFile||se===X||se.startsWith(`${X}/`)))try{if((await n.readFile(se)).includes(B))return g}catch{return g}let z=A(d.routeState.entryFile,M),pe=un({source:d.mutatedSource,moduleSpecifier:z,imports:j.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:j.exportName}]});return pe.ok?{source:pe.source,files:O.sort((se,ye)=>se.localeCompare(ye))}:g}async function dp(d){if(n.getFileInfo){for(let w of d)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}}}let g=fp(d);if(g.length===0)return{ok:!0};let h=lb(n,d),b=rr({projectRoot:e.projectRoot,fileSystem:h,routes:[...o.values()].map(w=>({routeId:w.routeId,entryFile:w.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let w of g)await b.setActiveRoute(w)}catch(w){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Me(w)}`,details:{routeIds:g}}}finally{b.dispose()}return{ok:!0}}function fp(d){return d.map(h=>h.path).some(Cf)?[...o.keys()]:[]}function $o(d,g,h,b){let w=nr(g);return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:w,message:h,...b?{details:b}:{}}}}async function Bo(d){let g=[];for(let h of new Set(d))g.push(await pp(h));return g}async function pp(d){if(!(typeof n.exists=="function"?await n.exists(d):!0))return{file:d,content:"",version:Math.max(0,Z(d)),exists:!1};let h=await n.readFile(d);return{file:d,content:h,version:Math.max(1,Z(d)),exists:!0,sha256:ae(h)}}async function Ua(d,g,h,b){if(!e.historyStore)return null;let w=b.historyTransition;if(!w)throw new Error("Durable history did not provide an exact index transition.");let N=new Map(g.map(F=>[F.file,F])),j=new Map(h.map(F=>[F.file,F])),M=[...new Set([...N.keys(),...j.keys()])].sort().map(F=>{let B=N.get(F),X=j.get(F);return{path:F,preDigest:B?.exists===!1||!B?null:ae(B.content),postDigest:X?.exists===!1||!X?null:ae(X.content)}});return{schemaVersion:2,transactionId:`${d}:${w.expectedIndexDigest}`,operationId:d,phase:"prepared",historyTransition:w,files:M}}async function Va(d){return!d||!e.historyStore||await e.historyStore.writeTransactionJournal(d),d}async function Ht(d){d&&e.historyStore&&await e.historyStore.clearTransactionJournal(d.transactionId)}async function Ko(d,g){let h=[];try{for(let b of d)await Ja(b),typeof n.bumpVersion=="function"&&n.bumpVersion(b.file),h.push(b.file)}catch(b){let w=await mp(g.filter(N=>h.includes(N.file)));return w.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Me(b)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${w.failedFiles.join(", ")}: ${Me(b)}`,rolledBack:!1}}return{ok:!0,snapshots:d.map(hp)}}async function Ja(d){if(d.exists===!1){await n.deleteFile(d.file);return}await n.writeFile(d.file,d.content)}async function mp(d){let g=[];for(let h of d)try{await Ja(h),typeof n.bumpVersion=="function"&&n.bumpVersion(h.file)}catch{g.push(h.file)}return g.length===0?{ok:!0}:{ok:!1,failedFiles:g}}function hp(d){let g=d.exists!==!1;return{file:d.file,content:g?d.content:"",version:d.version,exists:g,...g?{sha256:ae(d.content)}:{}}}async function dr(d){return I.runExclusive(()=>gp(d))}async function gp(d){let g=d.filePlan.edits.map(P=>P.file),h=await Bo(g),b=new Map(h.filter(P=>P.exists!==!1).map(P=>[P.file,P.content])),w=p,N=Wa(),j=new Map(f),M=d.filePlan.edits.map(P=>P.operation==="delete"?{file:P.file,content:"",version:0,exists:!1}:{file:P.file,content:P.content,version:0,exists:!0,sha256:ae(P.content)}),F={operationId:d.filePlan.operationId,intents:d.filePlan.edits.map(P=>P.operation==="delete"?{kind:"delete",path:P.file}:{kind:P.operation==="create-only"?"create-only":"upsert",path:P.file,content:P.content})},B=null,X=!1,Y=await Eo({overlay:b,exists:P=>n.exists(P),plan:F,buildCandidate:async({plan:P})=>({plan:P}),prepareHistory:async()=>{let P=await l.prepareAppend({operationId:d.request.id,kind:d.request.kind,target:d.request.target,preSnapshots:h,postSnapshots:M,...d.selectionRef?{selectionRef:d.selectionRef}:{}});return B=await Ua(d.request.id,h,M,P),B=await Va(B),P},reverify:async()=>{},writeCandidate:async()=>{let P=await u.executeFilePlan(d.filePlan);if(!P.ok)throw new Io(P);return{postSnapshots:await Bo(P.affectedFiles),affectedFiles:P.affectedFiles,internalResultVersion:P.resultVersion}},validateCandidate:async({candidate:P,receipt:O})=>{let z=await ur(O.affectedFiles,{changed:!0,minimumVersion:O.internalResultVersion,publish:!1});if(z.failedRoutes.length>0)throw new Wt(z.failedRoutes);let pe=za(N,z.candidateRouteStates??[]),se=Math.max(O.internalResultVersion,...z.rebuiltRoutes.map(ye=>ye.version));return{...P,rebuild:z,routeSnapshots:pe,resultVersion:se,...If(d.selectionRef,pe.map(ye=>ye.state.document))?{selectionRef:If(d.selectionRef,pe.map(ye=>ye.state.document))}:{}}},publishCandidate:async({candidate:P,history:O,receipt:z})=>{if(!O)throw new Error("history intent is missing");await l.publishPrepared(O),X=!0;let pe=P.resultVersion??z.internalResultVersion;return{requestId:d.request.id,kind:d.request.kind,target:d.request.target,ok:!0,resultVersion:pe,affectedFiles:z.affectedFiles,...P.selectionRef?{selectionRef:P.selectionRef}:{}}},swapCandidate:({candidate:P,receipt:O})=>{P.routeSnapshots&&fr(P.routeSnapshots),P.rebuild?.candidateSourceCache&&Sn(f,P.rebuild.candidateSourceCache),ia(f,O.postSnapshots),p=Math.max(p,P.resultVersion??w)},finalizeCandidate:async()=>{await Ht(B)},emitCommitted:({candidate:P,published:O})=>{jo(O,P.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:P,receipt:O})=>{if(X)throw new Error("history was published before transaction finalization failed");if(O){let z=await Ko(h,O.postSnapshots);if(!z.ok)throw new Error(z.reason)}fr(N),Sn(f,j),p=w,P&&await l.discardPrepared?.(P),await Ht(B)}});if(Y.ok)return Y.published;if(Y.stage==="precheck"||Y.stage==="build")try{await Ht(B)}catch(P){let O=await pr(Me(P));return oe(d.request,O,"Unable to clear an uncommitted transaction journal.")}if(Y.recoveryRequired){let P=await pr(Y.reason);return oe(d.request,P===$.RECOVERY_PERSIST_FAILED?P:$.ROLLBACK_FAILED,Y.reason)}let ee=Y.error;return ee instanceof Io?{...oe(d.request,nr(ee.result.errorCode),ee.result.reason),...ee.result.affectedFiles?{affectedFiles:ee.result.affectedFiles}:{}}:ee instanceof Wt?oe(d.request,$.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${aa(ee.failedRoutes)}`,{failedRoutes:ee.failedRoutes}):oe(d.request,Ha(Y.stage),Me(ee))}async function Xa(d){return I.runExclusive(async()=>{let g=d==="undo"?await l.prepareUndo():await l.prepareRedo();return g?yp(d,g):{requestId:d,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:$.INTERNAL_ERROR,message:d==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function yp(d,g){let h=g.entry,b=d==="undo"?h.preSnapshots:h.postSnapshots,w=d==="undo"?h.postSnapshots:h.preSnapshots,N=b.map(O=>O.file),j=await Bo(N),M=new Map(j.filter(O=>O.exists!==!1).map(O=>[O.file,O.content])),F=p,B=Wa(),X=new Map(f),Y=null,ee=!1,P=await Eo({overlay:M,plan:{operationId:`${d}:${h.operationId}`,intents:b.map(O=>O.exists===!1?{kind:"delete",path:O.file}:{kind:"upsert",path:O.file,content:O.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(Y=await Ua(`${d}:${h.operationId}`,j,b,g),Y=await Va(Y),g),reverify:async()=>{},writeCandidate:async()=>{let O=await Ko(b,w);if(!O.ok)throw new Error(O.reason);return{snapshots:O.snapshots}},validateCandidate:async({candidate:O})=>{let z=await ur(N,{changed:!0,minimumVersion:p+1,publish:!1});if(z.failedRoutes.length>0)throw new Wt(z.failedRoutes);let pe=za(B,z.candidateRouteStates??[]),se=Math.max(p+1,...z.rebuiltRoutes.map(ye=>ye.version));return{...O,rebuild:z,routeSnapshots:pe,resultVersion:se}},publishCandidate:async({candidate:O,history:z})=>{if(!z)throw new Error("history cursor intent is missing");await l.publishPrepared(z),ee=!0;let pe=O.resultVersion??p+1;return{requestId:d,kind:h.kind,target:h.target,ok:!0,resultVersion:pe,affectedFiles:N}},swapCandidate:({candidate:O,receipt:z})=>{O.routeSnapshots&&fr(O.routeSnapshots),O.rebuild?.candidateSourceCache&&Sn(f,O.rebuild.candidateSourceCache),ia(f,z.snapshots),p=Math.max(p,O.resultVersion??F)},finalizeCandidate:async()=>{await Ht(Y)},emitCommitted:({candidate:O,published:z})=>jo(z,O.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:O,receipt:z})=>{if(ee)throw new Error("history cursor was published before transaction finalization failed");if(z){let pe=await Ko(w,z.snapshots);if(!pe.ok)throw new Error(pe.reason)}fr(B),Sn(f,X),p=F,O&&await l.discardPrepared?.(O),await Ht(Y)}});if(P.ok)return P.published;if(P.stage==="precheck"||P.stage==="build")try{await Ht(Y)}catch(O){let z=await pr(Me(O));return{requestId:d,kind:h.kind,target:h.target,ok:!1,resultVersion:p,error:{code:z,message:"Unable to clear an uncommitted transaction journal."}}}if(P.recoveryRequired){let O=await pr(P.reason);return{requestId:d,kind:h.kind,target:h.target,ok:!1,resultVersion:p,affectedFiles:N,error:{code:O===$.RECOVERY_PERSIST_FAILED?O:$.ROLLBACK_FAILED,message:P.reason}}}return{requestId:d,kind:h.kind,target:h.target,ok:!1,resultVersion:p,affectedFiles:N,error:{code:P.error instanceof Wt?$.ROUTE_REBUILD_FAILED:Ha(P.stage),message:Me(P.error),...P.error instanceof Wt?{details:{failedRoutes:P.error.failedRoutes}}:{}}}}function Wa(){return[...o.values()].map(d=>({routeId:d.routeId,state:{...d,dependencyFiles:new Set(d.dependencyFiles),fileVersions:new Map(d.fileVersions)}}))}function za(d,g){let h=new Map(d.map(b=>[b.routeId,b]));for(let b of g)h.set(b.routeId,b);return[...h.values()]}function fr(d){for(let g of o.values())R(g);for(let g of d){let h={...g.state,dependencyFiles:new Set(g.state.dependencyFiles),fileVersions:new Map(g.state.fileVersions)};o.set(g.routeId,h),ue(h,h.dependencyFiles)}}async function Uo(d){let g=o.get(d);if(!g)throw new Error(`Route not found: ${d}`);if(g.graph)return;let h=await n.readFile(g.entryFile);await me(d,h)}function kn(d,g){if(g){let h=o.get(g)??null;return!h||!Vo(h,d)?null:h}for(let h of o.values())if(Vo(h,d))return h;return null}function Vo(d,g){if(d.documentIndex?.entriesByKey.has(g)||d.graph?.elements.has(g))return!0;let h=Ke(g);return h&&h!==g?d.graph?.elements.has(h)===!0:!1}function oe(d,g,h,b){return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:g,message:h,...b?{details:b}:{}}}}function Ha(d){return d==="validate"?$.ROUTE_REBUILD_FAILED:d==="publish"?$.HISTORY_COMMIT_FAILED:$.WRITE_IO_ERROR}async function pr(d){if(S=!0,!l.markRecoveryRequired)return $.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(d),$.RECOVERY_REQUIRED}catch{return $.RECOVERY_PERSIST_FAILED}}function xp(d){let h=d.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(b=>b.charAt(0).toUpperCase()+b.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return h?`Prefab${h}`:"GeneratedPrefab"}function Ya(d){return d==="VERSION_STALE"?$.VERSION_STALE:d==="CROSS_PAGE_MOVE_UNSUPPORTED"?$.CROSS_PAGE_MOVE_UNSUPPORTED:$.UNSUPPORTED_OPERATION}async function Ga(d){if(d.target.kind==="route"){let h=o.get(d.target.routeId)??null;return h?(h.graph||await Uo(h.routeId),h):oe(d,$.ROUTE_NOT_FOUND,`Route not found: ${d.target.routeId}`)}if(d.target.kind==="page-unit"){let h=o.get(d.target.routeId)??null;return h?(h.graph||await Uo(h.routeId),h):oe(d,$.ROUTE_NOT_FOUND,`Route not found: ${d.target.routeId}`)}if(d.target.kind!=="node")return oe(d,$.UNSUPPORTED_OPERATION,`${d.kind} source target execution is not implemented yet.`);if(!d.routeId)return oe(d,$.INVALID_TARGET,"routeId is required when executing a node target");let g=o.get(d.routeId)??null;return g?(g.graph||await Uo(g.routeId),Vo(g,d.target.key)?g:oe(d,$.NODE_NOT_FOUND,`Target key not found: ${d.target.key}`)):oe(d,$.ROUTE_NOT_FOUND,`Route not found: ${d.routeId}`)}return{get status(){return t},dispose(){t="disposed",a.clear(),o.clear(),i.clear(),f.clear(),s=null},registerRoute(d,g){let h=o.get(d);if(h?.entryFile===g)return;h&&R(h);let b=bf(d,g);o.set(d,b),ue(b,b.dependencyFiles),r.emit({type:"graph-invalidated",routeId:d})},unregisterRoute(d){let g=o.get(d);g&&(R(g),o.delete(d),s===d&&(s=null,t="idle"),r.emit({type:"graph-invalidated",routeId:d}))},getRouteEntryFiles(){return[...o.values()].map(d=>d.entryFile)},async setActiveRoute(d){let g=o.get(d);if(!g)throw new Error(`Route not found: ${d}`);let h=s===d;if(s=d,!g.graph){t="building";try{let b=await n.readFile(g.entryFile);await me(d,b);let w=o.get(d)?.graph?.version??1;t="ready",r.emit({type:"graph-ready",routeId:d,version:w})}catch(b){throw t="idle",r.emit({type:"graph-error",routeId:d,message:Me(b)}),b}return}t="ready",h||r.emit({type:"graph-ready",routeId:d,version:g.graph.version})},getDocument(d){let g=o.get(d);if(!g)throw new Error(`Route not found: ${d}`);if(!g.document)throw new Error(`Route not built: ${d}`);return g.document},async getHistoryStatus(){await v;let d=await l.getStatus?.();return d?{...d,recoveryRequired:S}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:S}},getObjectEditContext(d,g){let h=kn(d,g),b=Ke(d)??d;if(h?.graph&&h.topology&&h.capabilities&&h.detailProjections){let w=h.detailProjections.get(b);if(w){let N=fl(b,h.graph,h.topology,h.capabilities,w.textSources,w.provenances,w.dynamicData);return d===b?N:Ab(N,d,h.document??null,h.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${d}`)},getRenderDetail(d,g){let h=kn(d,g),b=Ke(d)??d;if(h?.graph&&h.topology&&h.capabilities&&h.detailProjections){let w=h.detailProjections.get(b);if(w){let N=dl(b,h.graph,h.topology,h.capabilities,w.textSources,w.writeTarget,w.provenances,w.conditional,w.componentSemantic,w.contentModel,w.mediaModel,w.styleSource,w.dynamicData);return d===b?N:Pb(N,d,h.document??null,h.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${d}`)},getClassNameSource(d,g){let h=kn(d,g),b=Ke(d)??d;if(!h?.graph)throw new Error(`Key not found: ${d}`);let w=h.graph.elements.get(b);if(!w)throw new Error(`Key not found: ${d}`);let N=f.get(w.sourceFile);if(N===void 0)throw new Error(`Source not loaded: ${w.sourceFile}`);return Xl({key:b,route:{routeId:h.routeId,graph:h.graph,source:N}})},refreshSourceForKey:sp,async execute(d){if(await v,S)return oe(d,$.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(d.kind==="source-edit")return await Ka(d),ap(d);let g=await Ga(d);if("ok"in g)return g;await Ka(d);let h=await Ga(d);if("ok"in h)return h;let b=h;if(d.target.kind==="page-unit"){let M=d;return d.kind==="insert-child"?cp(M,b):d.kind==="move-node"||d.kind==="remove-node"?lp(M,b):oe(d,$.UNSUPPORTED_OPERATION,"Only page-unit insert-child, move-node, and remove-node are currently supported by the page composition transaction.")}if(!b.graph||!b.topology||!b.capabilities)return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:d.target.kind==="route"?$.ROUTE_NOT_FOUND:$.NODE_NOT_FOUND,message:d.target.kind==="route"?`Route not ready: ${d.target.routeId}`:d.target.kind==="node"?`Target key not found: ${d.target.key}`:`${d.kind} source target execution is not implemented yet.`}};let w=hb(b,b.graph,b.capabilities,f,o),N=await new co(w).plan(d);if(!N.ok)return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:nr(N.errorCode),message:N.reason}};let j=N.plan;if(j.steps.length===0)return d.kind==="set-props"?{requestId:d.id,kind:d.kind,target:d.target,ok:!0,resultVersion:p,affectedFiles:[]}:{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:$.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};m+=1;try{if(j.steps.some(F=>F.type==="invoke-external-adapter")){let F=await u.execute(j);if(!F.ok)return oe(d,nr(F.errorCode),F.reason);let B={requestId:d.id,kind:d.kind,target:d.target,ok:!0,resultVersion:Math.max(p,F.resultVersion),affectedFiles:F.affectedFiles,...F.selectionRef?{selectionRef:F.selectionRef}:{}};return jo(B,{rebuiltRoutes:[],failedRoutes:[]}),B}let M=await u.prepareRewritePlan(j);return M.ok?await dr({request:d,filePlan:M.filePlan,...M.selectionRef?{selectionRef:M.selectionRef}:{}}):oe(d,nr(M.errorCode),M.reason)}catch(M){return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:$.INTERNAL_ERROR,message:Me(M)}}}finally{m-=1}},async undo(d){if(await v,S)return{requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:$.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};m+=1;try{return await Xa("undo")}finally{m-=1}},async redo(d){if(await v,S)return{requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:$.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};m+=1;try{return await Xa("redo")}finally{m-=1}},notifyFileChanged(d){ja([d])},subscribe(d){return r.subscribe(d)}}}function pb(e,t,n){let r=new Map;for(let i of t.elements.values()){if(i.sourceFile!==n.entryFile||!i.importedFrom||!/^[A-Z]/.test(i.tag))continue;let s=n.placements.find(c=>c.members.some(l=>l.sourceRange!==null&&ca(i.sourceRange,l.sourceRange)));if(!s)continue;let a=s.placementUnitKey;r.set(`${i.importedFrom}#${i.tag}`,a),i.exportName&&i.exportName!==i.tag&&r.set(`${i.importedFrom}#${i.exportName}`,a)}let o=n.placements.find(i=>i.placementKey===n.container.placementKey&&i.relation==="append");for(let i of e.entries){let s=t.elements.get(i.key);if(!s)continue;if(s.sourceFile===n.entryFile){if(n.container.sourceRange&&ca(s.sourceRange,n.container.sourceRange)&&o){i.pageCompositionUnitKey=o.placementUnitKey;continue}let c=n.placements.find(l=>l.members.some(u=>u.sourceRange!==null&&(ca(s.sourceRange,u.sourceRange)||mb(u.sourceRange,s.sourceRange))));if(c){i.pageCompositionUnitKey=c.placementUnitKey;continue}}let a=r.get(`${s.sourceFile}#${s.componentName}`);a&&(i.pageCompositionUnitKey=a)}}function ca(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function mb(e,t){return vf(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&vf(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function vf(e,t,n,r){return e!==n?e-n:t-r}function hb(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 p=t.elements.get(u);for(let m of p?.childKeys??[])a(m,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),p=t.elements.get(f.baseKey);return p?l(u,p):null},getChildNodes(u){let f=c(u),m=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(m)return m.map(I=>{let v=Ke(I)??I,C=t.elements.get(v);return C?l(I,C):null}).filter(I=>I!==null);let S=t.elements.get(f.baseKey);return S?S.childKeys.map(I=>{let v=t.elements.get(I);return v?l(I,v):null}).filter(I=>I!==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),p=n.get(f.baseKey);return p?{...p,key:u,constraints:p.constraints.map(m=>({...m})),...p.editModes?{editModes:{...p.editModes}}:{}}:{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},getEditableTextSegmentIndex(u){let f=c(u),m=e.detailProjections?.get(f.baseKey)?.textTargets.keys()?.next();return m&&!m.done?m.value:null},async getTextWriteTarget(u,f){let p=c(u);return wf(e.detailProjections?.get(p.baseKey)?.textTargets.get(f)??null,p.repeatIndex)},async getElementPropertyWriteTarget(u,f){let p=c(u);return wf(e.detailProjections?.get(p.baseKey)?.elementPropertyTargets.get(f)??null,p.repeatIndex)},getTextProvenance(u,f){let p=c(u);return e.detailProjections?.get(p.baseKey)?.provenances.get(f)??null}};function c(u){let f=WS(u);return f?{baseKey:f.baseKey,repeatIndex:Cb(e.document??null,u,f.baseKey,e.documentIndex)??vb(f)}:{baseKey:u,repeatIndex:null}}function l(u,f){let p=Ke(u)??u,m=e.documentIndex?.entriesByKey.get(u),S=e.detailProjections?.get(p);return{key:u,file:f.sourceFile,component:f.componentName,tag:f.tag,structuralPath:f.identity.structuralPath,sourceRange:f.sourceRange,parentKey:m?.parentKey??f.parentKey??void 0,isRepeatRegion:f.boundaryKind==="repeat-region"||s.has(p),isBoundary:!1,importedFrom:f.importedFrom,exportName:f.exportName,isRepeatItemRoot:i.has(p),repeatOwnerKey:i.get(p)??s.get(p),contentModel:S?.contentModel,attributes:f.attributes?.map(I=>({name:I.name,value:I.value,source:I.source?{expression:I.source.expression,base:I.source.base,path:I.source.path.map(v=>({...v}))}:null,resolvedValue:I.resolvedValue}))}}}var gb={"stale-version":$.VERSION_STALE,"capability-denied":$.CAPABILITY_REJECTED,"invalid-params":$.INVALID_PARAMS,"locator-miss":$.LOCATOR_FAILED,"route-not-found":$.ROUTE_NOT_FOUND,"unsupported-operation":$.UNSUPPORTED_OPERATION,"invalid-target":$.INVALID_TARGET,"ast-error":$.AST_PARSE_ERROR,"writeback-failed":$.WRITE_IO_ERROR,"rollback-failed":$.RECOVERY_REQUIRED,unknown:$.INTERNAL_ERROR};function nr(e){return gb[e]}function Me(e){return e instanceof Error&&e.message?e.message:String(e)}function Cf(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function yb(e){let t=zt(e);if(!YS.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=>GS.map(a=>`${s}/${a}`))}function xb(e){let n=zt(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function Eb(e){return Pf(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function Sb(e){return Pf(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Pf(e,t){let n=[];for(let r of e.matchAll(t)){let o=Af(r[1]??"");o&&n.push(o)}return n}function Rf(e,t){let n=Af(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?zt(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?zt(`${bb(e)}/${n}`):n.startsWith("/")?zt(n.slice(1)):la(n)?zt(n):null}function Af(e){return e.split(/[?#]/,1)[0]?.trim()??""}function la(e){return/\.css$/i.test(e)}function bb(e){let t=zt(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function Tf(e){return Array.from(new Set(e))}function zt(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 Ib(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 bo(e){return e?.map(t=>({...t}))}function wf(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=bo(e.collectionPathMap?.[t])??bo(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:bo(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>bo(o)??[])}}function kb(e,t,n){let r=new Set;for(let m of t.regions)if(m.kind==="repeat-region")for(let S of m.childKeys)r.add(S);if(r.size===0)return e;let o=new Map(e.entries.map(m=>[m.key,m])),i=[],s=new Map,a=(m,S)=>VS(m,S),c=(m,S,I)=>{let v=o.get(m);if(!v)return a(m,I);let C=a(m,I),A={...v,key:C,parentKey:S,childKeys:[]};return i.push(A),A.childKeys=v.childKeys.flatMap(T=>l(T,I,C)),C},l=(m,S,I)=>{if(!r.has(m))return[c(m,I,S)];let v=f(m,S),C=[];for(let A=0;A<v;A+=1)C.push(c(m,I,[...S,A]));return C},u=Tf([...e.rootKeys,...e.entries.filter(m=>m.parentKey===null).map(m=>m.key)]);for(let m of u){if(!r.has(m)){c(m,null,[]);continue}let S=f(m,[]);for(let I=0;I<S;I+=1)c(m,null,[I])}return{...e,rootKeys:[...e.rootKeys],entries:i};function f(m,S){let I=new Set;for(let v of p(m)){let C=n.get(v);if(C){for(let A of[...C.textTargets.values(),...C.elementPropertyTargets.values()])if(!(A?.kind!=="value-binding"||A.sourceKind!=="repeat-template"))for(let T of Rb(A))T.length<=S.length||wb(T,S)&&I.add(T[S.length])}}return I.size>0?I.size:Ib(n.get(m))}function p(m){let S=s.get(m);if(S)return S;let I=[m],v=o.get(m);for(let C of v?.childKeys??[])I.push(...p(C));return s.set(m,I),I}}function vb(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Cb(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((Ke(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function Rb(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 wb(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 Pb(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 Ab(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}}import ma from"node:path";import{TextDecoder as Tb}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Ff,SITE_EDIT_SOURCE_ALLOWED_DIRS as Mf,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Of,SiteEditSourceFileResponseSchema as ua,SiteEditSourceLocationSchema as Nb,SiteEditSourcePathSchema as ko,SiteEditSourceTreeResponseSchema as Fb,isSiteEditTextSourcePath as Mb}from"@vcp-dev/contracts";var Ob=[...Of,...Ff,...Mf],da=2e3,fa=12,pa=24*1024*1024,Nf=512*1024,_b=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),Db={".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"},Lb={".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"},jb=new Tb("utf-8",{fatal:!0});async function vo(e,t={}){let{files:n,truncated:r}=await Wb(e,t),o=Yb(n.map(i=>i.metadata));return Fb.parse({nodes:o,defaultPath:Gb(n.map(i=>i.metadata)),totalFiles:n.length,...r?{truncated:r}:{}})}async function Co(e,t,n={}){let r=ko.parse(t.path),o=await Kb(e,r,n);if(!o)throw new Error(`Source file not found: ${r}`);if(ha(r)){let s=Lf(r),a=await Vb(e,{path:r,sizeBytes:o.sizeBytes,mimeType:s});return ua.parse({path:r,kind:"binary",language:null,sizeBytes:o.sizeBytes,mimeType:s,readonly:!0,...a})}let i=await $b(e,r);return i.ok?ua.parse({path:r,kind:"text",language:jf(r),sizeBytes:i.sizeBytes,contentHash:ae(i.content),readonly:!1,content:i.content}):ua.parse({path:r,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function $b(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=Bb(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 Bb(e){if(e.includes(0))return null;try{return jb.decode(e)}catch{return null}}async function Kb(e,t,n){if(!Jb(t,n))return null;let r=await Ub(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function Ub(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=_f(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(ha(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function Vb(e,t){if(!_b.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Nf)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Nf?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function Jb(e,t){return Of.some(n=>n===e)||Ff.some(n=>n===e)||Mf.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=ko.safeParse(n);return r.success&&r.data===e})}function Ro(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return Nb.parse({key:e.key,routeId:e.routeId,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 _f(e){return Array.isArray(e)?{files:e}:e}function Xb(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function Wb(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=_f(await e.listFiles({roots:zb(t),maxFiles:da+1,maxDepth:fa,maxTotalBytes:pa+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=ko.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>fa){o.add("max-depth");continue}if(r.size>=da){o.add("max-files");break}if(i+a.sizeBytes>pa){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:Hb(l,a.sizeBytes)}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:Xb([...o]),maxFiles:da,maxDepth:fa,maxTotalBytes:pa}}:{}}}function zb(e){let t=new Set(Ob);for(let n of e.routeEntryFiles??[]){let r=ko.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function Hb(e,t){return ha(e)?{path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Lf(e),readonly:!0}:{path:e,kind:"text",language:jf(e),sizeBytes:t,readonly:!1}}function Yb(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 Df(t)}function Df(e){return e.map(t=>t.kind==="directory"?{...t,children:Df(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function Gb(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 ha(e){return!Mb(e)}function Lf(e){let t=ma.posix.extname(e).toLowerCase();return!t&&ma.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":Db[t]??"application/octet-stream"}function jf(e){let t=ma.posix.extname(e).toLowerCase();return Lb[t]??"plaintext"}var wo=class{constructor(t){this.options=t,this.fileSystem=new Dn(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}async setActiveRoute(t){await this.engine.setActiveRoute(t)}getDocument(t){return xr(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){return Er(this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(){return vo(this.fileSystem,{routeEntryFiles:this.options.routes.map(t=>t.entryFile)})}getSourceFile(t){return Co(this.fileSystem,t,{routeEntryFiles:this.options.routes.map(n=>n.entryFile)})}resolveSourceLocation(t){return Ro(t,this.engine.getRenderDetail(t.key,t.routeId))}async planOperation(t){let n=Qb.safeParse(t);if(!n.success)return{result:yr(t,n.error.issues.map(i=>i.message))};let r=new Dn(this.options.files),o=this.createEngine(r,{emitEvents:!1});try{for(let u of this.getPlanningRouteIds(n.data))await o.setActiveRoute(u);let i=this.withInferredNodeRouteId(n.data,o),s=await o.execute(i);if(!s.ok)return{result:{ok:!1,error:{code:s.error?.code??"INTERNAL_ERROR",message:s.error?.message??"Operation failed"},data:{requestId:s.requestId,kind:s.kind,target:s.target,resultVersion:s.resultVersion}}};let a={ok:!0,data:Ft(s)},c=r.getChangedFiles();if(c.length===0)return{result:a};let l=qb.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:c.map(u=>eI(u,t.kind==="source-edit")),changedRouteIds:this.getChangedRouteIds(c.map(u=>u.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:l.patches.map(u=>u.path),at:new Date().toISOString()}),{result:a,patchPlan:l}}finally{o.dispose()}}dispose(){this.engine.dispose()}getPlanningRouteIds(t){let n=this.getExplicitPlanningRouteId(t);if(n){let r=this.options.routes.find(o=>o.routeId===n);return r?[r.routeId]:this.options.routes.map(o=>o.routeId)}if(t.target.kind==="node"){let r=this.getBuiltRouteIdsForKey(t.target.key);if(r.length>0)return r}return this.options.routes.map(r=>r.routeId)}getExplicitPlanningRouteId(t){if(t.routeId)return t.routeId;if(t.target.kind==="route")return t.target.routeId;if(t.params.kind==="set-class-name-source")return t.params.routeId;if(t.params.kind==="apply-style-draft")return t.params.className?.routeId}getBuiltRouteIdsForKey(t){let n=[];for(let r of this.options.routes)try{this.engine.getRenderDetail(t,r.routeId),n.push(r.routeId)}catch{}return n}withInferredNodeRouteId(t,n){if(t.target.kind!=="node"||t.routeId)return t;let r=this.findRouteIdForNodeTarget(n,t.target.key);return r?{...t,routeId:r}:t}findRouteIdForNodeTarget(t,n){for(let r of this.options.routes)try{if(t.getDocument(r.routeId).entries.some(i=>i.key===n))return r.routeId}catch{}return this.options.routes.length===1?this.options.routes[0]?.routeId:void 0}createEngine(t,n={}){let r=n.emitEvents??!0;return rr({projectRoot:"/snapshot",fileSystem:t,routes:this.options.routes.map(o=>({routeId:o.routeId,entryFile:o.entryFile})),onEvent:r&&this.options.onEvent?o=>{let i=Sr(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})}getChangedRouteIds(t){let n=new Set(t),r=new Set(this.options.routes.map(s=>s.entryFile));if(t.some(s=>!r.has(s)))return this.options.routes.map(s=>s.routeId);let i=this.options.routes.filter(s=>n.has(s.entryFile)).map(s=>s.routeId);return i.length>0?i:this.options.routes.map(s=>s.routeId)}};function eI(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ae(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ae(e.before)},fullContent:e.after}}function tI(e){return new wo(e)}import{SiteEditOperationRequestSchema as oI}from"@vcp-dev/contracts";import qe from"node:fs/promises";import Ce from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as nI,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as rI}from"@vcp-dev/contracts";var Po=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=rr({...t,fileSystem:this.fileSystem})}get status(){return this.engine.status}registerRoute(t,n){this.engine.registerRoute(t,n)}unregisterRoute(t){this.engine.unregisterRoute(t)}async setActiveRoute(t){await this.engine.setActiveRoute(t)}getDocument(t){return this.engine.getDocument(t)}getHistoryStatus(){return this.engine.getHistoryStatus()}getObjectEditContext(t,n){return this.engine.getObjectEditContext(t,n)}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(){return vo(this.fileSystem,{routeEntryFiles:this.engine.getRouteEntryFiles()})}getSourceFile(t){return Co(this.fileSystem,t,{routeEntryFiles:this.engine.getRouteEntryFiles()})}resolveSourceLocation(t){return Ro(t,this.engine.getRenderDetail(t.key,t.routeId))}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 qe.readFile(Ce.join(n,r),"utf8")},async readFileBytes(r){return qe.readFile(Ce.join(n,r))},async getFileInfo(r){let o=Ce.join(n,...r.split("/"));try{let i=await qe.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await go(Ce.join(n,r),o)},async createExclusive(r,o){let i=Ce.join(n,r);await qe.mkdir(Ce.dirname(i),{recursive:!0});let s=await qe.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await qe.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await qe.rm(Ce.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=Ce.join(n,i),a=Ce.dirname(Ce.join(n,o));for(;a!==s&&a.startsWith(`${s}${Ce.sep}`);){try{await qe.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Ce.dirname(a);continue}break}a=Ce.dirname(a)}},async exists(r){try{return await qe.access(Ce.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...rI,...nI],i=[],s=new Set,a=0;for(let u of o)await l(u,i,1);let c=i.sort((u,f)=>u.path.localeCompare(f.path));return s.size>0?{files:c,truncated:{reasons:[...s]}}:{files:c};async function l(u,f,p){if(r.maxFiles!==void 0&&f.length>=r.maxFiles){s.add("max-files");return}if(r.maxDepth!==void 0&&p>r.maxDepth){s.add("max-depth");return}let m=Ce.join(n,...u.split("/")),S;try{S=await qe.lstat(m)}catch{return}if(S.isSymbolicLink())return;if(S.isFile()){if(r.maxTotalBytes!==void 0&&a+S.size>r.maxTotalBytes){s.add("max-total-bytes");return}f.push({path:u,sizeBytes:S.size}),a+=S.size;return}if(!S.isDirectory())return;let I=await qe.readdir(m,{withFileTypes:!0});for(let v of I)v.isSymbolicLink()||await l(`${u}/${v.name}`,f,p+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function ga(e){return new Po(e)}var Ao=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=ga({projectRoot:t.projectRoot,fileSystem:t.fileSystem,routes:t.routes.map(n=>({routeId:n.routeId,entryFile:n.entryFile})),onEvent:n=>{let r=Sr(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.initialDocumentVersion!==void 0?{initialDocumentVersion:t.initialDocumentVersion}:{},siteId:t.siteId,snapshotId:t.snapshotId})}get status(){return this.engine.status}registerRoute(t,n){this.engine.registerRoute(t,n)}unregisterRoute(t){this.engine.unregisterRoute(t)}async setActiveRoute(t){await this.engine.setActiveRoute(t)}getDocument(t){return{ok:!0,data:xr(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return{ok:!0,data:this.engine.getDocument(t).styleContext??null}}async getHistoryStatus(){return{ok:!0,data:await this.engine.getHistoryStatus()}}getObjectEditContext(t,n){return{ok:!0,data:Er(this.engine.getObjectEditContext(t,n))}}getClassNameSource(t,n){return{ok:!0,data:this.engine.getClassNameSource(t,n)}}async getSourceTree(){return{ok:!0,data:await this.engine.getSourceTree()}}async getSourceFile(t){return{ok:!0,data:await this.engine.getSourceFile(t)}}resolveSourceLocation(t){return{ok:!0,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=oI.safeParse(r);if(!o.success)return yr(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,error:{code:s.code,message:s.message},data:{requestId:i.requestId,kind:i.kind,target:i.target,resultVersion:i.resultVersion,...i.affectedFiles?.length?{affectedFiles:i.affectedFiles}:{}}}}return{ok:!0,data:Ft(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,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,data:Ft(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,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,data:Ft(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 iI(e){return new Ao(e)}import{createHash as sI,randomUUID as Pa}from"node:crypto";import ge from"node:fs/promises";import Ie from"node:path";var Ve=1,xa=1,aI=2,cI="index.json",lI="recovery.json",uI="transaction-journal.json",dI="document-version.json",No={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},V={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"},J=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 zf(e,t={}){let n=kI(e),r=RI(t.limits),o=ya(n),i=vI(n),s=await Ue(i),a=await Ue(o)||s;a||(await yI(n),await Xf(n)),a||await wI(n);let c=await Oe(n);a||await or(n,c.entryIds);let l=async()=>{if(await Ue(o)||s)throw new J(V.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Wf(n)},async writeDocumentVersion(u){if(await l(),!Number.isInteger(u)||u<0)throw new J(V.INVALID_SCHEMA,"document version must be a non-negative integer");let f=await Wf(n);await ir(tp(n),{schemaVersion:1,version:Math.max(f,u)})},async stageAppend(u,f={}){await l();let p=await Bf(u,r),m={schemaVersion:xa,stageId:Pa(),entryId:p.entryId,blobIds:p.blobs.map(S=>S.digest)};try{await Kf(n,p),await mI(n,m,f.durableManifest!==!1)}catch(S){try{await Vf(n,m)}catch(I){throw new J(V.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:I})}throw S}return{stageId:m.stageId,entryId:m.entryId,blobIds:m.blobIds}},async discardStage(u){await l(),Ia(u);let f=await Sa(n,u);f&&await Vf(n,f)},async previewStagedAppend(u,f){return await l(),(await $f(n,r,u,f)).transition},async previewCursor(u,f){await l();let p=await Oe(n);return ka(p,f),Ea(u,p.entryIds.length),Hf(p,p.entryIds,u)},async publishStagedAppend(u,f,p){if(await l(),Fo(u,"entryId"),p){Ia(p);let S=await Sa(n,p);if(!S||S.entryId!==u)throw new J(V.INVALID_SCHEMA,"history stage does not match the published entry")}let m=await $f(n,r,u,f);return Jf({rootDir:n,previousDigest:m.current.digest,entryIds:m.entryIds,cursor:m.cursor,afterWrite:async()=>{p?await Ta(n,p):await gI(n,u),await or(n,m.entryIds)}})},async append(u){await l();let f=await Oe(n),p=await Bf(u,r),m=[...f.entryIds];f.cursor<m.length-1&&m.splice(f.cursor+1),m.push(p.entryId);try{await Kf(n,p);let S=await Yf(n,m,r);return await Fa(n,S.entryIds,S.cursor),await or(n,S.entryIds),Oe(n)}catch(S){throw await or(n,f.entryIds),S}},async readEntry(u){return Fo(u,"entryId"),sr(n,u)},async readBlob(u){Fo(u,"blobId");let f=In(n,u),p=await At(f,V.NOT_FOUND,"blob");return Ma(p,u,f),p},async readIndex(){return Oe(n)},async readStatus(){let u=await Oe(n);return{canUndo:u.undoIds.length>0,canRedo:u.redoIds.length>0,undoDepth:u.undoIds.length,redoDepth:u.redoIds.length,cursor:u.cursor,recoveryRequired:await Ue(o)||await Ue(i)}},async readUndoRedoIds(){let u=await Oe(n);return{undoIds:u.undoIds,redoIds:u.redoIds,currentId:u.currentId}},async setCursor(u,f){await l();let p=await Oe(n);return ka(p,f),Ea(u,p.entryIds.length),Jf({rootDir:n,previousDigest:p.digest,entryIds:p.entryIds,cursor:u})},async markRecoveryRequired(u){await Ue(o)||await ir(ya(n),{schemaVersion:Ve,reason:CI(u),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await ge.rm(ya(n),{force:!0})},async readTransactionJournal(){return await Ue(i)?To(i):null},async writeTransactionJournal(u){await l(),np(u);try{await ir(i,u)}catch(p){let m=await To(i).catch(()=>null);if(m&&Buffer.from(_e(m)).equals(Buffer.from(_e(u))))return;throw m?new J(V.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:p}):p}let f=await To(i);if(!Buffer.from(_e(f)).equals(Buffer.from(_e(u))))throw new J(V.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(u){let f=await Ue(i)?await To(i):null;if(f&&f.transactionId!==u)throw new J(V.INVALID_SCHEMA,"transaction journal changed concurrently");try{await ge.rm(i,{force:!0})}catch(p){if(!await Ue(i))return;throw p}if(await Ue(i))throw new J(V.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await l(),await Xf(n);let u=await Oe(n);await or(n,u.entryIds)}}}async function $f(e,t,n,r){Fo(n,"entryId");let o=await Oe(e);ka(o,r);let i=await sr(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await Yf(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:Hf(o,a.entryIds,a.cursor)}}function Hf(e,t,n){return Ea(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:fI(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function fI(e,t){return Tt(_e({schemaVersion:Ve,entryIds:e,cursor:t}))}function Ea(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new J(V.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function pI(e){if(!et(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Ae(e.expectedIndexDigest)||!Ae(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Ae(n)?!1:t===-1?n===null:Ae(n)}async function Bf(e,t){if(!e.kind.trim())throw new J(V.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new J(V.INVALID_JSON,"history blob name must not be empty");let l=II(c.data),u=Tt(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:Ve,kind:e.kind,manifest:e.manifest,blobs:r},i=_e({...o}),s=Tt(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new J(V.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function Kf(e,t){let n=cr(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Uf(In(e,a.digest),a.bytes,{kind:"blob",digest:a.digest})),Uf(n,_e(r),{kind:"entry",digest:t.entryId})],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Uf(e,t,n){let r=await ep(e);if(r!==null){if(Buffer.compare(r,t)!==0)throw new J(n.kind==="blob"?V.BLOB_CORRUPT:V.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Qf(e,t)}async function Yf(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await Zf(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new J(V.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function mI(e,t,n){Na(t);let r=_a(e,t.stageId);if(n){await ir(r,t);return}await bI(r,t)}async function Sa(e,t){let n=await ep(_a(e,t));if(n===null)return null;let r=ar(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Na(r);if(o.stageId!==t)throw new J(V.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Aa(e){let t=[];for(let n of await wa(Oa(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Ia(r);let o=await Sa(e,r);o&&t.push(o)}return t}async function Vf(e,t){Na(t);let n=await Oe(e),r=(await Aa(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await sr(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 ba(cr(e,t.entryId));for(let s of t.blobIds)i.has(s)||await ba(In(e,s));await Ta(e,t.stageId),await Ra(Do(e)),await Ra(Lo(e))}async function Ta(e,t){await ba(_a(e,t)),await hI(e)}async function hI(e){try{await ge.rmdir(Oa(e))}catch(t){if(lr(t)||et(t)&&t.code==="ENOTEMPTY")return;throw t}}async function gI(e,t){for(let n of await Aa(e))n.entryId===t&&await Ta(e,n.stageId)}async function ba(e){if(await ge.rm(e,{force:!0}),await Ue(e))throw new J(V.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}function Na(e){if(!et(e)||e.schemaVersion!==xa||typeof e.stageId!="string"||!Gf(e.stageId)||!Ae(e.entryId))throw new J(V.INVALID_SCHEMA,"history stage schema is invalid");let t=qf(e.blobIds,"history stage blobIds");return{schemaVersion:xa,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Ia(e){if(!Gf(e))throw new J(V.INVALID_PATH,"history stageId must be a UUID")}function Gf(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 or(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await sr(e,c);for(let u of l.blobs)r.add(u.digest)}for(let c of await Aa(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=Do(e),i=await wa(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=c.slice(0,-5);Ae(l)&&!n.has(l)&&await Mo(cr(e,l))}let s=Lo(e),a=await wa(s);for(let c of a){let l=c;Ae(l)&&!r.has(l)&&await Mo(In(e,l))}}async function Oe(e){let t=_o(e),n=await At(t,V.NOT_FOUND,"index"),r=ar(Buffer.from(n).toString("utf8"),"index"),o=xI(r),i=[...o.entryIds],{totalBytes:s}=await Zf(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:Ve,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function Zf(e,t){let n=0,r=new Set,o=_o(e),i=await At(o,V.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await sr(e,s),c=cr(e,s),l=await At(c,V.NOT_FOUND,"entry");n+=l.byteLength;for(let u of a.blobs){if(r.has(u.digest))continue;r.add(u.digest);let f=In(e,u.digest),p=await At(f,V.NOT_FOUND,"blob");Ma(p,u.digest,f),n+=p.byteLength}}return{totalBytes:n}}async function sr(e,t){let n=cr(e,t),r=await At(n,V.NOT_FOUND,"entry"),o=ar(Buffer.from(r).toString("utf8"),`entry ${t}`),i=EI(o);if(i.id!==t)throw new J(V.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(Tt(_e({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new J(V.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=In(e,a.digest),l=await At(c,V.NOT_FOUND,"blob");Ma(l,a.digest,c)}return i}async function Fa(e,t,n){let r={schemaVersion:Ve,digest:Tt(_e({schemaVersion:Ve,entryIds:t,cursor:n})),entryIds:t,cursor:n};await ir(_o(e),r)}function ka(e,t){if(t!==void 0&&e.digest!==t)throw new J(V.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Jf(e){let t=Tt(_e({schemaVersion:Ve,entryIds:e.entryIds,cursor:e.cursor}));try{return await Fa(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await Oe(e.rootDir)}catch(n){let r=await Oe(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new J(V.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function yI(e){await ge.mkdir(e,{recursive:!0}),await ge.mkdir(Do(e),{recursive:!0}),await ge.mkdir(Lo(e),{recursive:!0}),await ge.mkdir(Oo(e),{recursive:!0})}async function Xf(e){await ge.rm(Oo(e),{recursive:!0,force:!0}),await ge.mkdir(Oo(e),{recursive:!0})}function xI(e){if(!et(e))throw new J(V.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==Ve)throw new J(V.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=qf(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new J(V.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Ae(o))throw new J(V.INDEX_CORRUPT,"index digest is invalid");let i=Tt(_e({schemaVersion:Ve,entryIds:t,cursor:r}));if(o!==i)throw new J(V.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:Ve,digest:o,entryIds:t,cursor:r}}function EI(e){if(!et(e))throw new J(V.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==Ve)throw new J(V.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Ae(t))throw new J(V.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new J(V.ENTRY_CORRUPT,"entry kind is invalid");let r=Ca(e.manifest,"entry.manifest"),o=SI(e.blobs);return{id:t,schemaVersion:Ve,kind:n,manifest:r,blobs:o}}function SI(e){if(!Array.isArray(e))throw new J(V.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!et(t))throw new J(V.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new J(V.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Ae(o))throw new J(V.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new J(V.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function ir(e,t){await Qf(e,_e(t))}async function bI(e,t){let n=Ie.dirname(e),r=Ie.basename(e),o=Ie.join(n,`.${r}.${process.pid}.${Pa()}.tmp`);await ge.mkdir(n,{recursive:!0});try{await ge.writeFile(o,_e(t),{flag:"wx"}),await ge.rename(o,e)}finally{await Mo(o)}}async function Qf(e,t){let n=Ie.dirname(e),r=Ie.basename(e),o=Ie.join(n,`.${r}.${process.pid}.${Pa()}.tmp`);await ge.mkdir(n,{recursive:!0});try{let i=await ge.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await ge.rename(o,e),await Ra(n)}finally{await Mo(o)}}function _e(e){return Buffer.from(JSON.stringify(va(e)),"utf8")}function va(e){if(Array.isArray(e))return e.map(t=>va(t));if(et(e)){let t={};for(let n of Object.keys(e).sort())t[n]=va(e[n]);return t}return e}function ar(e,t){try{return JSON.parse(e)}catch(n){throw new J(V.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Ca(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=>Ca(n,t));if(et(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Ca(o,t);return n}break}throw new J(V.INVALID_JSON,`${t} must be JSON-serializable`)}function qf(e,t){if(!Array.isArray(e))throw new J(V.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Ae(n))throw new J(V.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Fo(e,t){if(!Ae(e))throw new J(V.INVALID_PATH,`${t} must be a sha256 digest`)}function Ae(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function Tt(e){return`sha256:${sI("sha256").update(e).digest("hex")}`}function II(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function At(e,t,n){try{return await ge.readFile(e)}catch(r){throw new J(t,`${n} not found: ${e}`,{cause:r})}}async function ep(e){try{return await ge.readFile(e)}catch(t){if(lr(t))return null;throw t}}function Ma(e,t,n){if(Tt(e)!==t)throw new J(V.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Ue(e){try{return await ge.access(e),!0}catch(t){if(lr(t))return!1;throw t}}async function Mo(e){try{await ge.rm(e,{force:!0,recursive:!0})}catch{}}async function Ra(e){try{let t=await ge.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function wa(e){try{return await ge.readdir(e)}catch(t){if(lr(t))return[];throw t}}function kI(e){if(typeof e!="string"||e.trim().length===0)throw new J(V.INVALID_ROOT,"history store rootDir must be a non-empty string");return Ie.resolve(e)}function _o(e){return Ie.join(e,cI)}function ya(e){return Ie.join(e,lI)}function vI(e){return Ie.join(e,uI)}function tp(e){return Ie.join(e,dI)}async function Wf(e){try{let t=await ge.readFile(tp(e),"utf8"),n=ar(t,"document version");if(!et(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new J(V.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(lr(t))return 0;throw t}}async function To(e){let t=await At(e,V.RECOVERY_PENDING,"transaction journal"),n=ar(Buffer.from(t).toString("utf8"),"transaction journal");return np(n),n}function np(e){if(!et(e)||e.schemaVersion!==aI||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!pI(e.historyTransition)||!Array.isArray(e.files))throw new J(V.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!et(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Ae(t.preDigest)||t.postDigest!==null&&!Ae(t.postDigest))throw new J(V.INVALID_SCHEMA,"transaction journal file digest is invalid")}function CI(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Do(e){return Ie.join(e,"entries")}function Lo(e){return Ie.join(e,"blobs")}function Oo(e){return Ie.join(e,"tmp")}function Oa(e){return Ie.join(Oo(e),"stages")}function _a(e,t){return Ie.join(Oa(e),`${t}.json`)}function cr(e,t){return Ie.join(Do(e),`${t}.json`)}function In(e,t){return Ie.join(Lo(e),t)}function et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function RI(e){return{maxEntries:e?.maxEntries??No.maxEntries,maxSessionBytes:e?.maxSessionBytes??No.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??No.maxEntryBytes}}async function wI(e){let t=_o(e);await Ue(t)||await Fa(e,[],-1)}export{J as FileHistoryStoreError,Ao as PreviewFileSystemSiteEditEngineRuntime,Hd as SITE_EDIT_RAW_COLOR_LITERAL_RE,wo as SnapshotSiteEditEngineRuntime,iI as createPreviewSiteEditEngineRuntime,tI as createSiteEditEngineRuntime,zf as openFileHistoryStore,Zs as scanSiteEditThemeStyleViolations};
9
+ `||p==="\r"))return vn(t,`Unterminated string literal in ${t}.`);l=p===`
10
+ `||p==="\r";continue}if(p==="/"&&m==="*"){s=!0,d+=1,l=!1;continue}if(n==="mdx"&&p==="/"&&m==="/"){a=!0,d+=1,l=!1;continue}if(p==="'"||p==='"'||n==="mdx"&&p==="`"){o=p,l=!1;continue}if(p==="{"||p==="("||p==="["){r.push({char:p,offset:d}),l=!1;continue}if(p==="}"||p===")"||p==="]"){let E=p==="}"?"{":p===")"?"(":"[",b=r.pop();if(!b||b.char!==E)return vn(t,`Unexpected closing token "${p}" in ${t}.`);l=!1;continue}l=p===`
11
+ `||p==="\r"}if(s)return vn(t,`Unterminated block comment in ${t}.`);if(o)return vn(t,`Unterminated string literal in ${t}.`);if(c)return vn(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?vn(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function vn(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function sr(e){let t="idle",n=e.fileSystem??aS(),r=vd(),o=new Map,i=new Map,s=null,a=new Set,c=null,l=e.history??(e.historyStore?Vd(e.historyStore):cS()),u=kd(n,{externalAdapters:e.externalAdapters}),d=new Map,p=Math.max(0,e.initialDocumentVersion??0),m=0,E=e.historyStore?.recoveryRequired??!1,b=Gs(),v=G();function C(f){return(ko.isAbsolute(f)?ko.relative(e.projectRoot,f):f).replace(/\\/g,"/").replace(/^\.\//,"")}function A(f,y){let g=ko.posix.dirname(f),I=y.replace(/\.(?:tsx?|jsx?)$/i,""),P=ko.posix.relative(g,I);return P.startsWith(".")?P:`./${P}`}function N(f,y){return f.startLine===y.startLine&&f.startColumn===y.startColumn&&f.endLine===y.endLine&&f.endColumn===y.endColumn}async function G(){let f=e.historyStore;if(f)try{let y=await f.readTransactionJournal();if(!y)return;let g=await f.readIndex(),I=await Promise.all(y.files.map(async T=>await n.exists(T.path)?ae(await n.readFile(T.path)):null));if(Hd({journal:y,index:g,observedFileDigests:I})!=="ambiguous"){await f.clearTransactionJournal(y.transactionId);let T=await f.readStatus();T.recoveryRequired||(await f.cleanupTmp(),T=await f.readStatus()),E=T.recoveryRequired;return}await f.markRecoveryRequired(`Ambiguous transaction journal ${y.transactionId} at phase ${y.phase}`),E=!0}catch(y){E=!0,await f.markRecoveryRequired(`Transaction journal recovery failed: ${_e(y)}`).catch(()=>{})}}function fe(){return t==="disposed"}if(e.onEvent&&r.subscribe(e.onEvent),e.routes)for(let f of e.routes){let y=Zd(f.routeId,f.entryFile);o.set(f.routeId,y),ue(y,y.dependencyFiles)}function ue(f,y){let g=new Set(y);R(f),f.dependencyFiles=g;for(let I of f.dependencyFiles){let P=i.get(I);P||(P=new Set,i.set(I,P)),P.add(f.routeId)}}function R(f){for(let y of f.dependencyFiles){let g=i.get(y);g&&(g.delete(f.routeId),g.size===0&&i.delete(y))}f.dependencyFiles.clear()}function _(f){let y=new Set;for(let g of f)for(let I of i.get(g)??[])y.add(I);return y}function D(f){for(let y of f)if(!i.has(y))return!1;return!0}async function L(f,y,g,I,P){let T=new Map,j=Ru(P.values()),M=new Map,F=typeof n.exists=="function"?V=>n.exists(V):async()=>!1;for(let[V,X]of f.elements){let Y=y.nodes.get(V);if(!Y)continue;let ee=g.get(X.sourceFile)??I.get(X.sourceFile),w=new Map,O=new Map,z=new Map,pe=[];for(let de of X.textSegments){if(!ee){w.set(de.index,null);continue}let wn=await Pu({file:X.sourceFile,source:ee,segment:de,readFile:He=>n.readFile(He),exists:F,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:He,adapterId:Yo,capabilities:Go})=>({sourceType:He,adapterId:Yo,capabilities:Go})),functionCallContracts:e.functionCallContracts,fileCache:j}),ke=await Ss({file:X.sourceFile,source:ee,target:{kind:"text-segment",segment:de},readFile:He=>n.readFile(He),exists:F,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:He,adapterId:Yo,capabilities:Go})=>({sourceType:He,adapterId:Yo,capabilities:Go})),functionCallContracts:e.functionCallContracts,fileCache:j}),qt=yS(wn);w.set(de.index,qt),O.set(de.index,wn),z.set(de.index,ke),pe.push({editable:de.editable,source:qt})}let se=new Map;if(ee)for(let de of X.attributes??[]){let wn=await wu({file:X.sourceFile,source:ee,sourceRange:de.sourceRange,expression:de.source?.expression??de.value,sourceInfo:de.source,readFile:ke=>n.readFile(ke),exists:F,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ke,adapterId:qt,capabilities:He})=>({sourceType:ke,adapterId:qt,capabilities:He})),functionCallContracts:e.functionCallContracts,fileCache:j});se.set(de.name,wn)}let ye=rl(xS(Y.writeTarget),pe),xr=cl({key:V,element:X,graph:f,provenances:z}),we=fl(X),Er=pl(X),Sr=ml(X),Qt=ee?await nd({element:X,graph:f,file:X.sourceFile,source:ee,readFile:de=>n.readFile(de),exists:F,fileCache:M}):void 0,Mt=f.regions.find(de=>de.kind==="conditional-region"&&de.childKeys.includes(V)),Fe,Pn=Mt?.sourceCandidates?.[0];if(ee&&Mt&&Pn?.kind==="conditional-branch"){let de=await Ss({file:X.sourceFile,source:ee,target:{kind:"conditional-branch",candidate:Pn},readFile:ke=>n.readFile(ke),exists:F,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ke,adapterId:qt,capabilities:He})=>({sourceType:ke,adapterId:qt,capabilities:He})),functionCallContracts:e.functionCallContracts,fileCache:j});Fe={currentBranch:Mt.childKeys.indexOf(V)<=0?"then":"else",availableBranches:Mt.childKeys.length>1?["then","else"]:["then"],conditionExpression:Pn.conditionExpression,provenance:{finalSource:de.finalSource?{kind:de.finalSource.kind,file:de.finalSource.file,displayPath:de.finalSource.displayPath}:null,chain:de.chain.map(ke=>({kind:ke.kind,file:ke.file,displayName:ke.displayName,canEditHere:ke.canEditHere})),confidence:de.confidence,editMode:de.editMode,diagnostics:de.diagnostics.map(ke=>({code:ke.code,message:ke.message}))}}}T.set(V,{textSources:w,textTargets:O,elementPropertyTargets:se,provenances:z,writeTarget:ye,componentSemantic:xr,contentModel:we,mediaModel:Er,styleSource:Sr,conditional:Fe,dynamicData:Qt})}return T}function Z(f){return typeof n.getVersion=="function"?n.getVersion(f):0}function Q(f,y){let g=1;for(let I of y.values())g=Math.max(g,I);return Math.max(g,f.graph?.version??0)}async function he(f,y,g={}){let I=o.get(f);if(!I)return null;let P=g.sourceCache??Zs(d,[]),T=await W(I.entryFile),{graph:j,allSources:M,diagnostics:F,parsedModules:V,entryModule:X}=await qa(I.entryFile,y,Fe=>n.readFile(Fe),typeof n.exists=="function"?Fe=>n.exists(Fe):async()=>!1,{additionalEntries:T,version:I.graph?.version??1});if(F.length>0)throw new or(F);let Y=new Map;for(let Fe of M.keys())Y.set(Fe,Z(Fe));let ee=Math.max(Q(I,Y),g.minimumVersion??0,p);g.changed&&ee<=(I.graph?.version??0)&&(ee=(I.graph?.version??0)+1),j.version=ee;for(let[Fe,Pn]of M)qs(P,Fe,Pn,Wd);let w=await q(I.entryFile,M,P);j.routeId=f;let O=ec(j),z=nc(O,j),pe=await L(j,O,M,P,V),se=Mf(j,z,pe),ye=ht(pe),xr=MS(Qc(j,O,z,{canUpdateTextByKey:se,dynamicDataSummaryByKey:ye}),j,pe),we=Jc({route:f,entryFile:I.entryFile,version:ee,source:y,ast:X?.ast}),Er=Xc(we);we.ok&&kS(xr,j,we.projection);let Sr={...xr,...w?{styleContext:w}:{},pageComposition:Er},Qt=new Set([I.entryFile,...M.keys()]);if(w){Qt.add(w.entryCss.path);for(let Fe of w.stylesheets)Qt.add(Fe.path)}let Mt={...I,dependencyFiles:Qt,graph:j,topology:O,capabilities:z,document:Sr,pageComposition:Er,pageCompositionProjection:we.projection,pagePlacementByKey:we.ok?we.projection.placementByKey:null,pagePlacementUnitByKey:we.ok?we.projection.placementUnitByKey:null,pageUnitByKey:we.ok?we.projection.unitByKey:null,pagePlacementsByUnitKey:we.ok?we.projection.placementsByUnitKey:null,documentIndex:dS(Sr),detailProjections:pe,fileVersions:Y,styleContext:w};return g.publish===!1?Mt:(kn(d,P),p=Math.max(p,ee),ue(I,Qt),Object.assign(I,Mt),I)}async function W(f){let y=[];for(let g of PS(f))typeof n.exists=="function"&&await n.exists(g)&&y.push({file:g,source:await n.readFile(g)});return y}async function q(f,y,g){let I=[];for(let[F,V]of y){if(na(F)){I.push(F);continue}for(let X of AS(V)){let Y=nf(F,X);Y&&I.push(Y)}}if(!I.length){for(let F of wS(f))if(await at(F)){I.push(F);break}}let P=new Map,T=af(I).slice(0,zd);for(;T.length>0&&P.size<zd;){let F=T.shift();if(P.has(F)||!na(F))continue;let V=await ge(F,g);if(V!==null){P.set(F,{path:F,content:V});for(let X of NS(V)){let Y=nf(F,X);Y&&!P.has(Y)&&!T.includes(Y)&&T.push(Y)}}}let j=[...P.values()].map(F=>({...F,hash:ae(F.content)})),M=j[0];return M?{revision:ae(JSON.stringify(j.map(({path:F,hash:V})=>({path:F,hash:V})))),entryCss:M,stylesheets:j.slice(1)}:null}async function ge(f,y){let g=y.get(f);if(g!==void 0)return g;if(!await at(f))return null;let I=await n.readFile(f);return qs(y,f,I,Wd),I}async function at(f){return typeof n.exists=="function"?n.exists(f):!1}function ht(f){let y=new Map;for(let[g,I]of f)I.dynamicData?.bindings.length&&y.set(g,pd(I.dynamicData.bindings));return y}function Mf(f,y,g){let I=new Map;for(let[P,T]of f.elements){if(!y.get(P)?.canUpdateText){I.set(P,!1);continue}let M=g.get(P),F=T.textSegments.some(V=>{if(!V.editable)return!1;let X=M?.provenances.get(V.index)??null;return!X||Of(X)});I.set(P,F)}return I}function Of(f){return f.editMode==="direct"||f.editMode==="proxy"||f.editMode==="upstream"}async function mr(f,y={}){let g=[...new Set(f)],I=_(g);if(I.size===0||!D(g))for(let M of o.values())Pa(M,g)&&I.add(M.routeId);let P=I.size===0&&g.some(tf),T=y.publish===!1?Zs(d,g):void 0,j={rebuiltRoutes:[],failedRoutes:[],...y.publish===!1?{candidateRouteStates:[],candidateSourceCache:T}:{}};for(let M of o.values())if(I.has(M.routeId)||P)try{let V=!!M.graph,X=await n.readFile(M.entryFile),Y=await he(M.routeId,X,{...y,...T?{sourceCache:T}:{}});Y?.graph&&(j.rebuiltRoutes.push({documentChanged:V,routeId:M.routeId,version:Y.graph.version}),j.candidateRouteStates?.push({routeId:M.routeId,state:Y}))}catch(V){j.failedRoutes.push(Xd(M.routeId,V))}return j}function Ra(f){let y=[...new Set(f)],g=_(y);if(g.size>0&&D(y))return[...g];for(let I of o.values())Pa(I,y)&&g.add(I.routeId);return[...g]}function Ko(f,y){r.emit({type:"operation-completed",result:f});for(let{routeId:g,version:I}of y.rebuiltRoutes)r.emit({type:"document-changed",routeId:g,version:I});for(let{routeId:g,message:I}of y.failedRoutes)r.emit({type:"graph-error",routeId:g,message:I})}function Pa(f,y){return y.some(g=>f.dependencyFiles.has(g)||f.entryFile===g||f.graph?.fileIndex.has(g))}function wa(f){for(let y of f)a.add(y);c||fe()||(c=(async()=>{t="building";let y=!1;try{for(;a.size>0;){if(fe())return;await _f();let g=[...a];a.clear();let I=await Aa(g);if(I.length===0)continue;let P=Ra(I);for(let M of P)r.emit({type:"graph-invalidated",routeId:M});let{rebuiltRoutes:T,failedRoutes:j}=await mr(I,{changed:!0});for(let{documentChanged:M,routeId:F,version:V}of T)r.emit({type:"graph-ready",routeId:F,version:V}),M&&r.emit({type:"document-changed",routeId:F,version:V});for(let{routeId:M,message:F}of j)y=!0,r.emit({type:"graph-error",routeId:M,message:F})}}finally{if(c=null,t!=="disposed"){let g=s?o.get(s):null;t=!y&&g?.graph?"ready":"idle"}a.size>0&&wa([])}})())}async function _f(){for(;m>0;)await new Promise(f=>setTimeout(f,0))}async function Aa(f){let y=[];for(let g of new Set(f)){let I=d.get(g);if(I===void 0){y.push(g);continue}try{await n.readFile(g)!==I&&y.push(g)}catch{y.push(g)}}return y}async function Na(f){let y=await Aa(f);if(y.length===0)return;let g=Ra(y);for(let T of g)r.emit({type:"graph-invalidated",routeId:T});let{rebuiltRoutes:I,failedRoutes:P}=await mr(y,{changed:!0});for(let{documentChanged:T,routeId:j,version:M}of I)r.emit({type:"graph-ready",routeId:j,version:M}),T&&r.emit({type:"document-changed",routeId:j,version:M});for(let{routeId:T,message:j}of P)r.emit({type:"graph-error",routeId:T,message:j})}async function Df(f,y){let g=Rn(f,y);if(!g?.graph)return;let I=Ke(f)??f,P=g.graph.elements.get(I);P&&await Na([P.sourceFile])}async function Ta(f){let y=new Set;if(f.target.kind==="node"){let g=Rn(f.target.key,f.routeId),I=Ke(f.target.key)??f.target.key,P=g?.graph?.elements.get(I);P&&y.add(P.sourceFile)}else if(f.target.kind==="route"){let g=o.get(f.target.routeId);g&&y.add(g.entryFile)}else if(f.target.kind==="page-unit"){let g=o.get(f.target.routeId);g&&y.add(g.entryFile)}else if(f.target.kind==="source-file")y.add(f.target.path);else if(f.target.kind==="source-batch")for(let g of f.target.paths)y.add(g);await Na(y)}async function Lf(f){if(f.params.kind!=="source-edit")return Jo(f,"invalid-params","source-edit requires source-edit params");for(let y of f.params.edits){let g=IS(y);if(!g.ok)return Jo(f,g.errorCode,g.message,g.details)}m+=1;try{let y=await Uf(f.params.edits);if(!y.ok)return Jo(f,y.errorCode,y.message,y.details);let g={operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:f.params.conflictPolicy,edits:f.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 hr({request:f,filePlan:g})}catch(y){return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:B.INTERNAL_ERROR,message:_e(y)}}}finally{m-=1}}async function jf(f,y){if(f.kind!=="insert-child"||f.params.kind!=="insert-child")return oe(f,B.UNSUPPORTED_OPERATION,"Only page-unit insert-child is currently supported by the page composition transaction.");if(!("kind"in f.params.position)||f.params.position.kind!=="page-composition")return oe(f,B.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(f.params.position.documentVersion!==f.documentVersion)return oe(f,B.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.");let g=y.document,I=y.pageCompositionProjection;if(!g||g.pageComposition?.status!=="supported"||!I||I.status!=="supported")return oe(f,B.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==g.version||I.documentVersion!==g.version)return oe(f,B.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${g.version}).`);let P=f.params.node.kind==="component-call"?f.params.node.materialization:void 0;if(!P)return oe(f,B.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let T=f.params.position,j=await Fd({manifest:P,generatedRoot:"components/site/generated",controlledFiles:P.files.map(M=>({pathTemplate:M.pathTemplate})),exists:M=>n.exists(M),commit:async M=>{let F=await n.readFile(y.entryFile),V=y.document,X=y.pageCompositionProjection;if(!V||V.pageComposition?.status!=="supported"||V.version!==f.documentVersion||!X||X.status!=="supported"||X.documentVersion!==V.version)return{ok:!0,data:oe(f,B.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Y=M.entry.path,ee=Wf(M.instanceName),w=Ai({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:V.version,expectedDocumentVersion:f.documentVersion,source:F,projection:X,placementKey:T.placementKey,component:{source:Y,exportName:M.entry.export.kind==="default"?"default":M.entry.export.name,localName:ee}});if(!w.ok)return{ok:!0,data:oe(f,Ba(w.error.code),w.error.message,{diagnostics:w.error.diagnostics})};let O=w.plan.returnStep?Bc({source:F,jsx:w.plan.returnStep.node.jsx,placement:w.plan.returnStep.placement,...w.plan.returnStep.replaceOriginal?{replaceOriginal:!0}:{}}):w.plan.insertStep?.parentLocator?un({source:F,locator:w.plan.insertStep.parentLocator,node:w.plan.insertStep.node,placement:w.plan.insertStep.placement,...w.plan.insertStep.anchorLocator?{anchorLocator:w.plan.insertStep.anchorLocator}:{}}):{ok:!1,source:F,diagnostic:{code:"unsupported-syntax",message:"Route composition rewrite has no insertion step."}};if(!O.ok)return{ok:!0,data:oe(f,B.AST_PARSE_ERROR,O.diagnostic.message)};let z=pn({source:O.source,moduleSpecifier:w.plan.importStep.moduleSpecifier,imports:w.plan.importStep.imports});if(!z.ok)return{ok:!0,data:oe(f,B.AST_PARSE_ERROR,z.diagnostic.message)};let pe=M.files.map(ye=>({operation:"create-only",file:ye.path,content:ye.content})),se=[{operation:"upsert",file:y.entryFile,content:z.source,baseContentHash:ae(F)},...pe];m+=1;try{let ye=await hr({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:se}});return!ye.ok&&ye.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:ye.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:ye}}finally{m-=1}}});return j.ok?j.data:oe(f,B.VERSION_STALE,j.error.message,{materializationCode:j.error.code})}async function Bf(f,y){if(f.kind!=="move-node"&&f.kind!=="remove-node")return oe(f,B.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let g=y.document,I=y.pageCompositionProjection;if(!g||g.pageComposition?.status!=="supported"||!I||I.status!=="supported")return oe(f,B.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==g.version||I.documentVersion!==g.version)return oe(f,B.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${g.version}).`);let P=await n.readFile(y.entryFile),T=Vc({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:g.version,expectedDocumentVersion:f.documentVersion,source:P,projection:I,placementUnitKey:f.target.placementUnitKey,operation:f.kind,targetPlacement:f.kind==="move-node"&&f.params.kind==="move-node"&&"kind"in f.params.target&&f.params.target.kind==="page-composition"?f.params.target:void 0});if(!T.ok)return oe(f,Ba(T.error.code),T.error.message,{diagnostics:T.error.diagnostics});let j=T.plan.rewriteStep.kind==="move-node"?fn({source:P,locator:T.plan.rewriteStep.locator,targetParentLocator:T.plan.rewriteStep.targetParentLocator,placement:T.plan.rewriteStep.placement,...T.plan.rewriteStep.anchorLocator?{anchorLocator:T.plan.rewriteStep.anchorLocator}:{}}):cn({source:P,locator:T.plan.rewriteStep.locator});if(!j.ok)return oe(f,B.AST_PARSE_ERROR,j.diagnostic.message);let M=j.source,F=[];if(f.kind==="remove-node"){let X=await Vf({routeState:y,placementUnitKey:f.target.placementUnitKey,source:P,mutatedSource:M});M=X.source,F=await Promise.all(X.files.map(async Y=>({operation:"delete",file:Y,baseContentHash:ae(await n.readFile(Y))})))}let V=[{operation:"upsert",file:y.entryFile,content:M,baseContentHash:ae(P)},...F];m+=1;try{return await hr({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:V}})}finally{m-=1}}async function Vf(f){let y={source:f.mutatedSource,files:[]},g=f.routeState.graph,I=f.routeState.pageCompositionProjection;if(!g||!I||I.status!=="supported"||!n.listFiles)return y;let T=I.placementUnitByKey.get(f.placementUnitKey)?.sourceRange;if(!T)return y;let j=[...g.elements.values()].find(se=>se.sourceFile===f.routeState.entryFile&&se.importedFrom&&N(se.sourceRange,T));if(!j?.importedFrom||!j.exportName)return y;let M=C(j.importedFrom),F="components/site/generated/";if(!M.startsWith(F))return y;let V=M.slice(F.length).split("/")[0];if(!V||!/-[0-9a-f]{8}$/i.test(V))return y;let X=`${F}${V}`;if([...g.elements.values()].filter(se=>se.sourceFile===f.routeState.entryFile&&C(se.importedFrom??"")===M).length!==1)return y;let ee=await n.listFiles({maxFiles:5e3,maxDepth:32}),w=Array.isArray(ee)?ee:ee.files;if(!Array.isArray(ee)&&ee.truncated)return y;let O=w.map(({path:se})=>se).filter(se=>se===X||se.startsWith(`${X}/`));if(O.length===0||!O.includes(M))return y;for(let{path:se}of w)if(!(se===f.routeState.entryFile||se===X||se.startsWith(`${X}/`)))try{if((await n.readFile(se)).includes(V))return y}catch{return y}let z=A(f.routeState.entryFile,M),pe=mn({source:f.mutatedSource,moduleSpecifier:z,imports:j.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:j.exportName}]});return pe.ok?{source:pe.source,files:O.sort((se,ye)=>se.localeCompare(ye))}:y}async function Uf(f){if(n.getFileInfo){for(let P of f)if(await n.exists(P.path)&&await n.getFileInfo(P.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${P.path}`,details:{path:P.path}}}let y=$f(f);if(y.length===0)return{ok:!0};let g=ES(n,f),I=sr({projectRoot:e.projectRoot,fileSystem:g,routes:[...o.values()].map(P=>({routeId:P.routeId,entryFile:P.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let P of y)await I.setActiveRoute(P)}catch(P){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${_e(P)}`,details:{routeIds:y}}}finally{I.dispose()}return{ok:!0}}function $f(f){return f.map(g=>g.path).some(tf)?[...o.keys()]:[]}function Jo(f,y,g,I){let P=ir(y);return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:P,message:g,...I?{details:I}:{}}}}async function Xo(f){let y=[];for(let g of new Set(f))y.push(await Kf(g));return y}async function Kf(f){if(!(typeof n.exists=="function"?await n.exists(f):!0))return{file:f,content:"",version:Math.max(0,Z(f)),exists:!1};let g=await n.readFile(f);return{file:f,content:g,version:Math.max(1,Z(f)),exists:!0,sha256:ae(g)}}async function Fa(f,y,g,I){if(!e.historyStore)return null;let P=I.historyTransition;if(!P)throw new Error("Durable history did not provide an exact index transition.");let T=new Map(y.map(F=>[F.file,F])),j=new Map(g.map(F=>[F.file,F])),M=[...new Set([...T.keys(),...j.keys()])].sort().map(F=>{let V=T.get(F),X=j.get(F);return{path:F,preDigest:V?.exists===!1||!V?null:ae(V.content),postDigest:X?.exists===!1||!X?null:ae(X.content)}});return{schemaVersion:2,transactionId:`${f}:${P.expectedIndexDigest}`,operationId:f,phase:"prepared",historyTransition:P,files:M}}async function Ma(f){return!f||!e.historyStore||await e.historyStore.writeTransactionJournal(f),f}async function Zt(f){f&&e.historyStore&&await e.historyStore.clearTransactionJournal(f.transactionId)}async function Ho(f,y){let g=[];try{for(let I of f)await Oa(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),g.push(I.file)}catch(I){let P=await Jf(y.filter(T=>g.includes(T.file)));return P.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${_e(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${P.failedFiles.join(", ")}: ${_e(I)}`,rolledBack:!1}}return{ok:!0,snapshots:f.map(Xf)}}async function Oa(f){if(f.exists===!1){await n.deleteFile(f.file);return}await n.writeFile(f.file,f.content)}async function Jf(f){let y=[];for(let g of f)try{await Oa(g),typeof n.bumpVersion=="function"&&n.bumpVersion(g.file)}catch{y.push(g.file)}return y.length===0?{ok:!0}:{ok:!1,failedFiles:y}}function Xf(f){let y=f.exists!==!1;return{file:f.file,content:y?f.content:"",version:f.version,exists:y,...y?{sha256:ae(f.content)}:{}}}async function hr(f){return b.runExclusive(()=>Hf(f))}async function Hf(f){let y=f.filePlan.edits.map(w=>w.file),g=await Xo(y),I=new Map(g.filter(w=>w.exists!==!1).map(w=>[w.file,w.content])),P=p,T=Da(),j=new Map(d),M=f.filePlan.edits.map(w=>w.operation==="delete"?{file:w.file,content:"",version:0,exists:!1}:{file:w.file,content:w.content,version:0,exists:!0,sha256:ae(w.content)}),F={operationId:f.filePlan.operationId,intents:f.filePlan.edits.map(w=>w.operation==="delete"?{kind:"delete",path:w.file}:{kind:w.operation==="create-only"?"create-only":"upsert",path:w.file,content:w.content})},V=null,X=!1,Y=await Io({overlay:I,exists:w=>n.exists(w),plan:F,buildCandidate:async({plan:w})=>({plan:w}),prepareHistory:async()=>{let w=await l.prepareAppend({operationId:f.request.id,kind:f.request.kind,target:f.request.target,preSnapshots:g,postSnapshots:M,...f.selectionRef?{selectionRef:f.selectionRef}:{}});return V=await Fa(f.request.id,g,M,w),V=await Ma(V),w},reverify:async()=>{},writeCandidate:async()=>{let w=await u.executeFilePlan(f.filePlan);if(!w.ok)throw new Co(w);return{postSnapshots:await Xo(w.affectedFiles),affectedFiles:w.affectedFiles,internalResultVersion:w.resultVersion}},validateCandidate:async({candidate:w,receipt:O})=>{let z=await mr(O.affectedFiles,{changed:!0,minimumVersion:O.internalResultVersion,publish:!1});if(z.failedRoutes.length>0)throw new Yt(z.failedRoutes);let pe=La(T,z.candidateRouteStates??[]),se=Math.max(O.internalResultVersion,...z.rebuiltRoutes.map(ye=>ye.version));return{...w,rebuild:z,routeSnapshots:pe,resultVersion:se,...Qd(f.selectionRef,pe.map(ye=>ye.state.document))?{selectionRef:Qd(f.selectionRef,pe.map(ye=>ye.state.document))}:{}}},publishCandidate:async({candidate:w,history:O,receipt:z})=>{if(!O)throw new Error("history intent is missing");await l.publishPrepared(O),X=!0;let pe=w.resultVersion??z.internalResultVersion;return{requestId:f.request.id,kind:f.request.kind,target:f.request.target,ok:!0,resultVersion:pe,affectedFiles:z.affectedFiles,...w.selectionRef?{selectionRef:w.selectionRef}:{}}},swapCandidate:({candidate:w,receipt:O})=>{w.routeSnapshots&&gr(w.routeSnapshots),w.rebuild?.candidateSourceCache&&kn(d,w.rebuild.candidateSourceCache),Qs(d,O.postSnapshots),p=Math.max(p,w.resultVersion??P)},finalizeCandidate:async()=>{await Zt(V)},emitCommitted:({candidate:w,published:O})=>{Ko(O,w.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:w,receipt:O})=>{if(X)throw new Error("history was published before transaction finalization failed");if(O){let z=await Ho(g,O.postSnapshots);if(!z.ok)throw new Error(z.reason)}gr(T),kn(d,j),p=P,w&&await l.discardPrepared?.(w),await Zt(V)}});if(Y.ok)return Y.published;if(Y.stage==="precheck"||Y.stage==="build")try{await Zt(V)}catch(w){let O=await yr(_e(w));return oe(f.request,O,"Unable to clear an uncommitted transaction journal.")}if(Y.recoveryRequired){let w=await yr(Y.reason);return oe(f.request,w===B.RECOVERY_PERSIST_FAILED?w:B.ROLLBACK_FAILED,Y.reason)}let ee=Y.error;return ee instanceof Co?{...oe(f.request,ir(ee.result.errorCode),ee.result.reason),...ee.result.affectedFiles?{affectedFiles:ee.result.affectedFiles}:{}}:ee instanceof Yt?oe(f.request,B.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${ea(ee.failedRoutes)}`,{failedRoutes:ee.failedRoutes}):oe(f.request,ja(Y.stage),_e(ee))}async function _a(f){return b.runExclusive(async()=>{let y=f==="undo"?await l.prepareUndo():await l.prepareRedo();return y?zf(f,y):{requestId:f,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:B.INTERNAL_ERROR,message:f==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function zf(f,y){let g=y.entry,I=f==="undo"?g.preSnapshots:g.postSnapshots,P=f==="undo"?g.postSnapshots:g.preSnapshots,T=I.map(O=>O.file),j=await Xo(T),M=new Map(j.filter(O=>O.exists!==!1).map(O=>[O.file,O.content])),F=p,V=Da(),X=new Map(d),Y=null,ee=!1,w=await Io({overlay:M,plan:{operationId:`${f}:${g.operationId}`,intents:I.map(O=>O.exists===!1?{kind:"delete",path:O.file}:{kind:"upsert",path:O.file,content:O.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(Y=await Fa(`${f}:${g.operationId}`,j,I,y),Y=await Ma(Y),y),reverify:async()=>{},writeCandidate:async()=>{let O=await Ho(I,P);if(!O.ok)throw new Error(O.reason);return{snapshots:O.snapshots}},validateCandidate:async({candidate:O})=>{let z=await mr(T,{changed:!0,minimumVersion:p+1,publish:!1});if(z.failedRoutes.length>0)throw new Yt(z.failedRoutes);let pe=La(V,z.candidateRouteStates??[]),se=Math.max(p+1,...z.rebuiltRoutes.map(ye=>ye.version));return{...O,rebuild:z,routeSnapshots:pe,resultVersion:se}},publishCandidate:async({candidate:O,history:z})=>{if(!z)throw new Error("history cursor intent is missing");await l.publishPrepared(z),ee=!0;let pe=O.resultVersion??p+1;return{requestId:f,kind:g.kind,target:g.target,ok:!0,resultVersion:pe,affectedFiles:T}},swapCandidate:({candidate:O,receipt:z})=>{O.routeSnapshots&&gr(O.routeSnapshots),O.rebuild?.candidateSourceCache&&kn(d,O.rebuild.candidateSourceCache),Qs(d,z.snapshots),p=Math.max(p,O.resultVersion??F)},finalizeCandidate:async()=>{await Zt(Y)},emitCommitted:({candidate:O,published:z})=>Ko(z,O.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:O,receipt:z})=>{if(ee)throw new Error("history cursor was published before transaction finalization failed");if(z){let pe=await Ho(P,z.snapshots);if(!pe.ok)throw new Error(pe.reason)}gr(V),kn(d,X),p=F,O&&await l.discardPrepared?.(O),await Zt(Y)}});if(w.ok)return w.published;if(w.stage==="precheck"||w.stage==="build")try{await Zt(Y)}catch(O){let z=await yr(_e(O));return{requestId:f,kind:g.kind,target:g.target,ok:!1,resultVersion:p,error:{code:z,message:"Unable to clear an uncommitted transaction journal."}}}if(w.recoveryRequired){let O=await yr(w.reason);return{requestId:f,kind:g.kind,target:g.target,ok:!1,resultVersion:p,affectedFiles:T,error:{code:O===B.RECOVERY_PERSIST_FAILED?O:B.ROLLBACK_FAILED,message:w.reason}}}return{requestId:f,kind:g.kind,target:g.target,ok:!1,resultVersion:p,affectedFiles:T,error:{code:w.error instanceof Yt?B.ROUTE_REBUILD_FAILED:ja(w.stage),message:_e(w.error),...w.error instanceof Yt?{details:{failedRoutes:w.error.failedRoutes}}:{}}}}function Da(){return[...o.values()].map(f=>({routeId:f.routeId,state:{...f,dependencyFiles:new Set(f.dependencyFiles),fileVersions:new Map(f.fileVersions)}}))}function La(f,y){let g=new Map(f.map(I=>[I.routeId,I]));for(let I of y)g.set(I.routeId,I);return[...g.values()]}function gr(f){for(let y of o.values())R(y);for(let y of f){let g={...y.state,dependencyFiles:new Set(y.state.dependencyFiles),fileVersions:new Map(y.state.fileVersions)};o.set(y.routeId,g),ue(g,g.dependencyFiles)}}async function zo(f){let y=o.get(f);if(!y)throw new Error(`Route not found: ${f}`);if(y.graph)return;let g=await n.readFile(y.entryFile);await he(f,g)}function Rn(f,y){if(y){let g=o.get(y)??null;return!g||!Wo(g,f)?null:g}for(let g of o.values())if(Wo(g,f))return g;return null}function Wo(f,y){if(f.documentIndex?.entriesByKey.has(y)||f.graph?.elements.has(y))return!0;let g=Ke(y);return g&&g!==y?f.graph?.elements.has(g)===!0:!1}function oe(f,y,g,I){return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:y,message:g,...I?{details:I}:{}}}}function ja(f){return f==="validate"?B.ROUTE_REBUILD_FAILED:f==="publish"?B.HISTORY_COMMIT_FAILED:B.WRITE_IO_ERROR}async function yr(f){if(E=!0,!l.markRecoveryRequired)return B.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(f),B.RECOVERY_REQUIRED}catch{return B.RECOVERY_PERSIST_FAILED}}function Wf(f){let g=f.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return g?`Prefab${g}`:"GeneratedPrefab"}function Ba(f){return f==="VERSION_STALE"?B.VERSION_STALE:f==="CROSS_PAGE_MOVE_UNSUPPORTED"?B.CROSS_PAGE_MOVE_UNSUPPORTED:B.UNSUPPORTED_OPERATION}async function Va(f){if(f.target.kind==="route"){let g=o.get(f.target.routeId)??null;return g?(g.graph||await zo(g.routeId),g):oe(f,B.ROUTE_NOT_FOUND,`Route not found: ${f.target.routeId}`)}if(f.target.kind==="page-unit"){let g=o.get(f.target.routeId)??null;return g?(g.graph||await zo(g.routeId),g):oe(f,B.ROUTE_NOT_FOUND,`Route not found: ${f.target.routeId}`)}if(f.target.kind!=="node")return oe(f,B.UNSUPPORTED_OPERATION,`${f.kind} source target execution is not implemented yet.`);if(!f.routeId)return oe(f,B.INVALID_TARGET,"routeId is required when executing a node target");let y=o.get(f.routeId)??null;return y?(y.graph||await zo(y.routeId),Wo(y,f.target.key)?y:oe(f,B.NODE_NOT_FOUND,`Target key not found: ${f.target.key}`)):oe(f,B.ROUTE_NOT_FOUND,`Route not found: ${f.routeId}`)}return{get status(){return t},dispose(){t="disposed",a.clear(),o.clear(),i.clear(),d.clear(),s=null},registerRoute(f,y){let g=o.get(f);if(g?.entryFile===y)return;g&&R(g);let I=Zd(f,y);o.set(f,I),ue(I,I.dependencyFiles),r.emit({type:"graph-invalidated",routeId:f})},unregisterRoute(f){let y=o.get(f);y&&(R(y),o.delete(f),s===f&&(s=null,t="idle"),r.emit({type:"graph-invalidated",routeId:f}))},getRouteEntryFiles(){return[...o.values()].map(f=>f.entryFile)},async setActiveRoute(f){let y=o.get(f);if(!y)throw new Error(`Route not found: ${f}`);let g=s===f;if(s=f,!y.graph){t="building";try{let I=await n.readFile(y.entryFile);await he(f,I);let P=o.get(f)?.graph?.version??1;t="ready",r.emit({type:"graph-ready",routeId:f,version:P})}catch(I){throw t="idle",r.emit({type:"graph-error",routeId:f,message:_e(I)}),I}return}t="ready",g||r.emit({type:"graph-ready",routeId:f,version:y.graph.version})},getDocument(f){let y=o.get(f);if(!y)throw new Error(`Route not found: ${f}`);if(!y.document)throw new Error(`Route not built: ${f}`);return y.document},async getHistoryStatus(){await v;let f=await l.getStatus?.();return f?{...f,recoveryRequired:E}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:E}},getObjectEditContext(f,y){let g=Rn(f,y),I=Ke(f)??f;if(g?.graph&&g.topology&&g.capabilities&&g.detailProjections){let P=g.detailProjections.get(I);if(P){let T=el(I,g.graph,g.topology,g.capabilities,P.textSources,P.provenances,P.dynamicData);return f===I?T:BS(T,f,g.document??null,g.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getRenderDetail(f,y){let g=Rn(f,y),I=Ke(f)??f;if(g?.graph&&g.topology&&g.capabilities&&g.detailProjections){let P=g.detailProjections.get(I);if(P){let T=qc(I,g.graph,g.topology,g.capabilities,P.textSources,P.writeTarget,P.provenances,P.conditional,P.componentSemantic,P.contentModel,P.mediaModel,P.styleSource,P.dynamicData);return f===I?T:jS(T,f,g.document??null,g.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getClassNameSource(f,y){let g=Rn(f,y),I=Ke(f)??f;if(!g?.graph)throw new Error(`Key not found: ${f}`);let P=g.graph.elements.get(I);if(!P)throw new Error(`Key not found: ${f}`);let T=d.get(P.sourceFile);if(T===void 0)throw new Error(`Source not loaded: ${P.sourceFile}`);return yl({key:I,route:{routeId:g.routeId,graph:g.graph,source:T}})},refreshSourceForKey:Df,async execute(f){if(await v,E)return oe(f,B.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(f.kind==="source-edit")return await Ta(f),Lf(f);let y=await Va(f);if("ok"in y)return y;await Ta(f);let g=await Va(f);if("ok"in g)return g;let I=g;if(f.target.kind==="page-unit"){let M=f;return f.kind==="insert-child"?jf(M,I):f.kind==="move-node"||f.kind==="remove-node"?Bf(M,I):oe(f,B.UNSUPPORTED_OPERATION,"Only page-unit insert-child, move-node, and remove-node are currently supported by the page composition transaction.")}if(!I.graph||!I.topology||!I.capabilities)return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:f.target.kind==="route"?B.ROUTE_NOT_FOUND:B.NODE_NOT_FOUND,message:f.target.kind==="route"?`Route not ready: ${f.target.routeId}`:f.target.kind==="node"?`Target key not found: ${f.target.key}`:`${f.kind} source target execution is not implemented yet.`}};let P=CS(I,I.graph,I.capabilities,d,o),T=await new uo(P).plan(f);if(!T.ok)return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:ir(T.errorCode),message:T.reason}};let j=T.plan;if(j.steps.length===0)return f.kind==="set-props"?{requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:p,affectedFiles:[]}:{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:B.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};m+=1;try{if(j.steps.some(F=>F.type==="invoke-external-adapter")){let F=await u.execute(j);if(!F.ok)return oe(f,ir(F.errorCode),F.reason);let V={requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:Math.max(p,F.resultVersion),affectedFiles:F.affectedFiles,...F.selectionRef?{selectionRef:F.selectionRef}:{}};return Ko(V,{rebuiltRoutes:[],failedRoutes:[]}),V}let M=await u.prepareRewritePlan(j);return M.ok?await hr({request:f,filePlan:M.filePlan,...M.selectionRef?{selectionRef:M.selectionRef}:{}}):oe(f,ir(M.errorCode),M.reason)}catch(M){return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:B.INTERNAL_ERROR,message:_e(M)}}}finally{m-=1}},async undo(f){if(await v,E)return{requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:B.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};m+=1;try{return await _a("undo")}finally{m-=1}},async redo(f){if(await v,E)return{requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:B.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};m+=1;try{return await _a("redo")}finally{m-=1}},notifyFileChanged(f){wa([f])},subscribe(f){return r.subscribe(f)}}}function kS(e,t,n){let r=new Map;for(let i of t.elements.values()){if(i.sourceFile!==n.entryFile||!i.importedFrom||!/^[A-Z]/.test(i.tag))continue;let s=n.placements.find(c=>c.members.some(l=>l.sourceRange!==null&&ta(i.sourceRange,l.sourceRange)));if(!s)continue;let a=s.placementUnitKey;r.set(`${i.importedFrom}#${i.tag}`,a),i.exportName&&i.exportName!==i.tag&&r.set(`${i.importedFrom}#${i.exportName}`,a)}let o=n.placements.find(i=>i.placementKey===n.container.placementKey&&i.relation==="append");for(let i of e.entries){let s=t.elements.get(i.key);if(!s)continue;if(s.sourceFile===n.entryFile){if(n.container.sourceRange&&ta(s.sourceRange,n.container.sourceRange)&&o){i.pageCompositionUnitKey=o.placementUnitKey;continue}let c=n.placements.find(l=>l.members.some(u=>u.sourceRange!==null&&(ta(s.sourceRange,u.sourceRange)||vS(u.sourceRange,s.sourceRange))));if(c){i.pageCompositionUnitKey=c.placementUnitKey;continue}}let a=r.get(`${s.sourceFile}#${s.componentName}`);a&&(i.pageCompositionUnitKey=a)}}function ta(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function vS(e,t){return ef(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&ef(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function ef(e,t,n,r){return e!==n?e-n:t-r}function CS(e,t,n,r,o){let i=new Map,s=new Map,a=(u,d)=>{if(s.has(u))return;s.set(u,d);let p=t.elements.get(u);for(let m of p?.childKeys??[])a(m,d)};for(let u of t.regions)if(u.kind==="repeat-region")for(let d of u.childKeys)i.set(d,u.ownerKey),a(d,u.ownerKey);return{getNode(u){let d=c(u),p=t.elements.get(d.baseKey);return p?l(u,p):null},getChildNodes(u){let d=c(u),m=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(m)return m.map(b=>{let v=Ke(b)??b,C=t.elements.get(v);return C?l(b,C):null}).filter(b=>b!==null);let E=t.elements.get(d.baseKey);return E?E.childKeys.map(b=>{let v=t.elements.get(b);return v?l(b,v):null}).filter(b=>b!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,d])=>({file:u,content:d}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let d=c(u),p=n.get(d.baseKey);return p?{...p,key:u,constraints:p.constraints.map(m=>({...m})),...p.editModes?{editModes:{...p.editModes}}:{}}:{key:u,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(u){return r.get(u)??""},getFileVersion(u){return Math.max(e.fileVersions.get(u)??0,t.version)},getRouteEntryFile(u){return e.routeId===u?e.entryFile:null},getComponentSemantic(u){let d=c(u);return e.detailProjections?.get(d.baseKey)?.componentSemantic??null},getEditableTextSegmentIndex(u){let d=c(u),m=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return m&&!m.done?m.value:null},async getTextWriteTarget(u,d){let p=c(u);return rf(e.detailProjections?.get(p.baseKey)?.textTargets.get(d)??null,p.repeatIndex)},async getElementPropertyWriteTarget(u,d){let p=c(u);return rf(e.detailProjections?.get(p.baseKey)?.elementPropertyTargets.get(d)??null,p.repeatIndex)},getTextProvenance(u,d){let p=c(u);return e.detailProjections?.get(p.baseKey)?.provenances.get(d)??null}};function c(u){let d=nS(u);return d?{baseKey:d.baseKey,repeatIndex:_S(e.document??null,u,d.baseKey,e.documentIndex)??OS(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let p=Ke(u)??u,m=e.documentIndex?.entriesByKey.get(u),E=e.detailProjections?.get(p);return{key:u,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:m?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(p),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(p),repeatOwnerKey:i.get(p)??s.get(p),contentModel:E?.contentModel,attributes:d.attributes?.map(b=>({name:b.name,value:b.value,source:b.source?{expression:b.source.expression,base:b.source.base,path:b.source.path.map(v=>({...v}))}:null,resolvedValue:b.resolvedValue}))}}}var RS={"stale-version":B.VERSION_STALE,"capability-denied":B.CAPABILITY_REJECTED,"invalid-params":B.INVALID_PARAMS,"locator-miss":B.LOCATOR_FAILED,"route-not-found":B.ROUTE_NOT_FOUND,"unsupported-operation":B.UNSUPPORTED_OPERATION,"invalid-target":B.INVALID_TARGET,"ast-error":B.AST_PARSE_ERROR,"writeback-failed":B.WRITE_IO_ERROR,"rollback-failed":B.RECOVERY_REQUIRED,unknown:B.INTERNAL_ERROR};function ir(e){return RS[e]}function _e(e){return e instanceof Error&&e.message?e.message:String(e)}function tf(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function PS(e){let t=Gt(e);if(!iS.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=>sS.map(a=>`${s}/${a}`))}function wS(e){let n=Gt(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function AS(e){return of(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function NS(e){return of(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function of(e,t){let n=[];for(let r of e.matchAll(t)){let o=sf(r[1]??"");o&&n.push(o)}return n}function nf(e,t){let n=sf(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Gt(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Gt(`${TS(e)}/${n}`):n.startsWith("/")?Gt(n.slice(1)):na(n)?Gt(n):null}function sf(e){return e.split(/[?#]/,1)[0]?.trim()??""}function na(e){return/\.css$/i.test(e)}function TS(e){let t=Gt(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function af(e){return Array.from(new Set(e))}function Gt(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 FS(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 vo(e){return e?.map(t=>({...t}))}function rf(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=vo(e.collectionPathMap?.[t])??vo(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:vo(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>vo(o)??[])}}function MS(e,t,n){let r=new Set;for(let m of t.regions)if(m.kind==="repeat-region")for(let E of m.childKeys)r.add(E);if(r.size===0)return e;let o=new Map(e.entries.map(m=>[m.key,m])),i=[],s=new Map,a=(m,E)=>qE(m,E),c=(m,E,b)=>{let v=o.get(m);if(!v)return a(m,b);let C=a(m,b),A={...v,key:C,parentKey:E,childKeys:[]};return i.push(A),A.childKeys=v.childKeys.flatMap(N=>l(N,b,C)),C},l=(m,E,b)=>{if(!r.has(m))return[c(m,b,E)];let v=d(m,E),C=[];for(let A=0;A<v;A+=1)C.push(c(m,b,[...E,A]));return C},u=af([...e.rootKeys,...e.entries.filter(m=>m.parentKey===null).map(m=>m.key)]);for(let m of u){if(!r.has(m)){c(m,null,[]);continue}let E=d(m,[]);for(let b=0;b<E;b+=1)c(m,null,[b])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(m,E){let b=new Set;for(let v of p(m)){let C=n.get(v);if(C){for(let A of[...C.textTargets.values(),...C.elementPropertyTargets.values()])if(!(A?.kind!=="value-binding"||A.sourceKind!=="repeat-template"))for(let N of DS(A))N.length<=E.length||LS(N,E)&&b.add(N[E.length])}}return b.size>0?b.size:FS(n.get(m))}function p(m){let E=s.get(m);if(E)return E;let b=[m],v=o.get(m);for(let C of v?.childKeys??[])b.push(...p(C));return s.set(m,b),b}}function OS(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function _S(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((Ke(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function DS(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 LS(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 jS(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 BS(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}}import aa from"node:path";import{TextDecoder as VS}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as lf,SITE_EDIT_SOURCE_ALLOWED_DIRS as uf,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as df,SiteEditSourceFileResponseSchema as ra,SiteEditSourceLocationSchema as US,SiteEditSourcePathSchema as Ro,SiteEditSourceTreeResponseSchema as $S,isSiteEditTextSourcePath as KS}from"@vcp-dev/contracts";var JS=[...df,...lf,...uf],oa=2e3,ia=12,sa=24*1024*1024,cf=512*1024,XS=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),HS={".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"},zS={".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"},WS=new VS("utf-8",{fatal:!0});async function Po(e,t={}){let{files:n,truncated:r}=await nb(e,t),o=ib(n.map(i=>i.metadata));return $S.parse({nodes:o,defaultPath:sb(n.map(i=>i.metadata)),totalFiles:n.length,...r?{truncated:r}:{}})}async function wo(e,t,n={}){let r=Ro.parse(t.path),o=await ZS(e,r,n);if(!o)throw new Error(`Source file not found: ${r}`);if(ca(r)){let s=mf(r),a=await qS(e,{path:r,sizeBytes:o.sizeBytes,mimeType:s});return ra.parse({path:r,kind:"binary",language:null,sizeBytes:o.sizeBytes,mimeType:s,readonly:!0,...a})}let i=await YS(e,r);return i.ok?ra.parse({path:r,kind:"text",language:hf(r),sizeBytes:i.sizeBytes,contentHash:ae(i.content),readonly:!1,content:i.content}):ra.parse({path:r,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function YS(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=GS(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 GS(e){if(e.includes(0))return null;try{return WS.decode(e)}catch{return null}}async function ZS(e,t,n){if(!eb(t,n))return null;let r=await QS(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function QS(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=ff(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(ca(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function qS(e,t){if(!XS.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>cf)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>cf?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function eb(e,t){return df.some(n=>n===e)||lf.some(n=>n===e)||uf.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Ro.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 US.parse({key:e.key,routeId:e.routeId,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 ff(e){return Array.isArray(e)?{files:e}:e}function tb(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function nb(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=ff(await e.listFiles({roots:rb(t),maxFiles:oa+1,maxDepth:ia,maxTotalBytes:sa+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=Ro.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>ia){o.add("max-depth");continue}if(r.size>=oa){o.add("max-files");break}if(i+a.sizeBytes>sa){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:ob(l,a.sizeBytes)}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:tb([...o]),maxFiles:oa,maxDepth:ia,maxTotalBytes:sa}}:{}}}function rb(e){let t=new Set(JS);for(let n of e.routeEntryFiles??[]){let r=Ro.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function ob(e,t){return ca(e)?{path:e,kind:"binary",language:null,sizeBytes:t,mimeType:mf(e),readonly:!0}:{path:e,kind:"text",language:hf(e),sizeBytes:t,readonly:!1}}function ib(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 pf(t)}function pf(e){return e.map(t=>t.kind==="directory"?{...t,children:pf(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function sb(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 ca(e){return!KS(e)}function mf(e){let t=aa.posix.extname(e).toLowerCase();return!t&&aa.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":HS[t]??"application/octet-stream"}function hf(e){let t=aa.posix.extname(e).toLowerCase();return zS[t]??"plaintext"}var No=class{constructor(t){this.options=t,this.fileSystem=new jn(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}async setActiveRoute(t){await this.engine.setActiveRoute(t)}getDocument(t){return Ir(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){return kr(this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(){return Po(this.fileSystem,{routeEntryFiles:this.options.routes.map(t=>t.entryFile)})}getSourceFile(t){return wo(this.fileSystem,t,{routeEntryFiles:this.options.routes.map(n=>n.entryFile)})}resolveSourceLocation(t){return Ao(t,this.engine.getRenderDetail(t.key,t.routeId))}async planOperation(t){let n=cb.safeParse(t);if(!n.success)return{result:br(t,n.error.issues.map(i=>i.message))};let r=new jn(this.options.files),o=this.createEngine(r,{emitEvents:!1});try{for(let u of this.getPlanningRouteIds(n.data))await o.setActiveRoute(u);let i=this.withInferredNodeRouteId(n.data,o),s=await o.execute(i);if(!s.ok)return{result:{ok:!1,error:{code:s.error?.code??"INTERNAL_ERROR",message:s.error?.message??"Operation failed"},data:{requestId:s.requestId,kind:s.kind,target:s.target,resultVersion:s.resultVersion}}};let a={ok:!0,data:Ot(s)},c=r.getChangedFiles();if(c.length===0)return{result:a};let l=lb.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:c.map(u=>ub(u,t.kind==="source-edit")),changedRouteIds:this.getChangedRouteIds(c.map(u=>u.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:l.patches.map(u=>u.path),at:new Date().toISOString()}),{result:a,patchPlan:l}}finally{o.dispose()}}dispose(){this.engine.dispose()}getPlanningRouteIds(t){let n=this.getExplicitPlanningRouteId(t);if(n){let r=this.options.routes.find(o=>o.routeId===n);return r?[r.routeId]:this.options.routes.map(o=>o.routeId)}if(t.target.kind==="node"){let r=this.getBuiltRouteIdsForKey(t.target.key);if(r.length>0)return r}return this.options.routes.map(r=>r.routeId)}getExplicitPlanningRouteId(t){if(t.routeId)return t.routeId;if(t.target.kind==="route")return t.target.routeId;if(t.params.kind==="set-class-name-source")return t.params.routeId;if(t.params.kind==="apply-style-draft")return t.params.className?.routeId}getBuiltRouteIdsForKey(t){let n=[];for(let r of this.options.routes)try{this.engine.getRenderDetail(t,r.routeId),n.push(r.routeId)}catch{}return n}withInferredNodeRouteId(t,n){if(t.target.kind!=="node"||t.routeId)return t;let r=this.findRouteIdForNodeTarget(n,t.target.key);return r?{...t,routeId:r}:t}findRouteIdForNodeTarget(t,n){for(let r of this.options.routes)try{if(t.getDocument(r.routeId).entries.some(i=>i.key===n))return r.routeId}catch{}return this.options.routes.length===1?this.options.routes[0]?.routeId:void 0}createEngine(t,n={}){let r=n.emitEvents??!0;return sr({projectRoot:"/snapshot",fileSystem:t,routes:this.options.routes.map(o=>({routeId:o.routeId,entryFile:o.entryFile})),onEvent:r&&this.options.onEvent?o=>{let i=vr(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})}getChangedRouteIds(t){let n=new Set(t),r=new Set(this.options.routes.map(s=>s.entryFile));if(t.some(s=>!r.has(s)))return this.options.routes.map(s=>s.routeId);let i=this.options.routes.filter(s=>n.has(s.entryFile)).map(s=>s.routeId);return i.length>0?i:this.options.routes.map(s=>s.routeId)}};function ub(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ae(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ae(e.before)},fullContent:e.after}}function db(e){return new No(e)}import{SiteEditOperationRequestSchema as mb}from"@vcp-dev/contracts";import tt from"node:fs/promises";import Pe from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as fb,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as pb}from"@vcp-dev/contracts";var To=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=sr({...t,fileSystem:this.fileSystem})}get status(){return this.engine.status}registerRoute(t,n){this.engine.registerRoute(t,n)}unregisterRoute(t){this.engine.unregisterRoute(t)}async setActiveRoute(t){await this.engine.setActiveRoute(t)}getDocument(t){return this.engine.getDocument(t)}getHistoryStatus(){return this.engine.getHistoryStatus()}getObjectEditContext(t,n){return this.engine.getObjectEditContext(t,n)}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(){return Po(this.fileSystem,{routeEntryFiles:this.engine.getRouteEntryFiles()})}getSourceFile(t){return wo(this.fileSystem,t,{routeEntryFiles:this.engine.getRouteEntryFiles()})}resolveSourceLocation(t){return Ao(t,this.engine.getRenderDetail(t.key,t.routeId))}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 tt.readFile(Pe.join(n,r),"utf8")},async readFileBytes(r){return tt.readFile(Pe.join(n,r))},async getFileInfo(r){let o=Pe.join(n,...r.split("/"));try{let i=await tt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await Eo(Pe.join(n,r),o)},async createExclusive(r,o){let i=Pe.join(n,r);await tt.mkdir(Pe.dirname(i),{recursive:!0});let s=await tt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await tt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await tt.rm(Pe.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=Pe.join(n,i),a=Pe.dirname(Pe.join(n,o));for(;a!==s&&a.startsWith(`${s}${Pe.sep}`);){try{await tt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Pe.dirname(a);continue}break}a=Pe.dirname(a)}},async exists(r){try{return await tt.access(Pe.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...pb,...fb],i=[],s=new Set,a=0;for(let u of o)await l(u,i,1);let c=i.sort((u,d)=>u.path.localeCompare(d.path));return s.size>0?{files:c,truncated:{reasons:[...s]}}:{files:c};async function l(u,d,p){if(r.maxFiles!==void 0&&d.length>=r.maxFiles){s.add("max-files");return}if(r.maxDepth!==void 0&&p>r.maxDepth){s.add("max-depth");return}let m=Pe.join(n,...u.split("/")),E;try{E=await tt.lstat(m)}catch{return}if(E.isSymbolicLink())return;if(E.isFile()){if(r.maxTotalBytes!==void 0&&a+E.size>r.maxTotalBytes){s.add("max-total-bytes");return}d.push({path:u,sizeBytes:E.size}),a+=E.size;return}if(!E.isDirectory())return;let b=await tt.readdir(m,{withFileTypes:!0});for(let v of b)v.isSymbolicLink()||await l(`${u}/${v.name}`,d,p+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function la(e){return new To(e)}var Fo=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=la({projectRoot:t.projectRoot,fileSystem:t.fileSystem,routes:t.routes.map(n=>({routeId:n.routeId,entryFile:n.entryFile})),onEvent:n=>{let r=vr(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.initialDocumentVersion!==void 0?{initialDocumentVersion:t.initialDocumentVersion}:{},siteId:t.siteId,snapshotId:t.snapshotId})}get status(){return this.engine.status}registerRoute(t,n){this.engine.registerRoute(t,n)}unregisterRoute(t){this.engine.unregisterRoute(t)}async setActiveRoute(t){await this.engine.setActiveRoute(t)}getDocument(t){return{ok:!0,data:Ir(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return{ok:!0,data:this.engine.getDocument(t).styleContext??null}}async getHistoryStatus(){return{ok:!0,data:await this.engine.getHistoryStatus()}}getObjectEditContext(t,n){return{ok:!0,data:kr(this.engine.getObjectEditContext(t,n))}}getClassNameSource(t,n){return{ok:!0,data:this.engine.getClassNameSource(t,n)}}async getSourceTree(){return{ok:!0,data:await this.engine.getSourceTree()}}async getSourceFile(t){return{ok:!0,data:await this.engine.getSourceFile(t)}}resolveSourceLocation(t){return{ok:!0,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=mb.safeParse(r);if(!o.success)return br(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,error:{code:s.code,message:s.message},data:{requestId:i.requestId,kind:i.kind,target:i.target,resultVersion:i.resultVersion,...i.affectedFiles?.length?{affectedFiles:i.affectedFiles}:{}}}}return{ok:!0,data:Ot(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,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,data:Ot(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,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,data:Ot(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 hb(e){return new Fo(e)}import{createHash as gb,randomUUID as Sa}from"node:crypto";import me from"node:fs/promises";import Ie from"node:path";var Xe=1,da=1,yb=2,xb="index.json",Eb="recovery.json",Sb="transaction-journal.json",bb="document-version.json",Oo={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},K={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"},J=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 kf(e,t={}){let n=_b(e),r=jb(t.limits),o=ua(n),i=Db(n),s=await Je(i),a=await Je(o)||s;a||(await Pb(n),await wb(n)),a||await Bb(n);let c=await De(n),l=new Set(a?(await Bo(n)).map(d=>d.stageId):[]);a||await ar(n,c.entryIds);let u=async()=>{if(await Je(o)||s)throw new J(K.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return If(n)},async writeDocumentVersion(d){if(await u(),!Number.isInteger(d)||d<0)throw new J(K.INVALID_SCHEMA,"document version must be a non-negative integer");let p=await If(n);await cr(Tf(n),{schemaVersion:1,version:Math.max(p,d)})},async stageAppend(d,p={}){await u();let m=await yf(d,r),E={schemaVersion:da,stageId:Sa(),entryId:m.entryId,blobIds:m.blobs.map(b=>b.digest)};try{await xf(n,m),await vb(n,E,p.durableManifest!==!1)}catch(b){try{await Sf(n,E)}catch(v){throw new J(K.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:v})}throw b}return{stageId:E.stageId,entryId:E.entryId,blobIds:E.blobIds}},async discardStage(d){await u(),ha(d);let p=await pa(n,d);p&&await Sf(n,p)},async previewStagedAppend(d,p){return await u(),(await gf(n,r,d,p)).transition},async previewCursor(d,p){await u();let m=await De(n);return ga(m,p),fa(d,m.entryIds.length),vf(m,m.entryIds,d)},async publishStagedAppend(d,p,m){if(await u(),_o(d,"entryId"),m){ha(m);let b=await pa(n,m);if(!b||b.entryId!==d)throw new J(K.INVALID_SCHEMA,"history stage does not match the published entry")}let E=await gf(n,r,d,p);return bf({rootDir:n,previousDigest:E.current.digest,entryIds:E.entryIds,cursor:E.cursor,afterWrite:async()=>{m?await Do(n,m):await Rb(n,d),await ar(n,E.entryIds)}})},async append(d){await u();let p=await De(n),m=await yf(d,r),E=[...p.entryIds];p.cursor<E.length-1&&E.splice(p.cursor+1),E.push(m.entryId);try{await xf(n,m);let b=await Cf(n,E,r);return await Ia(n,b.entryIds,b.cursor),await ar(n,b.entryIds),De(n)}catch(b){throw await ar(n,p.entryIds),b}},async readEntry(d){return _o(d,"entryId"),ur(n,d)},async readBlob(d){_o(d,"blobId");let p=Cn(n,d),m=await Tt(p,K.NOT_FOUND,"blob");return ka(m,d,p),m},async readIndex(){return De(n)},async readStatus(){let d=await De(n);return{canUndo:d.undoIds.length>0,canRedo:d.redoIds.length>0,undoDepth:d.undoIds.length,redoDepth:d.redoIds.length,cursor:d.cursor,recoveryRequired:await Je(o)||await Je(i)}},async readUndoRedoIds(){let d=await De(n);return{undoIds:d.undoIds,redoIds:d.redoIds,currentId:d.currentId}},async setCursor(d,p){await u();let m=await De(n);return ga(m,p),fa(d,m.entryIds.length),bf({rootDir:n,previousDigest:m.digest,entryIds:m.entryIds,cursor:d})},async markRecoveryRequired(d){await Je(o)||await cr(ua(n),{schemaVersion:Xe,reason:Lb(d),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await me.rm(ua(n),{force:!0})},async readTransactionJournal(){return await Je(i)?Mo(i):null},async writeTransactionJournal(d){await u(),Ff(d);try{await cr(i,d)}catch(m){let E=await Mo(i).catch(()=>null);if(E&&Buffer.from(Le(E)).equals(Buffer.from(Le(d))))return;throw E?new J(K.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:m}):m}let p=await Mo(i);if(!Buffer.from(Le(p)).equals(Buffer.from(Le(d))))throw new J(K.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(d){let p=await Je(i)?await Mo(i):null;if(p&&p.transactionId!==d)throw new J(K.INVALID_SCHEMA,"transaction journal changed concurrently");try{await me.rm(i,{force:!0})}catch(m){if(!await Je(i))return;throw m}if(await Je(i))throw new J(K.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await u();for(let p of l)await Do(n,p),l.delete(p);await Ab(n);let d=await De(n);await ar(n,d.entryIds)}}}async function gf(e,t,n,r){_o(n,"entryId");let o=await De(e);ga(o,r);let i=await ur(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await Cf(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:vf(o,a.entryIds,a.cursor)}}function vf(e,t,n){return fa(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:Ib(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function Ib(e,t){return Ft(Le({schemaVersion:Xe,entryIds:e,cursor:t}))}function fa(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new J(K.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function kb(e){if(!nt(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Te(e.expectedIndexDigest)||!Te(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Te(n)?!1:t===-1?n===null:Te(n)}async function yf(e,t){if(!e.kind.trim())throw new J(K.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new J(K.INVALID_JSON,"history blob name must not be empty");let l=Ob(c.data),u=Ft(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:Xe,kind:e.kind,manifest:e.manifest,blobs:r},i=Le({...o}),s=Ft(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new J(K.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function xf(e,t){let n=fr(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Ef(Cn(e,a.digest),a.bytes,{kind:"blob",digest:a.digest})),Ef(n,Le(r),{kind:"entry",digest:t.entryId})],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Ef(e,t,n){let r=await Nf(e);if(r!==null){if(Buffer.compare(r,t)!==0)throw new J(n.kind==="blob"?K.BLOB_CORRUPT:K.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await wf(e,t)}async function Cf(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await Pf(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new J(K.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function vb(e,t,n){ba(t);let r=Ca(e,t.stageId);if(n){await cr(r,t);return}await Mb(r,t)}async function pa(e,t){let n=await Nf(Ca(e,t));if(n===null)return null;let r=dr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=ba(r);if(o.stageId!==t)throw new J(K.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Bo(e){let t=[];for(let n of await jo(va(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);ha(r);let o=await pa(e,r);o&&t.push(o)}return t}async function Sf(e,t){ba(t);let n=await De(e),r=(await Bo(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await ur(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 ma(fr(e,t.entryId));for(let s of t.blobIds)i.has(s)||await ma(Cn(e,s));await Do(e,t.stageId),await Ea(Uo(e)),await Ea($o(e))}async function Do(e,t){await ma(Ca(e,t)),await Cb(e)}async function Cb(e){try{await me.rmdir(va(e))}catch(t){if(pr(t)||nt(t)&&t.code==="ENOTEMPTY")return;throw t}}async function Rb(e,t){for(let n of await Bo(e))n.entryId===t&&await Do(e,n.stageId)}async function ma(e){if(await me.rm(e,{force:!0}),await Je(e))throw new J(K.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}function ba(e){if(!nt(e)||e.schemaVersion!==da||typeof e.stageId!="string"||!Rf(e.stageId)||!Te(e.entryId))throw new J(K.INVALID_SCHEMA,"history stage schema is invalid");let t=Af(e.blobIds,"history stage blobIds");return{schemaVersion:da,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function ha(e){if(!Rf(e))throw new J(K.INVALID_PATH,"history stageId must be a UUID")}function Rf(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 ar(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await ur(e,c);for(let u of l.blobs)r.add(u.digest)}for(let c of await Bo(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=Uo(e),i=await jo(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=c.slice(0,-5);Te(l)&&!n.has(l)&&await Lo(fr(e,l))}let s=$o(e),a=await jo(s);for(let c of a){let l=c;Te(l)&&!r.has(l)&&await Lo(Cn(e,l))}}async function De(e){let t=Vo(e),n=await Tt(t,K.NOT_FOUND,"index"),r=dr(Buffer.from(n).toString("utf8"),"index"),o=Nb(r),i=[...o.entryIds],{totalBytes:s}=await Pf(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:Xe,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function Pf(e,t){let n=0,r=new Set,o=Vo(e),i=await Tt(o,K.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await ur(e,s),c=fr(e,s),l=await Tt(c,K.NOT_FOUND,"entry");n+=l.byteLength;for(let u of a.blobs){if(r.has(u.digest))continue;r.add(u.digest);let d=Cn(e,u.digest),p=await Tt(d,K.NOT_FOUND,"blob");ka(p,u.digest,d),n+=p.byteLength}}return{totalBytes:n}}async function ur(e,t){let n=fr(e,t),r=await Tt(n,K.NOT_FOUND,"entry"),o=dr(Buffer.from(r).toString("utf8"),`entry ${t}`),i=Tb(o);if(i.id!==t)throw new J(K.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(Ft(Le({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new J(K.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=Cn(e,a.digest),l=await Tt(c,K.NOT_FOUND,"blob");ka(l,a.digest,c)}return i}async function Ia(e,t,n){let r={schemaVersion:Xe,digest:Ft(Le({schemaVersion:Xe,entryIds:t,cursor:n})),entryIds:t,cursor:n};await cr(Vo(e),r)}function ga(e,t){if(t!==void 0&&e.digest!==t)throw new J(K.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function bf(e){let t=Ft(Le({schemaVersion:Xe,entryIds:e.entryIds,cursor:e.cursor}));try{return await Ia(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await De(e.rootDir)}catch(n){let r=await De(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new J(K.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function Pb(e){await me.mkdir(e,{recursive:!0}),await me.mkdir(Uo(e),{recursive:!0}),await me.mkdir($o(e),{recursive:!0}),await me.mkdir(lr(e),{recursive:!0})}async function wb(e){await me.rm(lr(e),{recursive:!0,force:!0}),await me.mkdir(lr(e),{recursive:!0})}async function Ab(e){let t=lr(e);await me.mkdir(t,{recursive:!0});for(let n of await jo(t))n!=="stages"&&await me.rm(Ie.join(t,n),{recursive:!0,force:!0})}function Nb(e){if(!nt(e))throw new J(K.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==Xe)throw new J(K.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Af(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new J(K.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Te(o))throw new J(K.INDEX_CORRUPT,"index digest is invalid");let i=Ft(Le({schemaVersion:Xe,entryIds:t,cursor:r}));if(o!==i)throw new J(K.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:Xe,digest:o,entryIds:t,cursor:r}}function Tb(e){if(!nt(e))throw new J(K.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==Xe)throw new J(K.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Te(t))throw new J(K.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new J(K.ENTRY_CORRUPT,"entry kind is invalid");let r=xa(e.manifest,"entry.manifest"),o=Fb(e.blobs);return{id:t,schemaVersion:Xe,kind:n,manifest:r,blobs:o}}function Fb(e){if(!Array.isArray(e))throw new J(K.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!nt(t))throw new J(K.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new J(K.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Te(o))throw new J(K.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new J(K.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function cr(e,t){await wf(e,Le(t))}async function Mb(e,t){let n=Ie.dirname(e),r=Ie.basename(e),o=Ie.join(n,`.${r}.${process.pid}.${Sa()}.tmp`);await me.mkdir(n,{recursive:!0});try{await me.writeFile(o,Le(t),{flag:"wx"}),await me.rename(o,e)}finally{await Lo(o)}}async function wf(e,t){let n=Ie.dirname(e),r=Ie.basename(e),o=Ie.join(n,`.${r}.${process.pid}.${Sa()}.tmp`);await me.mkdir(n,{recursive:!0});try{let i=await me.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await me.rename(o,e),await Ea(n)}finally{await Lo(o)}}function Le(e){return Buffer.from(JSON.stringify(ya(e)),"utf8")}function ya(e){if(Array.isArray(e))return e.map(t=>ya(t));if(nt(e)){let t={};for(let n of Object.keys(e).sort())t[n]=ya(e[n]);return t}return e}function dr(e,t){try{return JSON.parse(e)}catch(n){throw new J(K.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function xa(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=>xa(n,t));if(nt(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=xa(o,t);return n}break}throw new J(K.INVALID_JSON,`${t} must be JSON-serializable`)}function Af(e,t){if(!Array.isArray(e))throw new J(K.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Te(n))throw new J(K.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function _o(e,t){if(!Te(e))throw new J(K.INVALID_PATH,`${t} must be a sha256 digest`)}function Te(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function Ft(e){return`sha256:${gb("sha256").update(e).digest("hex")}`}function Ob(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Tt(e,t,n){try{return await me.readFile(e)}catch(r){throw new J(t,`${n} not found: ${e}`,{cause:r})}}async function Nf(e){try{return await me.readFile(e)}catch(t){if(pr(t))return null;throw t}}function ka(e,t,n){if(Ft(e)!==t)throw new J(K.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Je(e){try{return await me.access(e),!0}catch(t){if(pr(t))return!1;throw t}}async function Lo(e){try{await me.rm(e,{force:!0,recursive:!0})}catch{}}async function Ea(e){try{let t=await me.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function jo(e){try{return await me.readdir(e)}catch(t){if(pr(t))return[];throw t}}function _b(e){if(typeof e!="string"||e.trim().length===0)throw new J(K.INVALID_ROOT,"history store rootDir must be a non-empty string");return Ie.resolve(e)}function Vo(e){return Ie.join(e,xb)}function ua(e){return Ie.join(e,Eb)}function Db(e){return Ie.join(e,Sb)}function Tf(e){return Ie.join(e,bb)}async function If(e){try{let t=await me.readFile(Tf(e),"utf8"),n=dr(t,"document version");if(!nt(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new J(K.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(pr(t))return 0;throw t}}async function Mo(e){let t=await Tt(e,K.RECOVERY_PENDING,"transaction journal"),n=dr(Buffer.from(t).toString("utf8"),"transaction journal");return Ff(n),n}function Ff(e){if(!nt(e)||e.schemaVersion!==yb||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!kb(e.historyTransition)||!Array.isArray(e.files))throw new J(K.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!nt(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Te(t.preDigest)||t.postDigest!==null&&!Te(t.postDigest))throw new J(K.INVALID_SCHEMA,"transaction journal file digest is invalid")}function Lb(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Uo(e){return Ie.join(e,"entries")}function $o(e){return Ie.join(e,"blobs")}function lr(e){return Ie.join(e,"tmp")}function va(e){return Ie.join(lr(e),"stages")}function Ca(e,t){return Ie.join(va(e),`${t}.json`)}function fr(e,t){return Ie.join(Uo(e),`${t}.json`)}function Cn(e,t){return Ie.join($o(e),t)}function nt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function jb(e){return{maxEntries:e?.maxEntries??Oo.maxEntries,maxSessionBytes:e?.maxSessionBytes??Oo.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Oo.maxEntryBytes}}async function Bb(e){let t=Vo(e);await Je(t)||await Ia(e,[],-1)}export{J as FileHistoryStoreError,Fo as PreviewFileSystemSiteEditEngineRuntime,Cd as SITE_EDIT_RAW_COLOR_LITERAL_RE,No as SnapshotSiteEditEngineRuntime,hb as createPreviewSiteEditEngineRuntime,db as createSiteEditEngineRuntime,kf as openFileHistoryStore,Js as scanSiteEditThemeStyleViolations};