@sap-ux/fiori-mcp-server 0.4.10 → 0.4.11

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 +2 -2
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1650,12 +1650,12 @@ ${n.message}`:h,_=[v,t,e].filter(Boolean).join(`
1650
1650
 
1651
1651
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let p=l[1];if(t===l[0]){o(l);continue}if(n.external){let d=n.external.registry.get(l[0])?.id;if(t!==l[0]&&d){o(l);continue}}if(this.metadataRegistry.get(l[0])?.id){o(l);continue}if(p.cycle){o(l);continue}if(p.count>1&&n.reused==="ref"){o(l);continue}}let s=(l,p)=>{let f=this.seen.get(l),d=f.def??f.schema,h={...d};if(f.ref===null)return;let m=f.ref;if(f.ref=null,m){s(m,p);let v=this.seen.get(m).schema;v.$ref&&(p.target==="draft-7"||p.target==="draft-4"||p.target==="openapi-3.0")?(d.allOf=d.allOf??[],d.allOf.push(v)):(Object.assign(d,v),Object.assign(d,h))}f.isParent||this.override({zodSchema:l,jsonSchema:d,path:f.path??[]})};for(let l of[...this.seen.entries()].reverse())s(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":this.target==="draft-4"?c.$schema="http://json-schema.org/draft-04/schema#":this.target==="openapi-3.0"||console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(t)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,i.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let p=l[1];p.def&&p.defId&&(u[p.defId]=p.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function GT(e,t){if(e instanceof cC){let n=new Bk(t),i={};for(let s of e._idmap.entries()){let[c,u]=s;n.process(u)}let a={},o={registry:e,uri:t?.uri,defs:i};for(let s of e._idmap.entries()){let[c,u]=s;a[c]=n.emit(u,{...t,external:o})}if(Object.keys(i).length>0){let s=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[s]:i}}return{schemas:a}}let r=new Bk(t);return r.process(e),r.emit(e,t)}function eu(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return eu(n.element,r);if(n.type==="set")return eu(n.valueType,r);if(n.type==="lazy")return eu(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return eu(n.innerType,r);if(n.type==="intersection")return eu(n.left,r)||eu(n.right,r);if(n.type==="record"||n.type==="map")return eu(n.keyType,r)||eu(n.valueType,r);if(n.type==="pipe")return eu(n.in,r)||eu(n.out,r);if(n.type==="object"){for(let i in n.shape)if(eu(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(eu(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(eu(i,r))return!0;return!!(n.rest&&eu(n.rest,r))}return!1}var BKe={};function xC(e){return!!e._zod}function m0(e,t){return xC(e)?VT(e,t):e.safeParse(t)}function C5(e){var t,r;if(!e)return;let n;if(xC(e)?n=(r=(t=e._zod)===null||t===void 0?void 0:t.def)===null||r===void 0?void 0:r.shape:n=e.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function GKe(e){var t;if(xC(e)){let o=(t=e._zod)===null||t===void 0?void 0:t.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let n=e._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let i=e.value;if(i!==void 0)return i}var KT={};Ri(KT,{$brand:()=>ik,$input:()=>M6,$output:()=>$6,NEVER:()=>o8,TimePrecision:()=>q6,ZodAny:()=>QKe,ZodArray:()=>nYe,ZodBase64:()=>qpe,ZodBase64URL:()=>Upe,ZodBigInt:()=>Wk,ZodBigIntFormat:()=>Hpe,ZodBoolean:()=>Yk,ZodCIDRv4:()=>jpe,ZodCIDRv6:()=>Vpe,ZodCUID:()=>Ipe,ZodCUID2:()=>Rpe,ZodCatch:()=>EYe,ZodCodec:()=>Qpe,ZodCustom:()=>q5,ZodCustomStringFormat:()=>Gk,ZodDate:()=>F5,ZodDefault:()=>hYe,ZodDiscriminatedUnion:()=>iYe,ZodE164:()=>Bpe,ZodEmail:()=>wpe,ZodEmoji:()=>Dpe,ZodEnum:()=>zk,ZodError:()=>dpe,ZodFile:()=>pYe,ZodFirstPartyTypeKind:()=>tfe,ZodFunction:()=>PYe,ZodGUID:()=>R5,ZodIPv4:()=>Mpe,ZodIPv6:()=>Fpe,ZodISODate:()=>P5,ZodISODateTime:()=>w5,ZodISODuration:()=>N5,ZodISOTime:()=>D5,ZodIntersection:()=>aYe,ZodIssueCode:()=>uDr,ZodJWT:()=>zpe,ZodKSUID:()=>$pe,ZodLazy:()=>AYe,ZodLiteral:()=>lYe,ZodMAC:()=>WKe,ZodMap:()=>cYe,ZodNaN:()=>TYe,ZodNanoID:()=>Npe,ZodNever:()=>tYe,ZodNonOptional:()=>Jpe,ZodNull:()=>ZKe,ZodNullable:()=>dYe,ZodNumber:()=>Kk,ZodNumberFormat:()=>OC,ZodObject:()=>j5,ZodOptional:()=>Xpe,ZodPipe:()=>Zpe,ZodPrefault:()=>gYe,ZodPromise:()=>wYe,ZodReadonly:()=>xYe,ZodRealError:()=>zu,ZodRecord:()=>Ype,ZodSet:()=>uYe,ZodString:()=>Hk,ZodStringFormat:()=>pi,ZodSuccess:()=>bYe,ZodSymbol:()=>XKe,ZodTemplateLiteral:()=>SYe,ZodTransform:()=>fYe,ZodTuple:()=>oYe,ZodType:()=>wr,ZodULID:()=>Lpe,ZodURL:()=>$5,ZodUUID:()=>xy,ZodUndefined:()=>JKe,ZodUnion:()=>Kpe,ZodUnknown:()=>eYe,ZodVoid:()=>rYe,ZodXID:()=>kpe,_ZodString:()=>Cpe,_default:()=>mYe,_function:()=>rDr,any:()=>M5,array:()=>zt,base64:()=>OPr,base64url:()=>SPr,bigint:()=>$Pr,boolean:()=>Qi,catch:()=>_Ye,check:()=>nDr,cidrv4:()=>TPr,cidrv6:()=>xPr,clone:()=>Ss,codec:()=>QPr,coerce:()=>rfe,config:()=>va,core:()=>ap,cuid:()=>hPr,cuid2:()=>mPr,custom:()=>efe,date:()=>UPr,decode:()=>bpe,decodeAsync:()=>_pe,describe:()=>iDr,discriminatedUnion:()=>V5,e164:()=>APr,email:()=>aPr,emoji:()=>fPr,encode:()=>vpe,encodeAsync:()=>Epe,endsWith:()=>yC,enum:()=>Fn,file:()=>WPr,flattenError:()=>WA,float32:()=>IPr,float64:()=>RPr,formatError:()=>XA,function:()=>rDr,getErrorMap:()=>pDr,globalRegistry:()=>nc,gt:()=>Jh,gte:()=>ic,guid:()=>oPr,hash:()=>NPr,hex:()=>DPr,hostname:()=>PPr,httpUrl:()=>pPr,includes:()=>mC,instanceof:()=>oDr,int:()=>Ape,int32:()=>LPr,int64:()=>MPr,intersection:()=>Jk,ipv4:()=>bPr,ipv6:()=>_Pr,iso:()=>I5,json:()=>cDr,jwt:()=>CPr,keyof:()=>BPr,ksuid:()=>vPr,lazy:()=>CYe,length:()=>zT,literal:()=>ht,locales:()=>sC,looseObject:()=>op,lowercase:()=>dC,lt:()=>Xh,lte:()=>Bu,mac:()=>EPr,map:()=>GPr,maxLength:()=>BT,maxSize:()=>UT,meta:()=>aDr,mime:()=>vC,minLength:()=>Ty,minSize:()=>h0,multipleOf:()=>d0,nan:()=>ZPr,nanoid:()=>dPr,nativeEnum:()=>YPr,negative:()=>g5,never:()=>Gpe,nonnegative:()=>v5,nonoptional:()=>vYe,nonpositive:()=>y5,normalize:()=>bC,null:()=>Xk,nullable:()=>L5,nullish:()=>XPr,number:()=>Mn,object:()=>Ae,optional:()=>pt,overwrite:()=>kd,parse:()=>hpe,parseAsync:()=>mpe,partialRecord:()=>HPr,pipe:()=>k5,positive:()=>m5,prefault:()=>yYe,preprocess:()=>U5,prettifyError:()=>l8,promise:()=>tDr,property:()=>b5,readonly:()=>OYe,record:()=>Ei,refine:()=>DYe,regex:()=>fC,regexes:()=>Uu,registry:()=>_k,safeDecode:()=>xpe,safeDecodeAsync:()=>Spe,safeEncode:()=>Tpe,safeEncodeAsync:()=>Ope,safeParse:()=>gpe,safeParseAsync:()=>ype,set:()=>KPr,setErrorMap:()=>lDr,size:()=>pC,slugify:()=>Uk,startsWith:()=>gC,strictObject:()=>zPr,string:()=>re,stringFormat:()=>wPr,stringbool:()=>sDr,success:()=>JPr,superRefine:()=>NYe,symbol:()=>jPr,templateLiteral:()=>eDr,toJSONSchema:()=>GT,toLowerCase:()=>_C,toUpperCase:()=>TC,transform:()=>Wpe,treeifyError:()=>u8,trim:()=>EC,tuple:()=>sYe,uint32:()=>kPr,uint64:()=>FPr,ulid:()=>gPr,undefined:()=>VPr,union:()=>hn,unknown:()=>fi,uppercase:()=>hC,url:()=>Ppe,util:()=>Le,uuid:()=>sPr,uuidv4:()=>cPr,uuidv6:()=>uPr,uuidv7:()=>lPr,void:()=>qPr,xid:()=>yPr});var I5={};Ri(I5,{ZodISODate:()=>P5,ZodISODateTime:()=>w5,ZodISODuration:()=>N5,ZodISOTime:()=>D5,date:()=>lpe,datetime:()=>upe,duration:()=>fpe,time:()=>ppe});var w5=ne("ZodISODateTime",(e,t)=>{F8.init(e,t),pi.init(e,t)});function upe(e){return U6(w5,e)}var P5=ne("ZodISODate",(e,t)=>{j8.init(e,t),pi.init(e,t)});function lpe(e){return B6(P5,e)}var D5=ne("ZodISOTime",(e,t)=>{V8.init(e,t),pi.init(e,t)});function ppe(e){return z6(D5,e)}var N5=ne("ZodISODuration",(e,t)=>{q8.init(e,t),pi.init(e,t)});function fpe(e){return H6(N5,e)}var YKe=(e,t)=>{pk.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>XA(e,r)},flatten:{value:r=>WA(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,GA,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,GA,2)}},isEmpty:{get(){return e.issues.length===0}}})},dpe=ne("ZodError",YKe),zu=ne("ZodError",YKe,{Parent:Error});var hpe=JA(zu),mpe=QA(zu),gpe=tC(zu),ype=rC(zu),vpe=p8(zu),bpe=f8(zu),Epe=d8(zu),_pe=h8(zu),Tpe=m8(zu),xpe=g8(zu),Ope=y8(zu),Spe=v8(zu);var wr=ne("ZodType",(e,t)=>(Jt.init(e,t),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(Le.mergeDefs(t,{checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]})),e.clone=(r,n)=>Ss(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>hpe(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>gpe(e,r,n),e.parseAsync=async(r,n)=>mpe(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>ype(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>vpe(e,r,n),e.decode=(r,n)=>bpe(e,r,n),e.encodeAsync=async(r,n)=>Epe(e,r,n),e.decodeAsync=async(r,n)=>_pe(e,r,n),e.safeEncode=(r,n)=>Tpe(e,r,n),e.safeDecode=(r,n)=>xpe(e,r,n),e.safeEncodeAsync=async(r,n)=>Ope(e,r,n),e.safeDecodeAsync=async(r,n)=>Spe(e,r,n),e.refine=(r,n)=>e.check(DYe(r,n)),e.superRefine=r=>e.check(NYe(r)),e.overwrite=r=>e.check(kd(r)),e.optional=()=>pt(e),e.nullable=()=>L5(e),e.nullish=()=>pt(L5(e)),e.nonoptional=r=>vYe(e,r),e.array=()=>zt(e),e.or=r=>hn([e,r]),e.and=r=>Jk(e,r),e.transform=r=>k5(e,Wpe(r)),e.default=r=>mYe(e,r),e.prefault=r=>yYe(e,r),e.catch=r=>_Ye(e,r),e.pipe=r=>k5(e,r),e.readonly=()=>OYe(e),e.describe=r=>{let n=e.clone();return nc.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return nc.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return nc.get(e);let n=e.clone();return nc.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Cpe=ne("_ZodString",(e,t)=>{f0.init(e,t),wr.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(fC(...n)),e.includes=(...n)=>e.check(mC(...n)),e.startsWith=(...n)=>e.check(gC(...n)),e.endsWith=(...n)=>e.check(yC(...n)),e.min=(...n)=>e.check(Ty(...n)),e.max=(...n)=>e.check(BT(...n)),e.length=(...n)=>e.check(zT(...n)),e.nonempty=(...n)=>e.check(Ty(1,...n)),e.lowercase=n=>e.check(dC(n)),e.uppercase=n=>e.check(hC(n)),e.trim=()=>e.check(EC()),e.normalize=(...n)=>e.check(bC(...n)),e.toLowerCase=()=>e.check(_C()),e.toUpperCase=()=>e.check(TC()),e.slugify=()=>e.check(Uk())}),Hk=ne("ZodString",(e,t)=>{f0.init(e,t),Cpe.init(e,t),e.email=r=>e.check(Tk(wpe,r)),e.url=r=>e.check(lC($5,r)),e.jwt=r=>e.check(qk(zpe,r)),e.emoji=r=>e.check(Ck(Dpe,r)),e.guid=r=>e.check(uC(R5,r)),e.uuid=r=>e.check(xk(xy,r)),e.uuidv4=r=>e.check(Ok(xy,r)),e.uuidv6=r=>e.check(Sk(xy,r)),e.uuidv7=r=>e.check(Ak(xy,r)),e.nanoid=r=>e.check(wk(Npe,r)),e.guid=r=>e.check(uC(R5,r)),e.cuid=r=>e.check(Pk(Ipe,r)),e.cuid2=r=>e.check(Dk(Rpe,r)),e.ulid=r=>e.check(Nk(Lpe,r)),e.base64=r=>e.check(Fk(qpe,r)),e.base64url=r=>e.check(jk(Upe,r)),e.xid=r=>e.check(Ik(kpe,r)),e.ksuid=r=>e.check(Rk($pe,r)),e.ipv4=r=>e.check(Lk(Mpe,r)),e.ipv6=r=>e.check(kk(Fpe,r)),e.cidrv4=r=>e.check($k(jpe,r)),e.cidrv6=r=>e.check(Mk(Vpe,r)),e.e164=r=>e.check(Vk(Bpe,r)),e.datetime=r=>e.check(upe(r)),e.date=r=>e.check(lpe(r)),e.time=r=>e.check(ppe(r)),e.duration=r=>e.check(fpe(r))});function re(e){return F6(Hk,e)}var pi=ne("ZodStringFormat",(e,t)=>{Wn.init(e,t),Cpe.init(e,t)}),wpe=ne("ZodEmail",(e,t)=>{P8.init(e,t),pi.init(e,t)});function aPr(e){return Tk(wpe,e)}var R5=ne("ZodGUID",(e,t)=>{C8.init(e,t),pi.init(e,t)});function oPr(e){return uC(R5,e)}var xy=ne("ZodUUID",(e,t)=>{w8.init(e,t),pi.init(e,t)});function sPr(e){return xk(xy,e)}function cPr(e){return Ok(xy,e)}function uPr(e){return Sk(xy,e)}function lPr(e){return Ak(xy,e)}var $5=ne("ZodURL",(e,t)=>{D8.init(e,t),pi.init(e,t)});function Ppe(e){return lC($5,e)}function pPr(e){return lC($5,{protocol:/^https?$/,hostname:Uu.domain,...Le.normalizeParams(e)})}var Dpe=ne("ZodEmoji",(e,t)=>{N8.init(e,t),pi.init(e,t)});function fPr(e){return Ck(Dpe,e)}var Npe=ne("ZodNanoID",(e,t)=>{I8.init(e,t),pi.init(e,t)});function dPr(e){return wk(Npe,e)}var Ipe=ne("ZodCUID",(e,t)=>{R8.init(e,t),pi.init(e,t)});function hPr(e){return Pk(Ipe,e)}var Rpe=ne("ZodCUID2",(e,t)=>{L8.init(e,t),pi.init(e,t)});function mPr(e){return Dk(Rpe,e)}var Lpe=ne("ZodULID",(e,t)=>{k8.init(e,t),pi.init(e,t)});function gPr(e){return Nk(Lpe,e)}var kpe=ne("ZodXID",(e,t)=>{$8.init(e,t),pi.init(e,t)});function yPr(e){return Ik(kpe,e)}var $pe=ne("ZodKSUID",(e,t)=>{M8.init(e,t),pi.init(e,t)});function vPr(e){return Rk($pe,e)}var Mpe=ne("ZodIPv4",(e,t)=>{U8.init(e,t),pi.init(e,t)});function bPr(e){return Lk(Mpe,e)}var WKe=ne("ZodMAC",(e,t)=>{z8.init(e,t),pi.init(e,t)});function EPr(e){return V6(WKe,e)}var Fpe=ne("ZodIPv6",(e,t)=>{B8.init(e,t),pi.init(e,t)});function _Pr(e){return kk(Fpe,e)}var jpe=ne("ZodCIDRv4",(e,t)=>{H8.init(e,t),pi.init(e,t)});function TPr(e){return $k(jpe,e)}var Vpe=ne("ZodCIDRv6",(e,t)=>{G8.init(e,t),pi.init(e,t)});function xPr(e){return Mk(Vpe,e)}var qpe=ne("ZodBase64",(e,t)=>{K8.init(e,t),pi.init(e,t)});function OPr(e){return Fk(qpe,e)}var Upe=ne("ZodBase64URL",(e,t)=>{Y8.init(e,t),pi.init(e,t)});function SPr(e){return jk(Upe,e)}var Bpe=ne("ZodE164",(e,t)=>{W8.init(e,t),pi.init(e,t)});function APr(e){return Vk(Bpe,e)}var zpe=ne("ZodJWT",(e,t)=>{X8.init(e,t),pi.init(e,t)});function CPr(e){return qk(zpe,e)}var Gk=ne("ZodCustomStringFormat",(e,t)=>{J8.init(e,t),pi.init(e,t)});function wPr(e,t,r={}){return HT(Gk,e,t,r)}function PPr(e){return HT(Gk,"hostname",Uu.hostname,e)}function DPr(e){return HT(Gk,"hex",Uu.hex,e)}function NPr(e,t){let r=t?.enc??"hex",n=`${e}_${r}`,i=Uu[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return HT(Gk,n,i,t)}var Kk=ne("ZodNumber",(e,t)=>{mk.init(e,t),wr.init(e,t),e.gt=(n,i)=>e.check(Jh(n,i)),e.gte=(n,i)=>e.check(ic(n,i)),e.min=(n,i)=>e.check(ic(n,i)),e.lt=(n,i)=>e.check(Xh(n,i)),e.lte=(n,i)=>e.check(Bu(n,i)),e.max=(n,i)=>e.check(Bu(n,i)),e.int=n=>e.check(Ape(n)),e.safe=n=>e.check(Ape(n)),e.positive=n=>e.check(Jh(0,n)),e.nonnegative=n=>e.check(ic(0,n)),e.negative=n=>e.check(Xh(0,n)),e.nonpositive=n=>e.check(Bu(0,n)),e.multipleOf=(n,i)=>e.check(d0(n,i)),e.step=(n,i)=>e.check(d0(n,i)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function Mn(e){return G6(Kk,e)}var OC=ne("ZodNumberFormat",(e,t)=>{Z8.init(e,t),Kk.init(e,t)});function Ape(e){return Y6(OC,e)}function IPr(e){return W6(OC,e)}function RPr(e){return X6(OC,e)}function LPr(e){return J6(OC,e)}function kPr(e){return Z6(OC,e)}var Yk=ne("ZodBoolean",(e,t)=>{aC.init(e,t),wr.init(e,t)});function Qi(e){return Q6(Yk,e)}var Wk=ne("ZodBigInt",(e,t)=>{gk.init(e,t),wr.init(e,t),e.gte=(n,i)=>e.check(ic(n,i)),e.min=(n,i)=>e.check(ic(n,i)),e.gt=(n,i)=>e.check(Jh(n,i)),e.gte=(n,i)=>e.check(ic(n,i)),e.min=(n,i)=>e.check(ic(n,i)),e.lt=(n,i)=>e.check(Xh(n,i)),e.lte=(n,i)=>e.check(Bu(n,i)),e.max=(n,i)=>e.check(Bu(n,i)),e.positive=n=>e.check(Jh(BigInt(0),n)),e.negative=n=>e.check(Xh(BigInt(0),n)),e.nonpositive=n=>e.check(Bu(BigInt(0),n)),e.nonnegative=n=>e.check(ic(BigInt(0),n)),e.multipleOf=(n,i)=>e.check(d0(n,i));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function $Pr(e){return t5(Wk,e)}var Hpe=ne("ZodBigIntFormat",(e,t)=>{Q8.init(e,t),Wk.init(e,t)});function MPr(e){return n5(Hpe,e)}function FPr(e){return i5(Hpe,e)}var XKe=ne("ZodSymbol",(e,t)=>{e6.init(e,t),wr.init(e,t)});function jPr(e){return a5(XKe,e)}var JKe=ne("ZodUndefined",(e,t)=>{t6.init(e,t),wr.init(e,t)});function VPr(e){return o5(JKe,e)}var ZKe=ne("ZodNull",(e,t)=>{r6.init(e,t),wr.init(e,t)});function Xk(e){return s5(ZKe,e)}var QKe=ne("ZodAny",(e,t)=>{n6.init(e,t),wr.init(e,t)});function M5(){return c5(QKe)}var eYe=ne("ZodUnknown",(e,t)=>{i6.init(e,t),wr.init(e,t)});function fi(){return u5(eYe)}var tYe=ne("ZodNever",(e,t)=>{a6.init(e,t),wr.init(e,t)});function Gpe(e){return l5(tYe,e)}var rYe=ne("ZodVoid",(e,t)=>{o6.init(e,t),wr.init(e,t)});function qPr(e){return p5(rYe,e)}var F5=ne("ZodDate",(e,t)=>{s6.init(e,t),wr.init(e,t),e.min=(n,i)=>e.check(ic(n,i)),e.max=(n,i)=>e.check(Bu(n,i));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});function UPr(e){return f5(F5,e)}var nYe=ne("ZodArray",(e,t)=>{c6.init(e,t),wr.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Ty(r,n)),e.nonempty=r=>e.check(Ty(1,r)),e.max=(r,n)=>e.check(BT(r,n)),e.length=(r,n)=>e.check(zT(r,n)),e.unwrap=()=>e.element});function zt(e,t){return cpe(nYe,e,t)}function BPr(e){let t=e._zod.def.shape;return Fn(Object.keys(t))}var j5=ne("ZodObject",(e,t)=>{spe.init(e,t),wr.init(e,t),Le.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Fn(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:fi()}),e.loose=()=>e.clone({...e._zod.def,catchall:fi()}),e.strict=()=>e.clone({...e._zod.def,catchall:Gpe()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>Le.extend(e,r),e.safeExtend=r=>Le.safeExtend(e,r),e.merge=r=>Le.merge(e,r),e.pick=r=>Le.pick(e,r),e.omit=r=>Le.omit(e,r),e.partial=(...r)=>Le.partial(Xpe,e,r[0]),e.required=(...r)=>Le.required(Jpe,e,r[0])});function Ae(e,t){let r={type:"object",shape:e??{},...Le.normalizeParams(t)};return new j5(r)}function zPr(e,t){return new j5({type:"object",shape:e,catchall:Gpe(),...Le.normalizeParams(t)})}function op(e,t){return new j5({type:"object",shape:e,catchall:fi(),...Le.normalizeParams(t)})}var Kpe=ne("ZodUnion",(e,t)=>{yk.init(e,t),wr.init(e,t),e.options=t.options});function hn(e,t){return new Kpe({type:"union",options:e,...Le.normalizeParams(t)})}var iYe=ne("ZodDiscriminatedUnion",(e,t)=>{Kpe.init(e,t),u6.init(e,t)});function V5(e,t,r){return new iYe({type:"union",options:t,discriminator:e,...Le.normalizeParams(r)})}var aYe=ne("ZodIntersection",(e,t)=>{l6.init(e,t),wr.init(e,t)});function Jk(e,t){return new aYe({type:"intersection",left:e,right:t})}var oYe=ne("ZodTuple",(e,t)=>{vk.init(e,t),wr.init(e,t),e.rest=r=>e.clone({...e._zod.def,rest:r})});function sYe(e,t,r){let n=t instanceof Jt,i=n?r:t,a=n?t:null;return new oYe({type:"tuple",items:e,rest:a,...Le.normalizeParams(i)})}var Ype=ne("ZodRecord",(e,t)=>{p6.init(e,t),wr.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function Ei(e,t,r){return new Ype({type:"record",keyType:e,valueType:t,...Le.normalizeParams(r)})}function HPr(e,t,r){let n=Ss(e);return n._zod.values=void 0,new Ype({type:"record",keyType:n,valueType:t,...Le.normalizeParams(r)})}var cYe=ne("ZodMap",(e,t)=>{f6.init(e,t),wr.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function GPr(e,t,r){return new cYe({type:"map",keyType:e,valueType:t,...Le.normalizeParams(r)})}var uYe=ne("ZodSet",(e,t)=>{d6.init(e,t),wr.init(e,t),e.min=(...r)=>e.check(h0(...r)),e.nonempty=r=>e.check(h0(1,r)),e.max=(...r)=>e.check(UT(...r)),e.size=(...r)=>e.check(pC(...r))});function KPr(e,t){return new uYe({type:"set",valueType:e,...Le.normalizeParams(t)})}var zk=ne("ZodEnum",(e,t)=>{h6.init(e,t),wr.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,i)=>{let a={};for(let o of n)if(r.has(o))a[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new zk({...t,checks:[],...Le.normalizeParams(i),entries:a})},e.exclude=(n,i)=>{let a={...t.entries};for(let o of n)if(r.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new zk({...t,checks:[],...Le.normalizeParams(i),entries:a})}});function Fn(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new zk({type:"enum",entries:r,...Le.normalizeParams(t)})}function YPr(e,t){return new zk({type:"enum",entries:e,...Le.normalizeParams(t)})}var lYe=ne("ZodLiteral",(e,t)=>{m6.init(e,t),wr.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function ht(e,t){return new lYe({type:"literal",values:Array.isArray(e)?e:[e],...Le.normalizeParams(t)})}var pYe=ne("ZodFile",(e,t)=>{g6.init(e,t),wr.init(e,t),e.min=(r,n)=>e.check(h0(r,n)),e.max=(r,n)=>e.check(UT(r,n)),e.mime=(r,n)=>e.check(vC(Array.isArray(r)?r:[r],n))});function WPr(e){return E5(pYe,e)}var fYe=ne("ZodTransform",(e,t)=>{y6.init(e,t),wr.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new o0(e.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(Le.issue(a,r.value,t));else{let o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),r.issues.push(Le.issue(o))}};let i=t.transform(r.value,r);return i instanceof Promise?i.then(a=>(r.value=a,r)):(r.value=i,r)}});function Wpe(e){return new fYe({type:"transform",transform:e})}var Xpe=ne("ZodOptional",(e,t)=>{v6.init(e,t),wr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function pt(e){return new Xpe({type:"optional",innerType:e})}var dYe=ne("ZodNullable",(e,t)=>{b6.init(e,t),wr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function L5(e){return new dYe({type:"nullable",innerType:e})}function XPr(e){return pt(L5(e))}var hYe=ne("ZodDefault",(e,t)=>{E6.init(e,t),wr.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function mYe(e,t){return new hYe({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Le.shallowClone(t)}})}var gYe=ne("ZodPrefault",(e,t)=>{_6.init(e,t),wr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function yYe(e,t){return new gYe({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Le.shallowClone(t)}})}var Jpe=ne("ZodNonOptional",(e,t)=>{T6.init(e,t),wr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function vYe(e,t){return new Jpe({type:"nonoptional",innerType:e,...Le.normalizeParams(t)})}var bYe=ne("ZodSuccess",(e,t)=>{x6.init(e,t),wr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function JPr(e){return new bYe({type:"success",innerType:e})}var EYe=ne("ZodCatch",(e,t)=>{O6.init(e,t),wr.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _Ye(e,t){return new EYe({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var TYe=ne("ZodNaN",(e,t)=>{S6.init(e,t),wr.init(e,t)});function ZPr(e){return h5(TYe,e)}var Zpe=ne("ZodPipe",(e,t)=>{A6.init(e,t),wr.init(e,t),e.in=t.in,e.out=t.out});function k5(e,t){return new Zpe({type:"pipe",in:e,out:t})}var Qpe=ne("ZodCodec",(e,t)=>{Zpe.init(e,t),oC.init(e,t)});function QPr(e,t,r){return new Qpe({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}var xYe=ne("ZodReadonly",(e,t)=>{C6.init(e,t),wr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function OYe(e){return new xYe({type:"readonly",innerType:e})}var SYe=ne("ZodTemplateLiteral",(e,t)=>{w6.init(e,t),wr.init(e,t)});function eDr(e,t){return new SYe({type:"template_literal",parts:e,...Le.normalizeParams(t)})}var AYe=ne("ZodLazy",(e,t)=>{N6.init(e,t),wr.init(e,t),e.unwrap=()=>e._zod.def.getter()});function CYe(e){return new AYe({type:"lazy",getter:e})}var wYe=ne("ZodPromise",(e,t)=>{D6.init(e,t),wr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function tDr(e){return new wYe({type:"promise",innerType:e})}var PYe=ne("ZodFunction",(e,t)=>{P6.init(e,t),wr.init(e,t)});function rDr(e){return new PYe({type:"function",input:Array.isArray(e?.input)?sYe(e?.input):e?.input??zt(fi()),output:e?.output??fi()})}var q5=ne("ZodCustom",(e,t)=>{I6.init(e,t),wr.init(e,t)});function nDr(e){let t=new ii({check:"custom"});return t._zod.check=e,t}function efe(e,t){return _5(q5,e??(()=>!0),t)}function DYe(e,t={}){return T5(q5,e,t)}function NYe(e){return x5(e)}var iDr=O5,aDr=S5;function oDr(e,t={error:`Input not instance of ${e.name}`}){let r=new q5({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...Le.normalizeParams(t)});return r._zod.bag.Class=e,r}var sDr=(...e)=>A5({Codec:Qpe,Boolean:Yk,String:Hk},...e);function cDr(e){let t=CYe(()=>hn([re(e),Mn(),Qi(),Xk(),zt(t),Ei(re(),t)]));return t}function U5(e,t){return k5(Wpe(e),t)}var uDr={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function lDr(e){va({customError:e})}function pDr(){return va().customError}var tfe;tfe||(tfe={});var rfe={};Ri(rfe,{bigint:()=>mDr,boolean:()=>hDr,date:()=>gDr,number:()=>dDr,string:()=>fDr});function fDr(e){return j6(Hk,e)}function dDr(e){return K6(Kk,e)}function hDr(e){return e5(Yk,e)}function mDr(e){return r5(Wk,e)}function gDr(e){return d5(F5,e)}va(R6());var ife="2025-11-25";var IYe=[ife,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Qh="io.modelcontextprotocol/related-task",z5="2.0",Zh=efe(e=>e!==null&&(typeof e=="object"||typeof e=="function")),RYe=hn([re(),Mn().int()]),LYe=re(),vDr=op({ttl:hn([Mn(),Xk()]).optional(),pollInterval:Mn().optional()}),afe=op({taskId:re()}),bDr=op({progressToken:RYe.optional(),[Qh]:afe.optional()}),Hu=op({task:vDr.optional(),_meta:bDr.optional()}),As=Ae({method:re(),params:Hu.optional()}),YT=op({_meta:Ae({[Qh]:pt(afe)}).passthrough().optional()}),cf=Ae({method:re(),params:YT.optional()}),ac=op({_meta:op({[Qh]:afe.optional()}).optional()}),H5=hn([re(),Mn().int()]),kYe=Ae({jsonrpc:ht(z5),id:H5,...As.shape}).strict(),ofe=e=>kYe.safeParse(e).success,$Ye=Ae({jsonrpc:ht(z5),...cf.shape}).strict(),MYe=e=>$Ye.safeParse(e).success,FYe=Ae({jsonrpc:ht(z5),id:H5,result:ac}).strict(),Zk=e=>FYe.safeParse(e).success,sn;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(sn||(sn={}));var jYe=Ae({jsonrpc:ht(z5),id:H5,error:Ae({code:Mn().int(),message:re(),data:pt(fi())})}).strict(),VYe=e=>jYe.safeParse(e).success,qYe=hn([kYe,$Ye,FYe,jYe]),G5=ac.strict(),EDr=YT.extend({requestId:H5,reason:re().optional()}),K5=cf.extend({method:ht("notifications/cancelled"),params:EDr}),_Dr=Ae({src:re(),mimeType:re().optional(),sizes:zt(re()).optional()}),Qk=Ae({icons:zt(_Dr).optional()}),SC=Ae({name:re(),title:re().optional()}),UYe=SC.extend({...SC.shape,...Qk.shape,version:re(),websiteUrl:re().optional()}),TDr=Jk(Ae({applyDefaults:Qi().optional()}),Ei(re(),fi())),xDr=U5(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Jk(Ae({form:TDr.optional(),url:Zh.optional()}),Ei(re(),fi()).optional())),ODr=Ae({list:pt(Ae({}).passthrough()),cancel:pt(Ae({}).passthrough()),requests:pt(Ae({sampling:pt(Ae({createMessage:pt(Ae({}).passthrough())}).passthrough()),elicitation:pt(Ae({create:pt(Ae({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),SDr=Ae({list:pt(Ae({}).passthrough()),cancel:pt(Ae({}).passthrough()),requests:pt(Ae({tools:pt(Ae({call:pt(Ae({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),ADr=Ae({experimental:Ei(re(),Zh).optional(),sampling:Ae({context:Zh.optional(),tools:Zh.optional()}).optional(),elicitation:xDr.optional(),roots:Ae({listChanged:Qi().optional()}).optional(),tasks:pt(ODr)}),CDr=Hu.extend({protocolVersion:re(),capabilities:ADr,clientInfo:UYe}),sfe=As.extend({method:ht("initialize"),params:CDr});var wDr=Ae({experimental:Ei(re(),Zh).optional(),logging:Zh.optional(),completions:Zh.optional(),prompts:pt(Ae({listChanged:pt(Qi())})),resources:Ae({subscribe:Qi().optional(),listChanged:Qi().optional()}).optional(),tools:Ae({listChanged:Qi().optional()}).optional(),tasks:pt(SDr)}).passthrough(),PDr=ac.extend({protocolVersion:re(),capabilities:wDr,serverInfo:UYe,instructions:re().optional()}),cfe=cf.extend({method:ht("notifications/initialized")});var Y5=As.extend({method:ht("ping")}),DDr=Ae({progress:Mn(),total:pt(Mn()),message:pt(re())}),NDr=Ae({...YT.shape,...DDr.shape,progressToken:RYe}),W5=cf.extend({method:ht("notifications/progress"),params:NDr}),IDr=Hu.extend({cursor:LYe.optional()}),e2=As.extend({params:IDr.optional()}),t2=ac.extend({nextCursor:pt(LYe)}),r2=Ae({taskId:re(),status:Fn(["working","input_required","completed","failed","cancelled"]),ttl:hn([Mn(),Xk()]),createdAt:re(),lastUpdatedAt:re(),pollInterval:pt(Mn()),statusMessage:pt(re())}),AC=ac.extend({task:r2}),RDr=YT.merge(r2),n2=cf.extend({method:ht("notifications/tasks/status"),params:RDr}),X5=As.extend({method:ht("tasks/get"),params:Hu.extend({taskId:re()})}),J5=ac.merge(r2),Z5=As.extend({method:ht("tasks/result"),params:Hu.extend({taskId:re()})}),Q5=e2.extend({method:ht("tasks/list")}),ez=t2.extend({tasks:zt(r2)}),BYe=As.extend({method:ht("tasks/cancel"),params:Hu.extend({taskId:re()})}),zYe=ac.merge(r2),HYe=Ae({uri:re(),mimeType:pt(re()),_meta:Ei(re(),fi()).optional()}),GYe=HYe.extend({text:re()}),ufe=re().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),KYe=HYe.extend({blob:ufe}),YYe=Ae({...SC.shape,...Qk.shape,uri:re(),description:pt(re()),mimeType:pt(re()),_meta:pt(op({}))}),LDr=Ae({...SC.shape,...Qk.shape,uriTemplate:re(),description:pt(re()),mimeType:pt(re()),_meta:pt(op({}))}),kDr=e2.extend({method:ht("resources/list")}),$Dr=t2.extend({resources:zt(YYe)}),MDr=e2.extend({method:ht("resources/templates/list")}),FDr=t2.extend({resourceTemplates:zt(LDr)}),lfe=Hu.extend({uri:re()}),jDr=lfe,VDr=As.extend({method:ht("resources/read"),params:jDr}),qDr=ac.extend({contents:zt(hn([GYe,KYe]))}),UDr=cf.extend({method:ht("notifications/resources/list_changed")}),BDr=lfe,zDr=As.extend({method:ht("resources/subscribe"),params:BDr}),HDr=lfe,GDr=As.extend({method:ht("resources/unsubscribe"),params:HDr}),KDr=YT.extend({uri:re()}),YDr=cf.extend({method:ht("notifications/resources/updated"),params:KDr}),WDr=Ae({name:re(),description:pt(re()),required:pt(Qi())}),XDr=Ae({...SC.shape,...Qk.shape,description:pt(re()),arguments:pt(zt(WDr)),_meta:pt(op({}))}),JDr=e2.extend({method:ht("prompts/list")}),ZDr=t2.extend({prompts:zt(XDr)}),QDr=Hu.extend({name:re(),arguments:Ei(re(),re()).optional()}),eNr=As.extend({method:ht("prompts/get"),params:QDr}),pfe=Ae({type:ht("text"),text:re(),_meta:Ei(re(),fi()).optional()}),ffe=Ae({type:ht("image"),data:ufe,mimeType:re(),_meta:Ei(re(),fi()).optional()}),dfe=Ae({type:ht("audio"),data:ufe,mimeType:re(),_meta:Ei(re(),fi()).optional()}),tNr=Ae({type:ht("tool_use"),name:re(),id:re(),input:Ae({}).passthrough(),_meta:pt(Ae({}).passthrough())}).passthrough(),rNr=Ae({type:ht("resource"),resource:hn([GYe,KYe]),_meta:Ei(re(),fi()).optional()}),nNr=YYe.extend({type:ht("resource_link")}),hfe=hn([pfe,ffe,dfe,nNr,rNr]),iNr=Ae({role:Fn(["user","assistant"]),content:hfe}),aNr=ac.extend({description:pt(re()),messages:zt(iNr)}),oNr=cf.extend({method:ht("notifications/prompts/list_changed")}),sNr=Ae({title:re().optional(),readOnlyHint:Qi().optional(),destructiveHint:Qi().optional(),idempotentHint:Qi().optional(),openWorldHint:Qi().optional()}),cNr=Ae({taskSupport:Fn(["required","optional","forbidden"]).optional()}),WYe=Ae({...SC.shape,...Qk.shape,description:re().optional(),inputSchema:Ae({type:ht("object"),properties:Ei(re(),Zh).optional(),required:zt(re()).optional()}).catchall(fi()),outputSchema:Ae({type:ht("object"),properties:Ei(re(),Zh).optional(),required:zt(re()).optional()}).catchall(fi()).optional(),annotations:pt(sNr),execution:pt(cNr),_meta:Ei(re(),fi()).optional()}),mfe=e2.extend({method:ht("tools/list")}),uNr=t2.extend({tools:zt(WYe)}),tz=ac.extend({content:zt(hfe).default([]),structuredContent:Ei(re(),fi()).optional(),isError:pt(Qi())}),QAi=tz.or(ac.extend({toolResult:fi()})),lNr=Hu.extend({name:re(),arguments:pt(Ei(re(),fi()))}),i2=As.extend({method:ht("tools/call"),params:lNr}),pNr=cf.extend({method:ht("notifications/tools/list_changed")}),a2=Fn(["debug","info","notice","warning","error","critical","alert","emergency"]),fNr=Hu.extend({level:a2}),gfe=As.extend({method:ht("logging/setLevel"),params:fNr}),dNr=YT.extend({level:a2,logger:re().optional(),data:fi()}),hNr=cf.extend({method:ht("notifications/message"),params:dNr}),mNr=Ae({name:re().optional()}),gNr=Ae({hints:pt(zt(mNr)),costPriority:pt(Mn().min(0).max(1)),speedPriority:pt(Mn().min(0).max(1)),intelligencePriority:pt(Mn().min(0).max(1))}),yNr=Ae({mode:pt(Fn(["auto","required","none"]))}),vNr=Ae({type:ht("tool_result"),toolUseId:re().describe("The unique identifier for the corresponding tool call."),content:zt(hfe).default([]),structuredContent:Ae({}).passthrough().optional(),isError:pt(Qi()),_meta:pt(Ae({}).passthrough())}).passthrough(),bNr=V5("type",[pfe,ffe,dfe]),B5=V5("type",[pfe,ffe,dfe,tNr,vNr]),ENr=Ae({role:Fn(["user","assistant"]),content:hn([B5,zt(B5)]),_meta:pt(Ae({}).passthrough())}).passthrough(),_Nr=Hu.extend({messages:zt(ENr),modelPreferences:gNr.optional(),systemPrompt:re().optional(),includeContext:Fn(["none","thisServer","allServers"]).optional(),temperature:Mn().optional(),maxTokens:Mn().int(),stopSequences:zt(re()).optional(),metadata:Zh.optional(),tools:pt(zt(WYe)),toolChoice:pt(yNr)}),TNr=As.extend({method:ht("sampling/createMessage"),params:_Nr}),yfe=ac.extend({model:re(),stopReason:pt(Fn(["endTurn","stopSequence","maxTokens"]).or(re())),role:Fn(["user","assistant"]),content:bNr}),vfe=ac.extend({model:re(),stopReason:pt(Fn(["endTurn","stopSequence","maxTokens","toolUse"]).or(re())),role:Fn(["user","assistant"]),content:hn([B5,zt(B5)])}),xNr=Ae({type:ht("boolean"),title:re().optional(),description:re().optional(),default:Qi().optional()}),ONr=Ae({type:ht("string"),title:re().optional(),description:re().optional(),minLength:Mn().optional(),maxLength:Mn().optional(),format:Fn(["email","uri","date","date-time"]).optional(),default:re().optional()}),SNr=Ae({type:Fn(["number","integer"]),title:re().optional(),description:re().optional(),minimum:Mn().optional(),maximum:Mn().optional(),default:Mn().optional()}),ANr=Ae({type:ht("string"),title:re().optional(),description:re().optional(),enum:zt(re()),default:re().optional()}),CNr=Ae({type:ht("string"),title:re().optional(),description:re().optional(),oneOf:zt(Ae({const:re(),title:re()})),default:re().optional()}),wNr=Ae({type:ht("string"),title:re().optional(),description:re().optional(),enum:zt(re()),enumNames:zt(re()).optional(),default:re().optional()}),PNr=hn([ANr,CNr]),DNr=Ae({type:ht("array"),title:re().optional(),description:re().optional(),minItems:Mn().optional(),maxItems:Mn().optional(),items:Ae({type:ht("string"),enum:zt(re())}),default:zt(re()).optional()}),NNr=Ae({type:ht("array"),title:re().optional(),description:re().optional(),minItems:Mn().optional(),maxItems:Mn().optional(),items:Ae({anyOf:zt(Ae({const:re(),title:re()}))}),default:zt(re()).optional()}),INr=hn([DNr,NNr]),RNr=hn([wNr,PNr,INr]),LNr=hn([RNr,xNr,ONr,SNr]),kNr=Hu.extend({mode:ht("form").optional(),message:re(),requestedSchema:Ae({type:ht("object"),properties:Ei(re(),LNr),required:zt(re()).optional()})}),$Nr=Hu.extend({mode:ht("url"),message:re(),elicitationId:re(),url:re().url()}),MNr=hn([kNr,$Nr]),FNr=As.extend({method:ht("elicitation/create"),params:MNr}),jNr=YT.extend({elicitationId:re()}),VNr=cf.extend({method:ht("notifications/elicitation/complete"),params:jNr}),rz=ac.extend({action:Fn(["accept","decline","cancel"]),content:U5(e=>e===null?void 0:e,Ei(re(),hn([re(),Mn(),Qi(),zt(re())])).optional())}),qNr=Ae({type:ht("ref/resource"),uri:re()});var UNr=Ae({type:ht("ref/prompt"),name:re()}),BNr=Hu.extend({ref:hn([UNr,qNr]),argument:Ae({name:re(),value:re()}),context:Ae({arguments:Ei(re(),re()).optional()}).optional()}),zNr=As.extend({method:ht("completion/complete"),params:BNr});var HNr=ac.extend({completion:op({values:zt(re()).max(100),total:pt(Mn().int()),hasMore:pt(Qi())})}),GNr=Ae({uri:re().startsWith("file://"),name:re().optional(),_meta:Ei(re(),fi()).optional()}),KNr=As.extend({method:ht("roots/list")}),bfe=ac.extend({roots:zt(GNr)}),YNr=cf.extend({method:ht("notifications/roots/list_changed")}),eCi=hn([Y5,sfe,zNr,gfe,eNr,JDr,kDr,MDr,VDr,zDr,GDr,i2,mfe,X5,Z5,Q5]),tCi=hn([K5,W5,cfe,YNr,n2]),rCi=hn([G5,yfe,vfe,rz,bfe,J5,ez,AC]),nCi=hn([Y5,TNr,FNr,KNr,X5,Z5,Q5]),iCi=hn([K5,W5,hNr,YDr,UDr,pNr,oNr,n2,VNr]),aCi=hn([G5,PDr,HNr,aNr,ZDr,$Dr,FDr,qDr,tz,uNr,J5,ez,AC]),Pr=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===sn.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new nfe(i.elicitations,r)}return new e(t,r,n)}},nfe=class extends Pr{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(sn.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){var t,r;return(r=(t=this.data)===null||t===void 0?void 0:t.elicitations)!==null&&r!==void 0?r:[]}};function g0(e){return e==="completed"||e==="failed"||e==="cancelled"}var WNr=Symbol("Let zodToJsonSchema decide on which parser to use");var jCi=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Efe(e){let t=C5(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");let n=GKe(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function _fe(e,t){let r=m0(e,t);if(!r.success)throw r.error;return r.data}var tIr=6e4,nz=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(K5,r=>{this._oncancel(r)}),this.setNotificationHandler(W5,r=>{this._onprogress(r)}),this.setRequestHandler(Y5,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(X5,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Pr(sn.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(Z5,async(r,n)=>{let i=async()=>{var a;let o=r.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(c.type==="response"||c.type==="error"){let u=c.message,l=u.id,p=this._requestResolvers.get(l);if(p)if(this._requestResolvers.delete(l),c.type==="response")p(u);else{let f=u,d=new Pr(f.error.code,f.error.message,f.error.data);p(d)}else{let f=c.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${l}`))}continue}await((a=this._transport)===null||a===void 0?void 0:a.send(c.message,{relatedRequestId:n.requestId}))}}let s=await this._taskStore.getTask(o,n.sessionId);if(!s)throw new Pr(sn.InvalidParams,`Task not found: ${o}`);if(!g0(s.status))return await this._waitForTaskUpdate(o,n.signal),await i();if(g0(s.status)){let c=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...c,_meta:{...c._meta,[Qh]:{taskId:o}}}}return await i()};return await i()}),this.setRequestHandler(Q5,async(r,n)=>{var i;try{let{tasks:a,nextCursor:o}=await this._taskStore.listTasks((i=r.params)===null||i===void 0?void 0:i.cursor,n.sessionId);return{tasks:a,nextCursor:o,_meta:{}}}catch(a){throw new Pr(sn.InvalidParams,`Failed to list tasks: ${a instanceof Error?a.message:String(a)}`)}}),this.setRequestHandler(BYe,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Pr(sn.InvalidParams,`Task not found: ${r.params.taskId}`);if(g0(i.status))throw new Pr(sn.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new Pr(sn.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(i){throw i instanceof Pr?i:new Pr(sn.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(t){let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}_setupTimeout(t,r,n,i,a=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:a,onTimeout:i})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),Pr.fromError(sn.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){var r,n,i;this._transport=t;let a=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{a?.(),this._onclose()};let o=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=c=>{o?.(c),this._onerror(c)};let s=(i=this._transport)===null||i===void 0?void 0:i.onmessage;this._transport.onmessage=(c,u)=>{s?.(c,u),Zk(c)||VYe(c)?this._onresponse(c):ofe(c)?this._onrequest(c,u):MYe(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var t;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let n=Pr.fromError(sn.ConnectionClosed,"Connection closed");this._transport=void 0,(t=this.onclose)===null||t===void 0||t.call(this);for(let i of r.values())i(n)}_onerror(t){var r;(r=this.onerror)===null||r===void 0||r.call(this,t)}_onnotification(t){var r;let n=(r=this._notificationHandlers.get(t.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(t)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(t,r){var n,i,a,o,s,c;let u=(n=this._requestHandlers.get(t.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,l=this._transport,p=(o=(a=(i=t.params)===null||i===void 0?void 0:i._meta)===null||a===void 0?void 0:a[Qh])===null||o===void 0?void 0:o.taskId;if(u===void 0){let v={jsonrpc:"2.0",id:t.id,error:{code:sn.MethodNotFound,message:"Method not found"}};p&&this._taskMessageQueue?this._enqueueTaskMessage(p,{type:"error",message:v,timestamp:Date.now()},l?.sessionId).catch(_=>this._onerror(new Error(`Failed to enqueue error response: ${_}`))):l?.send(v).catch(_=>this._onerror(new Error(`Failed to send an error response: ${_}`)));return}let f=new AbortController;this._requestHandlerAbortControllers.set(t.id,f);let d=(s=t.params)===null||s===void 0?void 0:s.task,h=this._taskStore?this.requestTaskStore(t,l?.sessionId):void 0,m={signal:f.signal,sessionId:l?.sessionId,_meta:(c=t.params)===null||c===void 0?void 0:c._meta,sendNotification:async v=>{let _={relatedRequestId:t.id};p&&(_.relatedTask={taskId:p}),await this.notification(v,_)},sendRequest:async(v,_,O)=>{var x,S;let A={...O,relatedRequestId:t.id};p&&!A.relatedTask&&(A.relatedTask={taskId:p});let P=(S=(x=A.relatedTask)===null||x===void 0?void 0:x.taskId)!==null&&S!==void 0?S:p;return P&&h&&await h.updateTaskStatus(P,"input_required"),await this.request(v,_,A)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:p,taskStore:h,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{d&&this.assertTaskHandlerCapability(t.method)}).then(()=>u(t,m)).then(async v=>{if(f.signal.aborted)return;let _={result:v,jsonrpc:"2.0",id:t.id};p&&this._taskMessageQueue?await this._enqueueTaskMessage(p,{type:"response",message:_,timestamp:Date.now()},l?.sessionId):await l?.send(_)},async v=>{var _;if(f.signal.aborted)return;let O={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(v.code)?v.code:sn.InternalError,message:(_=v.message)!==null&&_!==void 0?_:"Internal error",...v.data!==void 0&&{data:v.data}}};p&&this._taskMessageQueue?await this._enqueueTaskMessage(p,{type:"error",message:O,timestamp:Date.now()},l?.sessionId):await l?.send(O)}).catch(v=>this._onerror(new Error(`Failed to send response: ${v}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,i=Number(r),a=this._progressHandlers.get(i);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let o=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),o(c);return}a(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Zk(t))n(t);else{let o=new Pr(t.error.code,t.error.message,t.error.data);n(o)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let a=!1;if(Zk(t)&&t.result&&typeof t.result=="object"){let o=t.result;if(o.task&&typeof o.task=="object"){let s=o.task;typeof s.taskId=="string"&&(a=!0,this._taskProgressTokens.set(s.taskId,r))}}if(a||this._progressHandlers.delete(r),Zk(t))i(t);else{let o=Pr.fromError(t.error.code,t.error.message,t.error.data);i(o)}}get transport(){return this._transport}async close(){var t;await((t=this._transport)===null||t===void 0?void 0:t.close())}async*requestStream(t,r,n){var i,a,o,s;let{task:c}=n??{};if(!c){try{yield{type:"result",result:await this.request(t,r,n)}}catch(l){yield{type:"error",error:l instanceof Pr?l:new Pr(sn.InternalError,String(l))}}return}let u;try{let l=await this.request(t,AC,n);if(l.task)u=l.task.taskId,yield{type:"taskCreated",task:l.task};else throw new Pr(sn.InternalError,"Task creation did not return a task");for(;;){let p=await this.getTask({taskId:u},n);if(yield{type:"taskStatus",task:p},g0(p.status)){p.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:u},r,n)}:p.status==="failed"?yield{type:"error",error:new Pr(sn.InternalError,`Task ${u} failed`)}:p.status==="cancelled"&&(yield{type:"error",error:new Pr(sn.InternalError,`Task ${u} was cancelled`)});return}if(p.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:u},r,n)};return}let f=(o=(i=p.pollInterval)!==null&&i!==void 0?i:(a=this._options)===null||a===void 0?void 0:a.defaultTaskPollInterval)!==null&&o!==void 0?o:1e3;await new Promise(d=>setTimeout(d,f)),(s=n?.signal)===null||s===void 0||s.throwIfAborted()}}catch(l){yield{type:"error",error:l instanceof Pr?l:new Pr(sn.InternalError,String(l))}}}request(t,r,n){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,task:s,relatedTask:c}=n??{};return new Promise((u,l)=>{var p,f,d,h,m,v,_;let O=F=>{l(F)};if(!this._transport){O(new Error("Not connected"));return}if(((p=this._options)===null||p===void 0?void 0:p.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(F){O(F);return}(f=n?.signal)===null||f===void 0||f.throwIfAborted();let x=this._requestMessageId++,S={...t,jsonrpc:"2.0",id:x};n?.onprogress&&(this._progressHandlers.set(x,n.onprogress),S.params={...t.params,_meta:{...((d=t.params)===null||d===void 0?void 0:d._meta)||{},progressToken:x}}),s&&(S.params={...S.params,task:s}),c&&(S.params={...S.params,_meta:{...((h=S.params)===null||h===void 0?void 0:h._meta)||{},[Qh]:c}});let A=F=>{var K;this._responseHandlers.delete(x),this._progressHandlers.delete(x),this._cleanupTimeout(x),(K=this._transport)===null||K===void 0||K.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:x,reason:String(F)}},{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(H=>this._onerror(new Error(`Failed to send cancellation: ${H}`)));let $=F instanceof Pr?F:new Pr(sn.RequestTimeout,String(F));l($)};this._responseHandlers.set(x,F=>{var K;if(!(!((K=n?.signal)===null||K===void 0)&&K.aborted)){if(F instanceof Error)return l(F);try{let $=m0(r,F.result);$.success?u($.data):l($.error)}catch($){l($)}}}),(m=n?.signal)===null||m===void 0||m.addEventListener("abort",()=>{var F;A((F=n?.signal)===null||F===void 0?void 0:F.reason)});let P=(v=n?.timeout)!==null&&v!==void 0?v:tIr,k=()=>A(Pr.fromError(sn.RequestTimeout,"Request timed out",{timeout:P}));this._setupTimeout(x,P,n?.maxTotalTimeout,k,(_=n?.resetTimeoutOnProgress)!==null&&_!==void 0?_:!1);let D=c?.taskId;if(D){let F=K=>{let $=this._responseHandlers.get(x);$?$(K):this._onerror(new Error(`Response handler missing for side-channeled request ${x}`))};this._requestResolvers.set(x,F),this._enqueueTaskMessage(D,{type:"request",message:S,timestamp:Date.now()}).catch(K=>{this._cleanupTimeout(x),l(K)})}else this._transport.send(S,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(F=>{this._cleanupTimeout(x),l(F)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},J5,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},ez,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},zYe,r)}async notification(t,r){var n,i,a,o,s;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let c=(n=r?.relatedTask)===null||n===void 0?void 0:n.taskId;if(c){let f={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...((i=t.params)===null||i===void 0?void 0:i._meta)||{},[Qh]:r.relatedTask}}};await this._enqueueTaskMessage(c,{type:"notification",message:f,timestamp:Date.now()});return}if(((o=(a=this._options)===null||a===void 0?void 0:a.debouncedNotificationMethods)!==null&&o!==void 0?o:[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{var f,d;if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let h={...t,jsonrpc:"2.0"};r?.relatedTask&&(h={...h,params:{...h.params,_meta:{...((f=h.params)===null||f===void 0?void 0:f._meta)||{},[Qh]:r.relatedTask}}}),(d=this._transport)===null||d===void 0||d.send(h,r).catch(m=>this._onerror(m))});return}let p={...t,jsonrpc:"2.0"};r?.relatedTask&&(p={...p,params:{...p.params,_meta:{...((s=p.params)===null||s===void 0?void 0:s._meta)||{},[Qh]:r.relatedTask}}}),await this._transport.send(p,r)}setRequestHandler(t,r){let n=Efe(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,a)=>{let o=_fe(t,i);return Promise.resolve(r(o,a))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=Efe(t);this._notificationHandlers.set(n,i=>{let a=_fe(t,i);return Promise.resolve(r(a))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){var i;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let a=(i=this._options)===null||i===void 0?void 0:i.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,a)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let i of n)if(i.type==="request"&&ofe(i.message)){let a=i.message.id,o=this._requestResolvers.get(a);o?(o(new Pr(sn.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){var n,i,a;let o=(i=(n=this._options)===null||n===void 0?void 0:n.defaultTaskPollInterval)!==null&&i!==void 0?i:1e3;try{let s=await((a=this._taskStore)===null||a===void 0?void 0:a.getTask(t));s?.pollInterval&&(o=s.pollInterval)}catch{}return new Promise((s,c)=>{if(r.aborted){c(new Pr(sn.InvalidRequest,"Request cancelled"));return}let u=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(u),c(new Pr(sn.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!t)throw new Error("No request provided");return await n.createTask(i,t.id,{method:t.method,params:t.params},r)},getTask:async i=>{let a=await n.getTask(i,r);if(!a)throw new Pr(sn.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(i,a,o)=>{await n.storeTaskResult(i,a,o,r);let s=await n.getTask(i,r);if(s){let c=n2.parse({method:"notifications/tasks/status",params:s});await this.notification(c),g0(s.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,a,o)=>{let s=await n.getTask(i,r);if(!s)throw new Pr(sn.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(g0(s.status))throw new Pr(sn.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,a,o,r);let c=await n.getTask(i,r);if(c){let u=n2.parse({method:"notifications/tasks/status",params:c});await this.notification(u),g0(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function XYe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function JYe(e,t){let r={...e};for(let n in t){let i=n,a=t[i];if(a===void 0)continue;let o=r[i];XYe(o)&&XYe(a)?r[i]={...o,...a}:r[i]=a}return r}var BXe=dt(Fz(),1),zXe=dt(UXe(),1);function B$r(){let e=new BXe.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,zXe.default)(e),e}var Vz=class{constructor(t){this._ajv=t??B$r()}getValidator(t){var r;let n="$id"in t&&typeof t.$id=="string"?(r=this._ajv.getSchema(t.$id))!==null&&r!==void 0?r:this._ajv.compile(t):this._ajv.compile(t);return i=>n(i)?{valid:!0,data:i,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var qz=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function HXe(e,t,r){var n;if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!(!((n=e.tools)===null||n===void 0)&&n.call))throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function GXe(e,t,r){var n,i;if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!(!((n=e.sampling)===null||n===void 0)&&n.createMessage))throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!(!((i=e.elicitation)===null||i===void 0)&&i.create))throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Uz=class extends nz{constructor(t,r){var n,i;super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(a2.options.map((a,o)=>[a,o])),this.isMessageIgnored=(a,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(a)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._instructions=r?.instructions,this._jsonSchemaValidator=(i=r?.jsonSchemaValidator)!==null&&i!==void 0?i:new Vz,this.setRequestHandler(sfe,a=>this._oninitialize(a)),this.setNotificationHandler(cfe,()=>{var a;return(a=this.oninitialized)===null||a===void 0?void 0:a.call(this)}),this._capabilities.logging&&this.setRequestHandler(gfe,async(a,o)=>{var s;let c=o.sessionId||((s=o.requestInfo)===null||s===void 0?void 0:s.headers["mcp-session-id"])||void 0,{level:u}=a.params,l=a2.safeParse(u);return l.success&&this._loggingLevels.set(c,l.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new qz(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=JYe(this._capabilities,t)}setRequestHandler(t,r){var n,i,a;let o=C5(t),s=o?.method;if(!s)throw new Error("Schema is missing a method literal");let c;if(xC(s)){let l=s,p=(n=l._zod)===null||n===void 0?void 0:n.def;c=(i=p?.value)!==null&&i!==void 0?i:l.value}else{let l=s,p=l._def;c=(a=p?.value)!==null&&a!==void 0?a:l.value}if(typeof c!="string")throw new Error("Schema method literal must be a string");if(c==="tools/call"){let l=async(p,f)=>{let d=m0(i2,p);if(!d.success){let _=d.error instanceof Error?d.error.message:String(d.error);throw new Pr(sn.InvalidParams,`Invalid tools/call request: ${_}`)}let{params:h}=d.data,m=await Promise.resolve(r(p,f));if(h.task){let _=m0(AC,m);if(!_.success){let O=_.error instanceof Error?_.error.message:String(_.error);throw new Pr(sn.InvalidParams,`Invalid task creation result: ${O}`)}return _.data}let v=m0(tz,m);if(!v.success){let _=v.error instanceof Error?v.error.message:String(v.error);throw new Pr(sn.InvalidParams,`Invalid tools/call result: ${_}`)}return v.data};return super.setRequestHandler(t,l)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){var r,n,i;switch(t){case"sampling/createMessage":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.sampling))throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.elicitation))throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!(!((i=this._clientCapabilities)===null||i===void 0)&&i.roots))throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){var r,n;switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!(!((n=(r=this._clientCapabilities)===null||r===void 0?void 0:r.elicitation)===null||n===void 0)&&n.url))throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){var r,n;GXe((n=(r=this._clientCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests,t,"Client")}assertTaskHandlerCapability(t){var r;this._capabilities&&HXe((r=this._capabilities.tasks)===null||r===void 0?void 0:r.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:IYe.includes(r)?r:ife,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},G5)}async createMessage(t,r){var n,i;if((t.tools||t.toolChoice)&&!(!((i=(n=this._clientCapabilities)===null||n===void 0?void 0:n.sampling)===null||i===void 0)&&i.tools))throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let a=t.messages[t.messages.length-1],o=Array.isArray(a.content)?a.content:[a.content],s=o.some(p=>p.type==="tool_result"),c=t.messages.length>1?t.messages[t.messages.length-2]:void 0,u=c?Array.isArray(c.content)?c.content:[c.content]:[],l=u.some(p=>p.type==="tool_use");if(s){if(o.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let p=new Set(u.filter(d=>d.type==="tool_use").map(d=>d.id)),f=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(p.size!==f.size||![...p].every(d=>f.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},vfe,r):this.request({method:"sampling/createMessage",params:t},yfe,r)}async elicitInput(t,r){var n,i,a,o,s;switch((n=t.mode)!==null&&n!==void 0?n:"form"){case"url":{if(!(!((a=(i=this._clientCapabilities)===null||i===void 0?void 0:i.elicitation)===null||a===void 0)&&a.url))throw new Error("Client does not support url elicitation.");let u=t;return this.request({method:"elicitation/create",params:u},rz,r)}case"form":{if(!(!((s=(o=this._clientCapabilities)===null||o===void 0?void 0:o.elicitation)===null||s===void 0)&&s.form))throw new Error("Client does not support form elicitation.");let u=t.mode==="form"?t:{...t,mode:"form"},l=await this.request({method:"elicitation/create",params:u},rz,r);if(l.action==="accept"&&l.content&&u.requestedSchema)try{let f=this._jsonSchemaValidator.getValidator(u.requestedSchema)(l.content);if(!f.valid)throw new Pr(sn.InvalidParams,`Elicitation response content does not match requested schema: ${f.errorMessage}`)}catch(p){throw p instanceof Pr?p:new Pr(sn.InternalError,`Error validating elicitation response: ${p instanceof Error?p.message:String(p)}`)}return l}}}createElicitationCompletionNotifier(t,r){var n,i;if(!(!((i=(n=this._clientCapabilities)===null||n===void 0?void 0:n.elicitation)===null||i===void 0)&&i.url))throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},bfe,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var fhe=dt(require("node:process"),1);var Bz=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
1652
1652
  `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),H$r(r)}clear(){this._buffer=void 0}};function H$r(e){return qYe.parse(JSON.parse(e))}function KXe(e){return JSON.stringify(e)+`
1653
- `}var zz=class{constructor(t=fhe.default.stdin,r=fhe.default.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Bz,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var t,r;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(t=this.onmessage)===null||t===void 0||t.call(this,n)}catch(n){(r=this.onerror)===null||r===void 0||r.call(this,n)}}async close(){var t;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(t=this.onclose)===null||t===void 0||t.call(this)}send(t){return new Promise(r=>{let n=KXe(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var WXe="0.4.10";var $2={name:"@sap-ux/fiori-mcp-server",description:"SAP Fiori - Model Context Protocol (MCP) server",version:WXe,keywords:["SAP Fiori tools","SAP Fiori elements","SAP Fiori freestyle","MCP","AI"],repository:{type:"git",url:"https://github.com/SAP/open-ux-tools.git",directory:"packages/fiori-mcp-server"},bugs:{url:"https://github.com/SAP/open-ux-tools/issues?q=is%3Aopen+is%3Aissue+label%3Abug+label%3Afiori-mcp-server"},license:"Apache-2.0",main:"dist/index.js",scripts:{"build-esbuild-base":"esbuild --bundle --platform=node --target=node20 --outdir=dist --external:vscode --external:@lancedb/lancedb --external:@xenova/transformers --external:@sap-ux/fiori-docs-embeddings --external:@sap-ux/store --main-fields=module,main src/index.ts","build-dev":"pnpm run build-esbuild-base --sourcemap=inline","build-compile":"tsc --noEmit","build-bundle":"pnpm run build-esbuild-base --minify",build:"npm-run-all build-compile build-bundle",watch:"tsc --watch",bundle:"npm-run-all build tgz:package tgz:rename","tgz:package":"pnpm pack","tgz:rename":"node -e \"const fs=require('fs'), p=require('./package.json'), d=new Date().toISOString().split('T')[0], oldName=p.name.startsWith('@') ? `${p.name.replace('@', '').replace('/', '-')}-${p.version}.tgz` : `${p.name}-${p.version}.tgz`; fs.renameSync(oldName, `${oldName.replace('.tgz','')}-${d}.tgz`)\"",clean:"rimraf --glob dist test/test-output *.tsbuildinfo",format:"prettier --write '**/*.{js,json,ts,yaml,yml}' --ignore-path ../../.prettierignore",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",test:"jest --ci --forceExit --detectOpenHandles --colors",inspector:"npx @modelcontextprotocol/inspector node dist/index.js",start:'npx -y supergateway --port 9881 --sessionTimeout 300000 --stdio "node ./dist/index.js"',"view:integration":"promptfoo view -y","test:integration:once":"promptfoo eval --config test/integration/scenarios/promptfooconfig.yaml --max-concurrency 1 --repeat 1 --output reports/integration.txt","test:integration:dev":"promptfoo eval --config test/integration/scenarios/test-dev.yaml --max-concurrency 1 --repeat 1 --output reports/integration.txt","test:integration:multiple":"npm run test:promptfoo -- --repeat 5"},files:["LICENSE","dist","!dist/**/*.map"],bin:{"fiori-mcp":"./dist/index.js"},devDependencies:{"npm-run-all2":"8.0.4",esbuild:"0.25.6","@modelcontextprotocol/sdk":"1.24.1","@sap-ux/axios-extension":"workspace:*","@sap/ux-specification":"1.139.1","@sap-ux/project-access":"workspace:*","@sap-ux/fiori-annotation-api":"workspace:*","@sap-ux/annotation-converter":"0.10.8","@sap-ux/edmx-parser":"0.9.6","@sap-ux/fiori-docs-embeddings":"workspace:*","@sap-ux/i18n":"workspace:*","@sap-ux/logger":"workspace:*","@sap-ux/odata-annotation-core-types":"workspace:*","@sap-ux/odata-entity-model":"workspace:*","@sap-ux/text-document-utils":"workspace:*","@types/diff":"5.0.9","@types/json-schema":"7.0.5","@types/mem-fs":"1.1.2","@types/mem-fs-editor":"7.0.1","@sap-ux/btp-utils":"workspace:*","@sap-ux/feature-toggle":"workspace:*","@sap-ux/nodejs-utils":"workspace:*","@sap-ux/telemetry":"workspace:*",i18next:"25.3.0","os-name":"4.0.1",zod:"4.1.13","@sap-ai-sdk/foundation-models":"2.3.0","@sap-ai-sdk/langchain":"2.3.0",promptfoo:"0.119.14","@langchain/mcp-adapters":"1.0.2","@langchain/core":"1.1.1"},dependencies:{"@sap-ux/fiori-docs-embeddings":"workspace:*","@sap-ux/store":"workspace:*","@xenova/transformers":"2.17.2","@lancedb/lancedb":"0.22.0","mem-fs":"2.1.0","mem-fs-editor":"9.4.0"},engines:{node:">=20.x"}};var ZXe=Ae({name:re().describe("Name of the Fiori application. Usually derived from the `sap.app/id` field in the application's manifest.json."),appPath:re().describe("Absolute path to the Fiori application's root directory."),projectPath:re().describe("Absolute path to the root directory of the project containing this Fiori application. For EDMXBackend (standalone) projects, this is the same as `appPath`. For CAP projects, this points to the CAP project root, which may contain multiple Fiori applications."),projectType:Fn(["EDMXBackend","CAPJava","CAPNodejs"]).describe("Type of project the application belongs to."),odataVersion:re().describe("OData protocol version used by the application's main service.")}),ox=hn([re(),zt(hn([re(),Mn()]))]),QXe=Ae({functionalityId:ox.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),description:re()}),XXe=Fn(["object","array","string","number","boolean","null","integer","any"]),JXe=Ae({type:hn([XXe,zt(XXe)]).optional(),description:re().optional(),properties:M5().optional()}).catchall(M5()),eJe=JXe.extend({properties:Ei(re(),hn([JXe,Qi()])).optional()});var tJe=Ae({searchPath:zt(re()).describe("Path to search for Fiori applications (defaults to current directory). If VSCode - list of VS Code workspace folder paths(`workspace.workspaceFolders`)")}),rJe=Ae({appPath:re().describe("Path to the root folder of the Fiori application (where package.json and ui5.yaml reside) if one exists or to the current directory. Path should be an absolute path.")}),nJe=Ae({appPath:re().describe("Path to the Fiori application if one exists or to the current directory. Path should be an absolute path."),functionalityId:ox.describe("The ID of the functionality to get details for")}),iJe=Ae({functionalityId:ox.describe("The ID of the functionality to execute"),parameters:Ei(re(),fi()).describe("Parameters for the functionality execution"),appPath:re().describe("Path to the Fiori application if one exists or to the current directory. Path should be an absolute path.")}).describe('Input object for executing a functionality. Only three top-level properties are allowed: "functionalityId", "parameters", and "appPath". All other dynamic or functionality-specific inputs must be included inside the "parameters" object. Do not place any additional fields at the root level.'),xIi=Ae({query:re().min(2).describe("The search query for fiori elements, annotations, sapui5, fiori tools documentation")});var SIi=re().describe("Search results as formatted text"),aJe=Ae({applications:zt(ZXe)}),oJe=Ae({applicationPath:re(),functionalities:zt(QXe)}),sJe=Ae({functionalityId:ox.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),name:re(),description:re(),technicalDescription:re().optional(),parameters:eJe,prerequisites:zt(re()).optional(),impact:re().optional(),examples:zt(re()).optional(),pageName:re().optional()}),cJe=Ae({functionalityId:ox,status:re(),message:re(),parameters:fi(),appPath:re(),changes:zt(re()),timestamp:re()});var Wge=dt(require("node:fs/promises")),vf=dt(require("node:path"));var yf=dt(V0());function UHr(){let e=globalThis.LOG_LEVEL,t=process.env.LOG_LEVEL,r=process.argv.find(i=>i.startsWith("--log-level="))?.split("=")[1],n=e||t||r;if(n)switch(n.toUpperCase()){case"ERROR":return yf.LogLevel.Error;case"WARN":return yf.LogLevel.Warn;case"INFO":return yf.LogLevel.Info;case"DEBUG":return yf.LogLevel.Debug;case"VERBOSE":return yf.LogLevel.Verbose;case"SILLY":return yf.LogLevel.Silly;default:break}return yf.LogLevel.Error}var BHr=UHr(),Nt=new yf.ToolsLogger({logLevel:BHr,transports:[new yf.ConsoleTransport],logPrefix:"fiori-mcp"});async function $ot(){try{let r;try{r=require("@sap-ux/fiori-docs-embeddings")}catch{try{r=await import("@sap-ux/fiori-docs-embeddings")}catch{r=null}}if(!r||typeof r.getDataPath!="function")throw new Error("Package not found or invalid");let n=r.getDataPath();return await Wge.default.access(n),Nt.log("\u2713 Using @sap-ux/fiori-docs-embeddings package"),{dataPath:n,embeddingsPath:vf.default.join(n,"embeddings"),searchPath:vf.default.join(n,"search"),docsPath:vf.default.join(n,"docs"),isExternalPackage:!0,isAvailable:!0}}catch{Nt.warn("Could not load @sap-ux/fiori-docs-embeddings package, trying local data...")}let e=vf.default.join(__dirname,"../../data");try{return await Wge.default.access(e),Nt.log("\u2713 Using local data directory"),{dataPath:e,embeddingsPath:vf.default.join(e,"embeddings"),searchPath:vf.default.join(e,"search"),docsPath:vf.default.join(e,"docs"),isExternalPackage:!1,isAvailable:!0}}catch{Nt.warn("Local data directory not available either")}let t=vf.default.join(__dirname,"../../data");return Nt.warn("\u26A0\uFE0F No embeddings data available - running in limited mode"),{dataPath:t,embeddingsPath:vf.default.join(t,"embeddings"),searchPath:vf.default.join(t,"search"),docsPath:vf.default.join(t,"docs"),isExternalPackage:!1,isAvailable:!1}}var bc=dt(Zd()),wF=require("node:path");async function fu(e){try{e=(0,wF.join)(e);try{let t=await(0,bc.createApplicationAccess)(e);return{root:t.project.root,appId:t.getAppId(),applicationAccess:t}}catch(t){Nt.warn(`Application was not found by given path. Error: ${t}`);let r=await(0,bc.findProjectRoot)(e),n=await(0,bc.getProject)(r);if(n)return{root:n.root,appId:""}}}catch(t){Nt.warn(`Project was not found by given path. Error: ${t}`);return}}var XY=e=>{let t;switch(e){case bc.DirName.View:{t=(0,wF.join)(bc.DirName.Ext,bc.DirName.View);break}case bc.DirName.Fragment:{t=(0,wF.join)(bc.DirName.Ext,bc.DirName.Fragment);break}case bc.DirName.Controller:{t=(0,wF.join)(bc.DirName.Ext,bc.DirName.Controller);break}default:t=e}return t},Cm=(e,t,r=new Set)=>{if(!e||typeof e!="object")return{};if(e.$ref?.startsWith("#/definitions/")){let i=e.$ref,a=i.replace("#/definitions/",""),o=t.definitions?.[a]??null;if(r.has(i))return{...o};if(r.add(i),o){let s={...e};return delete s.$ref,Cm({...o,...s},t,r)}}let n={...e};return n.properties&&(n.properties=Object.fromEntries(Object.entries(n.properties).map(([i,a])=>[i,Cm(a,t,r)]))),n.items&&(Array.isArray(n.items)?n.items=n.items.map(i=>Cm(i,t,r)):n.items=Cm(n.items,t,r)),n.allOf&&(n.allOf=n.allOf.map(i=>Cm(i,t,r))),n.anyOf&&(n.anyOf=n.anyOf.map(i=>Cm(i,t,r))),n.oneOf&&(n.oneOf=n.oneOf.map(i=>Cm(i,t,r))),typeof n.additionalProperties=="object"&&(n.additionalProperties=Cm(n.additionalProperties,t,r)),n},Nxt=(e,t)=>({type:"object",properties:{[e]:t}}),Oa=e=>{let t=GT(e);return delete t.$schema,t},wm=(e,t)=>{try{return e.parse(t)}catch(r){throw r instanceof dpe?new Error(`Missing required fields in parameters. ${JSON.stringify(r.issues,null,4)}`):new Error("Unknown error. Recheck input parameters.")}};var nLt=require("node:util"),iLt=require("node:child_process"),aLt=dt(HCe());async function nX(e="1.18.5"){let t="@sap/generator-fiori";if((await(0,aLt.findInstalledPackages)(t,{minVersion:e}))?.length<1)throw new Error(`Fiori generator not found. Please install the Fiori generator >=${e} with 'npm install -g ${t}' and retry this call`)}var iX=(0,nLt.promisify)(iLt.exec);var oLt=require("@lancedb/lancedb");var GCe=dt(require("fs/promises")),KCe=dt(require("node:path")),aX=class{connection=null;tables=[];tableIndex=null;metadata=null;dataPath;constructor(t){this.dataPath=t||""}async initialize(){try{Nt.log("Loading vector database from pre-built embeddings...");let t=await $ot();if(!t.isAvailable)throw new Error("No embeddings data available");this.dataPath=t.embeddingsPath,Nt.log(`Using embeddings path: ${this.dataPath} (external: ${t.isExternalPackage})`);let r=KCe.default.join(this.dataPath,"metadata.json"),n=await GCe.default.readFile(r,"utf-8");this.metadata=JSON.parse(n),Nt.log("\u2713 Embedding metadata loaded:"),Nt.log(` Model: ${this?.metadata?.model}`),Nt.log(` Dimensions: ${this?.metadata?.dimensions}`),Nt.log(` Total vectors: ${this?.metadata?.totalVectors}`),Nt.log(` Created: ${this?.metadata?.createdAt}`),this.connection=await(0,oLt.connect)(this.dataPath);let i=KCe.default.join(this.dataPath,"table_index.json");try{let a=await GCe.default.readFile(i,"utf-8");this.tableIndex=JSON.parse(a),this.tables=[];for(let o of this.tableIndex?.tables||[]){let s=await this.connection.openTable(o);this.tables.push(s)}Nt.log(`\u2713 Loaded ${this.tables.length} split tables`)}catch{Nt.log("No table index found, trying single table...");try{let a=await this.connection.openTable("documents");this.tables=[a],this.tableIndex={tables:["documents"],totalTables:1,maxVectorsPerTable:-1,totalVectors:this.metadata?.totalVectors||0}}catch(a){throw new Error(`No tables found: ${a}`)}}Nt.log("\u2713 Vector database loaded and ready")}catch(t){throw new Error(`Failed to load vector database: ${t}`)}}async semanticSearch(t,r=10,n){if(this.tables.length===0)throw new Error("Vector database not initialized");try{let i=[];for(let o of this.tables){let s=o.vectorSearch(t).limit(r*2);n&&(s=s.where(`category = "${n}"`));let c=await s.toArray();i.push(...c)}return i.sort((o,s)=>(o._distance||0)-(s._distance||0)),i.slice(0,r).map(o=>({document:{id:o.document_id,vector:o.vector,content:o.content,title:o.title,category:o.category,path:o.path,chunk_index:o.chunk_index,metadata:{tags:this.parseJsonField(o.tags_json)||[],headers:this.parseJsonField(o.headers_json)||[],lastModified:new Date(o.lastModified),wordCount:o.wordCount,excerpt:o.excerpt}},score:1-(o._distance||0),distance:o._distance||0}))}catch(i){throw Nt.error(`Semantic search failed: ${i}`),new Error(`Semantic search failed: ${i}`)}}async findSimilarToText(t,r=5){return Nt.warn("findSimilarToText requires embedding generation - not available in simplified mode"),[]}async findSimilarToDocument(t,r=5){if(this.tables.length===0)throw new Error("Vector database not initialized");try{let n=null;for(let s of this.tables){let c=await s.search("").where(`document_id = "${t}" AND chunk_index = 0`).limit(1).toArray();if(c.length>0){n=c[0].vector;break}}if(!n)return[];let i=[];for(let s of this.tables){let c=await s.vectorSearch(n).where(`document_id != "${t}"`).limit(r*2).toArray();i.push(...c)}let a=new Map;for(let s of i){let c=s.document_id,u=1-(s._distance||0);(!a.has(c)||a.get(c).score<u)&&a.set(c,{...s,score:u,distance:s._distance||0})}return Array.from(a.values()).sort((s,c)=>c.score-s.score).slice(0,r).map(s=>({document:{id:s.document_id,vector:s.vector,content:s.content,title:s.title,category:s.category,path:s.path,chunk_index:s.chunk_index,metadata:{tags:this.parseJsonField(s.tags_json)||[],headers:this.parseJsonField(s.headers_json)||[],lastModified:new Date(s.lastModified),wordCount:s.wordCount,excerpt:s.excerpt}},score:s.score,distance:s.distance}))}catch(n){return Nt.error(`Find similar documents failed: ${n}`),[]}}async getDocumentsByCategory(t,r){if(this.tables.length===0)throw new Error("Vector database not initialized");try{let n=[];for(let a of this.tables){let o=a.search("").where(`category = "${t}" AND chunk_index = 0`);r&&(o=o.limit(Math.ceil(r/this.tables.length)+10));let s=await o.toArray();n.push(...s)}return(r?n.slice(0,r):n).map(a=>({document:{id:a.document_id,vector:a.vector,content:a.content,title:a.title,category:a.category,path:a.path,chunk_index:a.chunk_index,metadata:{tags:this.parseJsonField(a.tags_json)||[],headers:this.parseJsonField(a.headers_json)||[],lastModified:new Date(a.lastModified),wordCount:a.wordCount,excerpt:a.excerpt}},score:1,distance:0}))}catch(n){return Nt.error(`Get documents by category failed: ${n}`),[]}}getMetadata(){return this.metadata}parseJsonField(t){try{return t?JSON.parse(t):[]}catch{return[]}}isInitialized(){return this.tables.length>0&&this.metadata!==null}async close(){this.connection&&(this.connection=null,this.tables=[],Nt.log("Vector database connection closed"))}};var oX=class{pipeline=null;initialized=!1;async initialize(){if(!this.initialized)try{let{pipeline:t}=await import("@xenova/transformers");this.pipeline=await t("feature-extraction","Xenova/all-MiniLM-L6-v2",{quantized:!1}),this.initialized=!0}catch(t){throw new Error(`Failed to initialize text embedding service: ${t}. Make sure @xenova/transformers is available.`)}}async generateEmbedding(t){if(!this.initialized||!this.pipeline)throw new Error("Text embedding service not initialized. Call initialize() first.");try{let r=t.replace(/\n+/g," ").replace(/\s+/g," ").trim().substring(0,8192);if(!r)throw new Error("Empty text provided for embedding");let n=await this.pipeline(r,{pooling:"mean",normalize:!0});return Array.from(n.data)}catch(r){throw new Error(`Failed to generate embedding: ${r}`)}}isInitialized(){return this.initialized}};async function YCe(e,t=!1){let{query:r,maxResults:n}=e;try{let i=new aX,a=new oX;await i.initialize(),await a.initialize();let o=await a.generateEmbedding(r),s=await i.semanticSearch(o,n??10);if(t){let c="";for(let[u,l]of s.entries())c+=`Result ${u+1}:
1653
+ `}var zz=class{constructor(t=fhe.default.stdin,r=fhe.default.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Bz,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var t,r;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(t=this.onmessage)===null||t===void 0||t.call(this,n)}catch(n){(r=this.onerror)===null||r===void 0||r.call(this,n)}}async close(){var t;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(t=this.onclose)===null||t===void 0||t.call(this)}send(t){return new Promise(r=>{let n=KXe(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var WXe="0.4.11";var $2={name:"@sap-ux/fiori-mcp-server",description:"SAP Fiori - Model Context Protocol (MCP) server",version:WXe,keywords:["SAP Fiori tools","SAP Fiori elements","SAP Fiori freestyle","MCP","AI"],repository:{type:"git",url:"https://github.com/SAP/open-ux-tools.git",directory:"packages/fiori-mcp-server"},bugs:{url:"https://github.com/SAP/open-ux-tools/issues?q=is%3Aopen+is%3Aissue+label%3Abug+label%3Afiori-mcp-server"},license:"Apache-2.0",main:"dist/index.js",scripts:{"build-esbuild-base":"esbuild --bundle --platform=node --target=node20 --outdir=dist --external:vscode --external:@lancedb/lancedb --external:@xenova/transformers --external:@sap-ux/fiori-docs-embeddings --external:@sap-ux/store --main-fields=module,main src/index.ts","build-dev":"pnpm run build-esbuild-base --sourcemap=inline","build-compile":"tsc --noEmit","build-bundle":"pnpm run build-esbuild-base --minify",build:"npm-run-all build-compile build-bundle",watch:"tsc --watch",bundle:"npm-run-all build tgz:package tgz:rename","tgz:package":"pnpm pack","tgz:rename":"node -e \"const fs=require('fs'), p=require('./package.json'), d=new Date().toISOString().split('T')[0], oldName=p.name.startsWith('@') ? `${p.name.replace('@', '').replace('/', '-')}-${p.version}.tgz` : `${p.name}-${p.version}.tgz`; fs.renameSync(oldName, `${oldName.replace('.tgz','')}-${d}.tgz`)\"",clean:"rimraf --glob dist test/test-output *.tsbuildinfo",format:"prettier --write '**/*.{js,json,ts,yaml,yml}' --ignore-path ../../.prettierignore",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",test:"jest --ci --forceExit --detectOpenHandles --colors",inspector:"npx @modelcontextprotocol/inspector node dist/index.js",start:'npx -y supergateway --port 9881 --sessionTimeout 300000 --stdio "node ./dist/index.js"',"view:integration":"promptfoo view -y","test:integration:once":"promptfoo eval --config test/integration/scenarios/promptfooconfig.yaml --max-concurrency 1 --repeat 1 --output reports/integration.txt","test:integration:dev":"promptfoo eval --config test/integration/scenarios/test-dev.yaml --max-concurrency 1 --repeat 1 --output reports/integration.txt","test:integration:multiple":"npm run test:promptfoo -- --repeat 5"},files:["LICENSE","dist","!dist/**/*.map"],bin:{"fiori-mcp":"./dist/index.js"},devDependencies:{"npm-run-all2":"8.0.4",esbuild:"0.25.6","@modelcontextprotocol/sdk":"1.24.1","@sap-ux/axios-extension":"workspace:*","@sap/ux-specification":"1.139.1","@sap-ux/project-access":"workspace:*","@sap-ux/fiori-annotation-api":"workspace:*","@sap-ux/annotation-converter":"0.10.8","@sap-ux/edmx-parser":"0.9.6","@sap-ux/fiori-docs-embeddings":"workspace:*","@sap-ux/i18n":"workspace:*","@sap-ux/logger":"workspace:*","@sap-ux/odata-annotation-core-types":"workspace:*","@sap-ux/odata-entity-model":"workspace:*","@sap-ux/text-document-utils":"workspace:*","@types/diff":"5.0.9","@types/json-schema":"7.0.5","@types/mem-fs":"1.1.2","@types/mem-fs-editor":"7.0.1","@sap-ux/btp-utils":"workspace:*","@sap-ux/feature-toggle":"workspace:*","@sap-ux/nodejs-utils":"workspace:*","@sap-ux/telemetry":"workspace:*",i18next:"25.3.0","os-name":"4.0.1",zod:"4.1.13","@sap-ai-sdk/foundation-models":"2.3.0","@sap-ai-sdk/langchain":"2.3.0",promptfoo:"0.119.14","@langchain/mcp-adapters":"1.0.2","@langchain/core":"1.1.1"},dependencies:{"@sap-ux/fiori-docs-embeddings":"workspace:*","@sap-ux/store":"workspace:*","@xenova/transformers":"2.17.2","@lancedb/lancedb":"0.22.0","mem-fs":"2.1.0","mem-fs-editor":"9.4.0"},engines:{node:">=20.x"}};var ZXe=Ae({name:re().describe("Name of the Fiori application. Usually derived from the `sap.app/id` field in the application's manifest.json."),appPath:re().describe("Absolute path to the Fiori application's root directory."),projectPath:re().describe("Absolute path to the root directory of the project containing this Fiori application. For EDMXBackend (standalone) projects, this is the same as `appPath`. For CAP projects, this points to the CAP project root, which may contain multiple Fiori applications."),projectType:Fn(["EDMXBackend","CAPJava","CAPNodejs"]).describe("Type of project the application belongs to."),odataVersion:re().describe("OData protocol version used by the application's main service.")}),ox=hn([re(),zt(hn([re(),Mn()]))]),QXe=Ae({functionalityId:ox.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),description:re()}),XXe=Fn(["object","array","string","number","boolean","null","integer","any"]),JXe=Ae({type:hn([XXe,zt(XXe)]).optional(),description:re().optional(),properties:M5().optional()}).catchall(M5()),eJe=JXe.extend({properties:Ei(re(),hn([JXe,Qi()])).optional()});var tJe=Ae({searchPath:zt(re()).describe("Path to search for Fiori applications (defaults to current directory). If VSCode - list of VS Code workspace folder paths(`workspace.workspaceFolders`)")}),rJe=Ae({appPath:re().describe("Path to the root folder of the Fiori application (where package.json and ui5.yaml reside) if one exists or to the current directory. Path should be an absolute path.")}),nJe=Ae({appPath:re().describe("Path to the Fiori application if one exists or to the current directory. Path should be an absolute path."),functionalityId:ox.describe("The ID of the functionality to get details for")}),iJe=Ae({functionalityId:ox.describe("The ID of the functionality to execute"),parameters:Ei(re(),fi()).describe("Parameters for the functionality execution"),appPath:re().describe("Path to the Fiori application if one exists or to the current directory. Path should be an absolute path.")}).describe('Input object for executing a functionality. Only three top-level properties are allowed: "functionalityId", "parameters", and "appPath". All other dynamic or functionality-specific inputs must be included inside the "parameters" object. Do not place any additional fields at the root level.'),xIi=Ae({query:re().min(2).describe("The search query for fiori elements, annotations, sapui5, fiori tools documentation")});var SIi=re().describe("Search results as formatted text"),aJe=Ae({applications:zt(ZXe)}),oJe=Ae({applicationPath:re(),functionalities:zt(QXe)}),sJe=Ae({functionalityId:ox.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),name:re(),description:re(),technicalDescription:re().optional(),parameters:eJe,prerequisites:zt(re()).optional(),impact:re().optional(),examples:zt(re()).optional(),pageName:re().optional()}),cJe=Ae({functionalityId:ox,status:re(),message:re(),parameters:fi(),appPath:re(),changes:zt(re()),timestamp:re()});var Wge=dt(require("node:fs/promises")),vf=dt(require("node:path"));var yf=dt(V0());function UHr(){let e=globalThis.LOG_LEVEL,t=process.env.LOG_LEVEL,r=process.argv.find(i=>i.startsWith("--log-level="))?.split("=")[1],n=e||t||r;if(n)switch(n.toUpperCase()){case"ERROR":return yf.LogLevel.Error;case"WARN":return yf.LogLevel.Warn;case"INFO":return yf.LogLevel.Info;case"DEBUG":return yf.LogLevel.Debug;case"VERBOSE":return yf.LogLevel.Verbose;case"SILLY":return yf.LogLevel.Silly;default:break}return yf.LogLevel.Error}var BHr=UHr(),Nt=new yf.ToolsLogger({logLevel:BHr,transports:[new yf.ConsoleTransport],logPrefix:"fiori-mcp"});async function $ot(){try{let r;try{r=require("@sap-ux/fiori-docs-embeddings")}catch{try{r=await import("@sap-ux/fiori-docs-embeddings")}catch{r=null}}if(!r||typeof r.getDataPath!="function")throw new Error("Package not found or invalid");let n=r.getDataPath();return await Wge.default.access(n),Nt.log("\u2713 Using @sap-ux/fiori-docs-embeddings package"),{dataPath:n,embeddingsPath:vf.default.join(n,"embeddings"),searchPath:vf.default.join(n,"search"),docsPath:vf.default.join(n,"docs"),isExternalPackage:!0,isAvailable:!0}}catch{Nt.warn("Could not load @sap-ux/fiori-docs-embeddings package, trying local data...")}let e=vf.default.join(__dirname,"../../data");try{return await Wge.default.access(e),Nt.log("\u2713 Using local data directory"),{dataPath:e,embeddingsPath:vf.default.join(e,"embeddings"),searchPath:vf.default.join(e,"search"),docsPath:vf.default.join(e,"docs"),isExternalPackage:!1,isAvailable:!0}}catch{Nt.warn("Local data directory not available either")}let t=vf.default.join(__dirname,"../../data");return Nt.warn("\u26A0\uFE0F No embeddings data available - running in limited mode"),{dataPath:t,embeddingsPath:vf.default.join(t,"embeddings"),searchPath:vf.default.join(t,"search"),docsPath:vf.default.join(t,"docs"),isExternalPackage:!1,isAvailable:!1}}var bc=dt(Zd()),wF=require("node:path");async function fu(e){try{e=(0,wF.join)(e);try{let t=await(0,bc.createApplicationAccess)(e);return{root:t.project.root,appId:t.getAppId(),applicationAccess:t}}catch(t){Nt.warn(`Application was not found by given path. Error: ${t}`);let r=await(0,bc.findProjectRoot)(e),n=await(0,bc.getProject)(r);if(n)return{root:n.root,appId:""}}}catch(t){Nt.warn(`Project was not found by given path. Error: ${t}`);return}}var XY=e=>{let t;switch(e){case bc.DirName.View:{t=(0,wF.join)(bc.DirName.Ext,bc.DirName.View);break}case bc.DirName.Fragment:{t=(0,wF.join)(bc.DirName.Ext,bc.DirName.Fragment);break}case bc.DirName.Controller:{t=(0,wF.join)(bc.DirName.Ext,bc.DirName.Controller);break}default:t=e}return t},Cm=(e,t,r=new Set)=>{if(!e||typeof e!="object")return{};if(e.$ref?.startsWith("#/definitions/")){let i=e.$ref,a=i.replace("#/definitions/",""),o=t.definitions?.[a]??null;if(r.has(i))return{...o};if(r.add(i),o){let s={...e};return delete s.$ref,Cm({...o,...s},t,r)}}let n={...e};return n.properties&&(n.properties=Object.fromEntries(Object.entries(n.properties).map(([i,a])=>[i,Cm(a,t,r)]))),n.items&&(Array.isArray(n.items)?n.items=n.items.map(i=>Cm(i,t,r)):n.items=Cm(n.items,t,r)),n.allOf&&(n.allOf=n.allOf.map(i=>Cm(i,t,r))),n.anyOf&&(n.anyOf=n.anyOf.map(i=>Cm(i,t,r))),n.oneOf&&(n.oneOf=n.oneOf.map(i=>Cm(i,t,r))),typeof n.additionalProperties=="object"&&(n.additionalProperties=Cm(n.additionalProperties,t,r)),n},Nxt=(e,t)=>({type:"object",properties:{[e]:t}}),Oa=e=>{let t=GT(e);return delete t.$schema,t},wm=(e,t)=>{try{return e.parse(t)}catch(r){throw r instanceof dpe?new Error(`Missing required fields in parameters. ${JSON.stringify(r.issues,null,4)}`):new Error("Unknown error. Recheck input parameters.")}};var nLt=require("node:util"),iLt=require("node:child_process"),aLt=dt(HCe());async function nX(e="1.18.5"){let t="@sap/generator-fiori";if((await(0,aLt.findInstalledPackages)(t,{minVersion:e}))?.length<1)throw new Error(`Fiori generator not found. Please install the Fiori generator >=${e} with 'npm install -g ${t}' and retry this call`)}var iX=(0,nLt.promisify)(iLt.exec);var oLt=require("@lancedb/lancedb");var GCe=dt(require("fs/promises")),KCe=dt(require("node:path")),aX=class{connection=null;tables=[];tableIndex=null;metadata=null;dataPath;constructor(t){this.dataPath=t||""}async initialize(){try{Nt.log("Loading vector database from pre-built embeddings...");let t=await $ot();if(!t.isAvailable)throw new Error("No embeddings data available");this.dataPath=t.embeddingsPath,Nt.log(`Using embeddings path: ${this.dataPath} (external: ${t.isExternalPackage})`);let r=KCe.default.join(this.dataPath,"metadata.json"),n=await GCe.default.readFile(r,"utf-8");this.metadata=JSON.parse(n),Nt.log("\u2713 Embedding metadata loaded:"),Nt.log(` Model: ${this?.metadata?.model}`),Nt.log(` Dimensions: ${this?.metadata?.dimensions}`),Nt.log(` Total vectors: ${this?.metadata?.totalVectors}`),Nt.log(` Created: ${this?.metadata?.createdAt}`),this.connection=await(0,oLt.connect)(this.dataPath);let i=KCe.default.join(this.dataPath,"table_index.json");try{let a=await GCe.default.readFile(i,"utf-8");this.tableIndex=JSON.parse(a),this.tables=[];for(let o of this.tableIndex?.tables||[]){let s=await this.connection.openTable(o);this.tables.push(s)}Nt.log(`\u2713 Loaded ${this.tables.length} split tables`)}catch{Nt.log("No table index found, trying single table...");try{let a=await this.connection.openTable("documents");this.tables=[a],this.tableIndex={tables:["documents"],totalTables:1,maxVectorsPerTable:-1,totalVectors:this.metadata?.totalVectors||0}}catch(a){throw new Error(`No tables found: ${a}`)}}Nt.log("\u2713 Vector database loaded and ready")}catch(t){throw new Error(`Failed to load vector database: ${t}`)}}async semanticSearch(t,r=10,n){if(this.tables.length===0)throw new Error("Vector database not initialized");try{let i=[];for(let o of this.tables){let s=o.vectorSearch(t).limit(r*2);n&&(s=s.where(`category = "${n}"`));let c=await s.toArray();i.push(...c)}return i.sort((o,s)=>(o._distance||0)-(s._distance||0)),i.slice(0,r).map(o=>({document:{id:o.document_id,vector:o.vector,content:o.content,title:o.title,category:o.category,path:o.path,chunk_index:o.chunk_index,metadata:{tags:this.parseJsonField(o.tags_json)||[],headers:this.parseJsonField(o.headers_json)||[],lastModified:new Date(o.lastModified),wordCount:o.wordCount,excerpt:o.excerpt}},score:1-(o._distance||0),distance:o._distance||0}))}catch(i){throw Nt.error(`Semantic search failed: ${i}`),new Error(`Semantic search failed: ${i}`)}}async findSimilarToText(t,r=5){return Nt.warn("findSimilarToText requires embedding generation - not available in simplified mode"),[]}async findSimilarToDocument(t,r=5){if(this.tables.length===0)throw new Error("Vector database not initialized");try{let n=null;for(let s of this.tables){let c=await s.search("").where(`document_id = "${t}" AND chunk_index = 0`).limit(1).toArray();if(c.length>0){n=c[0].vector;break}}if(!n)return[];let i=[];for(let s of this.tables){let c=await s.vectorSearch(n).where(`document_id != "${t}"`).limit(r*2).toArray();i.push(...c)}let a=new Map;for(let s of i){let c=s.document_id,u=1-(s._distance||0);(!a.has(c)||a.get(c).score<u)&&a.set(c,{...s,score:u,distance:s._distance||0})}return Array.from(a.values()).sort((s,c)=>c.score-s.score).slice(0,r).map(s=>({document:{id:s.document_id,vector:s.vector,content:s.content,title:s.title,category:s.category,path:s.path,chunk_index:s.chunk_index,metadata:{tags:this.parseJsonField(s.tags_json)||[],headers:this.parseJsonField(s.headers_json)||[],lastModified:new Date(s.lastModified),wordCount:s.wordCount,excerpt:s.excerpt}},score:s.score,distance:s.distance}))}catch(n){return Nt.error(`Find similar documents failed: ${n}`),[]}}async getDocumentsByCategory(t,r){if(this.tables.length===0)throw new Error("Vector database not initialized");try{let n=[];for(let a of this.tables){let o=a.search("").where(`category = "${t}" AND chunk_index = 0`);r&&(o=o.limit(Math.ceil(r/this.tables.length)+10));let s=await o.toArray();n.push(...s)}return(r?n.slice(0,r):n).map(a=>({document:{id:a.document_id,vector:a.vector,content:a.content,title:a.title,category:a.category,path:a.path,chunk_index:a.chunk_index,metadata:{tags:this.parseJsonField(a.tags_json)||[],headers:this.parseJsonField(a.headers_json)||[],lastModified:new Date(a.lastModified),wordCount:a.wordCount,excerpt:a.excerpt}},score:1,distance:0}))}catch(n){return Nt.error(`Get documents by category failed: ${n}`),[]}}getMetadata(){return this.metadata}parseJsonField(t){try{return t?JSON.parse(t):[]}catch{return[]}}isInitialized(){return this.tables.length>0&&this.metadata!==null}async close(){this.connection&&(this.connection=null,this.tables=[],Nt.log("Vector database connection closed"))}};var oX=class{pipeline=null;initialized=!1;async initialize(){if(!this.initialized)try{let{pipeline:t}=await import("@xenova/transformers");this.pipeline=await t("feature-extraction","Xenova/all-MiniLM-L6-v2",{quantized:!1}),this.initialized=!0}catch(t){throw new Error(`Failed to initialize text embedding service: ${t}. Make sure @xenova/transformers is available.`)}}async generateEmbedding(t){if(!this.initialized||!this.pipeline)throw new Error("Text embedding service not initialized. Call initialize() first.");try{let r=t.replace(/\n+/g," ").replace(/\s+/g," ").trim().substring(0,8192);if(!r)throw new Error("Empty text provided for embedding");let n=await this.pipeline(r,{pooling:"mean",normalize:!0});return Array.from(n.data)}catch(r){throw new Error(`Failed to generate embedding: ${r}`)}}isInitialized(){return this.initialized}};async function YCe(e,t=!1){let{query:r,maxResults:n}=e;try{let i=new aX,a=new oX;await i.initialize(),await a.initialize();let o=await a.generateEmbedding(r),s=await i.semanticSearch(o,n??10);if(t){let c="";for(let[u,l]of s.entries())c+=`Result ${u+1}:
1654
1654
 
1655
1655
  `,c+=`${l.document.content}
1656
1656
  `,c+=`---
1657
1657
 
1658
- `;return c}else return{query:r,searchType:"hybrid",results:s.map(c=>({title:c.document.title,category:c.document.category,path:c.document.path,score:c.score,matches:[],excerpt:c.document.metadata?.excerpt,content:c.document.content,uri:`sap-fiori://docs/${c.document.category}/${c.document.id}`})),total:s.length}}catch(i){return Nt.warn(`Embeddings data not available, providing limited search capability: ${i}`),{query:r,searchType:"limited_fallback",error:"Embeddings data not available. Please install @sap-ux/fiori-docs-embeddings for full search capabilities.",results:[],total:0,suggestion:"Try running: npm install -g @sap-ux/fiori-docs-embeddings"}}}var sX=dt(Zd()),sLt=require("node:path");async function WCe(e){let{searchPath:t=[]}=e,n=(await(0,sX.findFioriArtifacts)({wsFolders:t,artifacts:["applications"]})).applications??[];return{applications:await Promise.all(n.map(async i=>{let a=await(0,sX.getProjectType)(i.projectRoot);return{name:i.manifest["sap.app"]?.id??(0,sLt.basename)(i.appRoot),appPath:i.appRoot,projectPath:i.projectRoot,projectType:a,odataVersion:i.manifest["sap.app"]?.dataSources?.mainService?.settings?.odataVersion??"4.0"}}))??[]}}var MMt=dt(Pc());var rr=e=>typeof e=="string",qj=()=>{let e,t,r=new Promise((n,i)=>{e=n,t=i});return r.resolve=e,r.reject=t,r},k$t=e=>e==null?"":""+e,_Rn=(e,t,r)=>{e.forEach(n=>{t[n]&&(r[n]=t[n])})},TRn=/###/g,$$t=e=>e&&e.indexOf("###")>-1?e.replace(TRn,"."):e,M$t=e=>!e||rr(e),Uj=(e,t,r)=>{let n=rr(t)?t.split("."):t,i=0;for(;i<n.length-1;){if(M$t(e))return{};let a=$$t(n[i]);!e[a]&&r&&(e[a]=new r),Object.prototype.hasOwnProperty.call(e,a)?e=e[a]:e={},++i}return M$t(e)?{}:{obj:e,k:$$t(n[i])}},F$t=(e,t,r)=>{let{obj:n,k:i}=Uj(e,t,Object);if(n!==void 0||t.length===1){n[i]=r;return}let a=t[t.length-1],o=t.slice(0,t.length-1),s=Uj(e,o,Object);for(;s.obj===void 0&&o.length;)a=`${o[o.length-1]}.${a}`,o=o.slice(0,o.length-1),s=Uj(e,o,Object),s?.obj&&typeof s.obj[`${s.k}.${a}`]<"u"&&(s.obj=void 0);s.obj[`${s.k}.${a}`]=r},xRn=(e,t,r,n)=>{let{obj:i,k:a}=Uj(e,t,Object);i[a]=i[a]||[],i[a].push(r)},_X=(e,t)=>{let{obj:r,k:n}=Uj(e,t);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},ORn=(e,t,r)=>{let n=_X(e,r);return n!==void 0?n:_X(t,r)},K$t=(e,t,r)=>{for(let n in t)n!=="__proto__"&&n!=="constructor"&&(n in e?rr(e[n])||e[n]instanceof String||rr(t[n])||t[n]instanceof String?r&&(e[n]=t[n]):K$t(e[n],t[n],r):e[n]=t[n]);return e},wD=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),SRn={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"},ARn=e=>rr(e)?e.replace(/[&<>"'\/]/g,t=>SRn[t]):e,awe=class{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){let r=this.regExpMap.get(t);if(r!==void 0)return r;let n=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,n),this.regExpQueue.push(t),n}},CRn=[" ",",","?","!",";"],wRn=new awe(20),PRn=(e,t,r)=>{t=t||"",r=r||"";let n=CRn.filter(o=>t.indexOf(o)<0&&r.indexOf(o)<0);if(n.length===0)return!0;let i=wRn.getRegExp(`(${n.map(o=>o==="?"?"\\?":o).join("|")})`),a=!i.test(e);if(!a){let o=e.indexOf(r);o>0&&!i.test(e.substring(0,o))&&(a=!0)}return a},owe=(e,t,r=".")=>{if(!e)return;if(e[t])return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;let n=t.split(r),i=e;for(let a=0;a<n.length;){if(!i||typeof i!="object")return;let o,s="";for(let c=a;c<n.length;++c)if(c!==a&&(s+=r),s+=n[c],o=i[s],o!==void 0){if(["string","number","boolean"].indexOf(typeof o)>-1&&c<n.length-1)continue;a+=c-a+1;break}i=o}return i},Bj=e=>e?.replace("_","-"),DRn={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console?.[e]?.apply?.(console,t)}},swe=class e{constructor(t,r={}){this.init(t,r)}init(t,r={}){this.prefix=r.prefix||"i18next:",this.logger=t||DRn,this.options=r,this.debug=r.debug}log(...t){return this.forward(t,"log","",!0)}warn(...t){return this.forward(t,"warn","",!0)}error(...t){return this.forward(t,"error","")}deprecate(...t){return this.forward(t,"warn","WARNING DEPRECATED: ",!0)}forward(t,r,n,i){return i&&!this.debug?null:(rr(t[0])&&(t[0]=`${n}${this.prefix} ${t[0]}`),this.logger[r](t))}create(t){return new e(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return t=t||this.options,t.prefix=t.prefix||this.prefix,new e(this.logger,t)}},Wm=new swe,PD=class{constructor(){this.observers={}}on(t,r){return t.split(" ").forEach(n=>{this.observers[n]||(this.observers[n]=new Map);let i=this.observers[n].get(r)||0;this.observers[n].set(r,i+1)}),this}off(t,r){if(this.observers[t]){if(!r){delete this.observers[t];return}this.observers[t].delete(r)}}emit(t,...r){this.observers[t]&&Array.from(this.observers[t].entries()).forEach(([i,a])=>{for(let o=0;o<a;o++)i(...r)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([i,a])=>{for(let o=0;o<a;o++)i.apply(i,[t,...r])})}},TX=class extends PD{constructor(t,r={ns:["translation"],defaultNS:"translation"}){super(),this.data=t||{},this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){let r=this.options.ns.indexOf(t);r>-1&&this.options.ns.splice(r,1)}getResource(t,r,n,i={}){let a=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,o=i.ignoreJSONStructure!==void 0?i.ignoreJSONStructure:this.options.ignoreJSONStructure,s;t.indexOf(".")>-1?s=t.split("."):(s=[t,r],n&&(Array.isArray(n)?s.push(...n):rr(n)&&a?s.push(...n.split(a)):s.push(n)));let c=_X(this.data,s);return!c&&!r&&!n&&t.indexOf(".")>-1&&(t=s[0],r=s[1],n=s.slice(2).join(".")),c||!o||!rr(n)?c:owe(this.data?.[t]?.[r],n,a)}addResource(t,r,n,i,a={silent:!1}){let o=a.keySeparator!==void 0?a.keySeparator:this.options.keySeparator,s=[t,r];n&&(s=s.concat(o?n.split(o):n)),t.indexOf(".")>-1&&(s=t.split("."),i=r,r=s[1]),this.addNamespaces(r),F$t(this.data,s,i),a.silent||this.emit("added",t,r,n,i)}addResources(t,r,n,i={silent:!1}){for(let a in n)(rr(n[a])||Array.isArray(n[a]))&&this.addResource(t,r,a,n[a],{silent:!0});i.silent||this.emit("added",t,r,n)}addResourceBundle(t,r,n,i,a,o={silent:!1,skipCopy:!1}){let s=[t,r];t.indexOf(".")>-1&&(s=t.split("."),i=n,n=r,r=s[1]),this.addNamespaces(r);let c=_X(this.data,s)||{};o.skipCopy||(n=JSON.parse(JSON.stringify(n))),i?K$t(c,n,a):c={...c,...n},F$t(this.data,s,c),o.silent||this.emit("added",t,r,n)}removeResourceBundle(t,r){this.hasResourceBundle(t,r)&&delete this.data[t][r],this.removeNamespaces(r),this.emit("removed",t,r)}hasResourceBundle(t,r){return this.getResource(t,r)!==void 0}getResourceBundle(t,r){return r||(r=this.options.defaultNS),this.getResource(t,r)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){let r=this.getDataByLanguage(t);return!!(r&&Object.keys(r)||[]).find(i=>r[i]&&Object.keys(r[i]).length>0)}toJSON(){return this.data}},Y$t={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,r,n,i){return e.forEach(a=>{t=this.processors[a]?.process(t,r,n,i)??t}),t}},j$t={},V$t=e=>!rr(e)&&typeof e!="boolean"&&typeof e!="number",xX=class e extends PD{constructor(t,r={}){super(),_Rn(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Wm.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t,r={interpolation:{}}){let n={...r};return t==null?!1:this.resolve(t,n)?.res!==void 0}extractFromKey(t,r){let n=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;n===void 0&&(n=":");let i=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator,a=r.ns||this.options.defaultNS||[],o=n&&t.indexOf(n)>-1,s=!this.options.userDefinedKeySeparator&&!r.keySeparator&&!this.options.userDefinedNsSeparator&&!r.nsSeparator&&!PRn(t,n,i);if(o&&!s){let c=t.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:t,namespaces:rr(a)?[a]:a};let u=t.split(n);(n!==i||n===i&&this.options.ns.indexOf(u[0])>-1)&&(a=u.shift()),t=u.join(i)}return{key:t,namespaces:rr(a)?[a]:a}}translate(t,r,n){let i=typeof r=="object"?{...r}:r;if(typeof i!="object"&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof options=="object"&&(i={...i}),i||(i={}),t==null)return"";Array.isArray(t)||(t=[String(t)]);let a=i.returnDetails!==void 0?i.returnDetails:this.options.returnDetails,o=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,{key:s,namespaces:c}=this.extractFromKey(t[t.length-1],i),u=c[c.length-1],l=i.nsSeparator!==void 0?i.nsSeparator:this.options.nsSeparator;l===void 0&&(l=":");let p=i.lng||this.language,f=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(p?.toLowerCase()==="cimode")return f?a?{res:`${u}${l}${s}`,usedKey:s,exactUsedKey:s,usedLng:p,usedNS:u,usedParams:this.getUsedParamsDetails(i)}:`${u}${l}${s}`:a?{res:s,usedKey:s,exactUsedKey:s,usedLng:p,usedNS:u,usedParams:this.getUsedParamsDetails(i)}:s;let d=this.resolve(t,i),h=d?.res,m=d?.usedKey||s,v=d?.exactUsedKey||s,_=["[object Number]","[object Function]","[object RegExp]"],O=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,x=!this.i18nFormat||this.i18nFormat.handleAsObject,S=i.count!==void 0&&!rr(i.count),A=e.hasDefaultValue(i),P=S?this.pluralResolver.getSuffix(p,i.count,i):"",k=i.ordinal&&S?this.pluralResolver.getSuffix(p,i.count,{ordinal:!1}):"",D=S&&!i.ordinal&&i.count===0,F=D&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${P}`]||i[`defaultValue${k}`]||i.defaultValue,K=h;x&&!h&&A&&(K=F);let $=V$t(K),H=Object.prototype.toString.apply(K);if(x&&K&&$&&_.indexOf(H)<0&&!(rr(O)&&Array.isArray(K))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");let Q=this.options.returnedObjectHandler?this.options.returnedObjectHandler(m,K,{...i,ns:c}):`key '${s} (${this.language})' returned an object instead of string.`;return a?(d.res=Q,d.usedParams=this.getUsedParamsDetails(i),d):Q}if(o){let Q=Array.isArray(K),ee=Q?[]:{},z=Q?v:m;for(let q in K)if(Object.prototype.hasOwnProperty.call(K,q)){let Y=`${z}${o}${q}`;A&&!h?ee[q]=this.translate(Y,{...i,defaultValue:V$t(F)?F[q]:void 0,joinArrays:!1,ns:c}):ee[q]=this.translate(Y,{...i,joinArrays:!1,ns:c}),ee[q]===Y&&(ee[q]=K[q])}h=ee}}else if(x&&rr(O)&&Array.isArray(h))h=h.join(O),h&&(h=this.extendTranslation(h,t,i,n));else{let Q=!1,ee=!1;!this.isValidLookup(h)&&A&&(Q=!0,h=F),this.isValidLookup(h)||(ee=!0,h=s);let q=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&ee?void 0:h,Y=A&&F!==h&&this.options.updateMissing;if(ee||Q||Y){if(this.logger.log(Y?"updateKey":"missingKey",p,u,s,Y?F:h),o){let de=this.resolve(s,{...i,keySeparator:!1});de&&de.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let X=[],me=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&me&&me[0])for(let de=0;de<me.length;de++)X.push(me[de]);else this.options.saveMissingTo==="all"?X=this.languageUtils.toResolveHierarchy(i.lng||this.language):X.push(i.lng||this.language);let ke=(de,Ge,mt)=>{let St=A&&mt!==h?mt:q;this.options.missingKeyHandler?this.options.missingKeyHandler(de,u,Ge,St,Y,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(de,u,Ge,St,Y,i),this.emit("missingKey",de,u,Ge,h)};this.options.saveMissing&&(this.options.saveMissingPlurals&&S?X.forEach(de=>{let Ge=this.pluralResolver.getSuffixes(de,i);D&&i[`defaultValue${this.options.pluralSeparator}zero`]&&Ge.indexOf(`${this.options.pluralSeparator}zero`)<0&&Ge.push(`${this.options.pluralSeparator}zero`),Ge.forEach(mt=>{ke([de],s+mt,i[`defaultValue${mt}`]||F)})}):ke(X,s,F))}h=this.extendTranslation(h,t,i,d,n),ee&&h===s&&this.options.appendNamespaceToMissingKey&&(h=`${u}${l}${s}`),(ee||Q)&&this.options.parseMissingKeyHandler&&(h=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${u}${l}${s}`:s,Q?h:void 0,i))}return a?(d.res=h,d.usedParams=this.getUsedParamsDetails(i),d):h}extendTranslation(t,r,n,i,a){if(this.i18nFormat?.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});let c=rr(t)&&(n?.interpolation?.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables),u;if(c){let p=t.match(this.interpolator.nestingRegexp);u=p&&p.length}let l=n.replace&&!rr(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(l={...this.options.interpolation.defaultVariables,...l}),t=this.interpolator.interpolate(t,l,n.lng||this.language||i.usedLng,n),c){let p=t.match(this.interpolator.nestingRegexp),f=p&&p.length;u<f&&(n.nest=!1)}!n.lng&&i&&i.res&&(n.lng=this.language||i.usedLng),n.nest!==!1&&(t=this.interpolator.nest(t,(...p)=>a?.[0]===p[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${p[0]} in key: ${r[0]}`),null):this.translate(...p,r),n)),n.interpolation&&this.interpolator.reset()}let o=n.postProcess||this.options.postProcess,s=rr(o)?[o]:o;return t!=null&&s?.length&&n.applyPostProcessor!==!1&&(t=Y$t.handle(s,t,r,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),t}resolve(t,r={}){let n,i,a,o,s;return rr(t)&&(t=[t]),t.forEach(c=>{if(this.isValidLookup(n))return;let u=this.extractFromKey(c,r),l=u.key;i=l;let p=u.namespaces;this.options.fallbackNS&&(p=p.concat(this.options.fallbackNS));let f=r.count!==void 0&&!rr(r.count),d=f&&!r.ordinal&&r.count===0,h=r.context!==void 0&&(rr(r.context)||typeof r.context=="number")&&r.context!=="",m=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);p.forEach(v=>{this.isValidLookup(n)||(s=v,!j$t[`${m[0]}-${v}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(s)&&(j$t[`${m[0]}-${v}`]=!0,this.logger.warn(`key "${i}" for languages "${m.join(", ")}" won't get resolved as namespace "${s}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),m.forEach(_=>{if(this.isValidLookup(n))return;o=_;let O=[l];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(O,l,_,v,r);else{let S;f&&(S=this.pluralResolver.getSuffix(_,r.count,r));let A=`${this.options.pluralSeparator}zero`,P=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(O.push(l+S),r.ordinal&&S.indexOf(P)===0&&O.push(l+S.replace(P,this.options.pluralSeparator)),d&&O.push(l+A)),h){let k=`${l}${this.options.contextSeparator}${r.context}`;O.push(k),f&&(O.push(k+S),r.ordinal&&S.indexOf(P)===0&&O.push(k+S.replace(P,this.options.pluralSeparator)),d&&O.push(k+A))}}let x;for(;x=O.pop();)this.isValidLookup(n)||(a=x,n=this.getResource(_,v,x,r))}))})}),{res:n,usedKey:i,exactUsedKey:a,usedLng:o,usedNS:s}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,r,n,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(t,r,n,i):this.resourceStore.getResource(t,r,n,i)}getUsedParamsDetails(t={}){let r=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=t.replace&&!rr(t.replace),i=n?t.replace:t;if(n&&typeof t.count<"u"&&(i.count=t.count),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!n){i={...i};for(let a of r)delete i[a]}return i}static hasDefaultValue(t){let r="defaultValue";for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&r===n.substring(0,r.length)&&t[n]!==void 0)return!0;return!1}},OX=class{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Wm.create("languageUtils")}getScriptPartFromCode(t){if(t=Bj(t),!t||t.indexOf("-")<0)return null;let r=t.split("-");return r.length===2||(r.pop(),r[r.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(r.join("-"))}getLanguagePartFromCode(t){if(t=Bj(t),!t||t.indexOf("-")<0)return t;let r=t.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(t){if(rr(t)&&t.indexOf("-")>-1){let r;try{r=Intl.getCanonicalLocales(t)[0]}catch{}return r&&this.options.lowerCaseLng&&(r=r.toLowerCase()),r||(this.options.lowerCaseLng?t.toLowerCase():t)}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let r;return t.forEach(n=>{if(r)return;let i=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(i))&&(r=i)}),!r&&this.options.supportedLngs&&t.forEach(n=>{if(r)return;let i=this.getScriptPartFromCode(n);if(this.isSupportedCode(i))return r=i;let a=this.getLanguagePartFromCode(n);if(this.isSupportedCode(a))return r=a;r=this.options.supportedLngs.find(o=>{if(o===a)return o;if(!(o.indexOf("-")<0&&a.indexOf("-")<0)&&(o.indexOf("-")>0&&a.indexOf("-")<0&&o.substring(0,o.indexOf("-"))===a||o.indexOf(a)===0&&a.length>1))return o})}),r||(r=this.getFallbackCodes(this.options.fallbackLng)[0]),r}getFallbackCodes(t,r){if(!t)return[];if(typeof t=="function"&&(t=t(r)),rr(t)&&(t=[t]),Array.isArray(t))return t;if(!r)return t.default||[];let n=t[r];return n||(n=t[this.getScriptPartFromCode(r)]),n||(n=t[this.formatLanguageCode(r)]),n||(n=t[this.getLanguagePartFromCode(r)]),n||(n=t.default),n||[]}toResolveHierarchy(t,r){let n=this.getFallbackCodes((r===!1?[]:r)||this.options.fallbackLng||[],t),i=[],a=o=>{o&&(this.isSupportedCode(o)?i.push(o):this.logger.warn(`rejecting language code not found in supportedLngs: ${o}`))};return rr(t)&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&a(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&a(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&a(this.getLanguagePartFromCode(t))):rr(t)&&a(this.formatLanguageCode(t)),n.forEach(o=>{i.indexOf(o)<0&&a(this.formatLanguageCode(o))}),i}},q$t={zero:0,one:1,two:2,few:3,many:4,other:5},U$t={select:e=>e===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})},cwe=class{constructor(t,r={}){this.languageUtils=t,this.options=r,this.logger=Wm.create("pluralResolver"),this.pluralRulesCache={}}addRule(t,r){this.rules[t]=r}clearCache(){this.pluralRulesCache={}}getRule(t,r={}){let n=Bj(t==="dev"?"en":t),i=r.ordinal?"ordinal":"cardinal",a=JSON.stringify({cleanedCode:n,type:i});if(a in this.pluralRulesCache)return this.pluralRulesCache[a];let o;try{o=new Intl.PluralRules(n,{type:i})}catch{if(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),U$t;if(!t.match(/-|_/))return U$t;let c=this.languageUtils.getLanguagePartFromCode(t);o=this.getRule(c,r)}return this.pluralRulesCache[a]=o,o}needsPlural(t,r={}){let n=this.getRule(t,r);return n||(n=this.getRule("dev",r)),n?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(t,r,n={}){return this.getSuffixes(t,n).map(i=>`${r}${i}`)}getSuffixes(t,r={}){let n=this.getRule(t,r);return n||(n=this.getRule("dev",r)),n?n.resolvedOptions().pluralCategories.sort((i,a)=>q$t[i]-q$t[a]).map(i=>`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(t,r,n={}){let i=this.getRule(t,n);return i?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i.select(r)}`:(this.logger.warn(`no plural rule found for: ${t}`),this.getSuffix("dev",r,n))}},B$t=(e,t,r,n=".",i=!0)=>{let a=ORn(e,t,r);return!a&&i&&rr(r)&&(a=owe(e,r,n),a===void 0&&(a=owe(t,r,n))),a},iwe=e=>e.replace(/\$/g,"$$$$"),uwe=class{constructor(t={}){this.logger=Wm.create("interpolator"),this.options=t,this.format=t?.interpolation?.format||(r=>r),this.init(t)}init(t={}){t.interpolation||(t.interpolation={escapeValue:!0});let{escape:r,escapeValue:n,useRawValueToEscape:i,prefix:a,prefixEscaped:o,suffix:s,suffixEscaped:c,formatSeparator:u,unescapeSuffix:l,unescapePrefix:p,nestingPrefix:f,nestingPrefixEscaped:d,nestingSuffix:h,nestingSuffixEscaped:m,nestingOptionsSeparator:v,maxReplaces:_,alwaysFormat:O}=t.interpolation;this.escape=r!==void 0?r:ARn,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=a?wD(a):o||"{{",this.suffix=s?wD(s):c||"}}",this.formatSeparator=u||",",this.unescapePrefix=l?"":p||"-",this.unescapeSuffix=this.unescapePrefix?"":l||"",this.nestingPrefix=f?wD(f):d||wD("$t("),this.nestingSuffix=h?wD(h):m||wD(")"),this.nestingOptionsSeparator=v||",",this.maxReplaces=_||1e3,this.alwaysFormat=O!==void 0?O:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){let t=(r,n)=>r?.source===n?(r.lastIndex=0,r):new RegExp(n,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}(.+?)${this.nestingSuffix}`)}interpolate(t,r,n,i){let a,o,s,c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},u=d=>{if(d.indexOf(this.formatSeparator)<0){let _=B$t(r,c,d,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(_,void 0,n,{...i,...r,interpolationkey:d}):_}let h=d.split(this.formatSeparator),m=h.shift().trim(),v=h.join(this.formatSeparator).trim();return this.format(B$t(r,c,m,this.options.keySeparator,this.options.ignoreJSONStructure),v,n,{...i,...r,interpolationkey:m})};this.resetRegExp();let l=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,p=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:d=>iwe(d)},{regex:this.regexp,safeValue:d=>this.escapeValue?iwe(this.escape(d)):iwe(d)}].forEach(d=>{for(s=0;a=d.regex.exec(t);){let h=a[1].trim();if(o=u(h),o===void 0)if(typeof l=="function"){let v=l(t,a,i);o=rr(v)?v:""}else if(i&&Object.prototype.hasOwnProperty.call(i,h))o="";else if(p){o=a[0];continue}else this.logger.warn(`missed to pass in variable ${h} for interpolating ${t}`),o="";else!rr(o)&&!this.useRawValueToEscape&&(o=k$t(o));let m=d.safeValue(o);if(t=t.replace(a[0],m),p?(d.regex.lastIndex+=o.length,d.regex.lastIndex-=a[0].length):d.regex.lastIndex=0,s++,s>=this.maxReplaces)break}}),t}nest(t,r,n={}){let i,a,o,s=(c,u)=>{let l=this.nestingOptionsSeparator;if(c.indexOf(l)<0)return c;let p=c.split(new RegExp(`${l}[ ]*{`)),f=`{${p[1]}`;c=p[0],f=this.interpolate(f,o);let d=f.match(/'/g),h=f.match(/"/g);((d?.length??0)%2===0&&!h||h.length%2!==0)&&(f=f.replace(/'/g,'"'));try{o=JSON.parse(f),u&&(o={...u,...o})}catch(m){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,m),`${c}${l}${f}`}return o.defaultValue&&o.defaultValue.indexOf(this.prefix)>-1&&delete o.defaultValue,c};for(;i=this.nestingRegexp.exec(t);){let c=[];o={...n},o=o.replace&&!rr(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;let u=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(u!==-1&&(c=i[1].slice(u).split(this.formatSeparator).map(l=>l.trim()).filter(Boolean),i[1]=i[1].slice(0,u)),a=r(s.call(this,i[1].trim(),o),o),a&&i[0]===t&&!rr(a))return a;rr(a)||(a=k$t(a)),a||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${t}`),a=""),c.length&&(a=c.reduce((l,p)=>this.format(l,p,n.lng,{...n,interpolationkey:i[1].trim()}),a.trim())),t=t.replace(i[0],a),this.regexp.lastIndex=0}return t}},NRn=e=>{let t=e.toLowerCase().trim(),r={};if(e.indexOf("(")>-1){let n=e.split("(");t=n[0].toLowerCase().trim();let i=n[1].substring(0,n[1].length-1);t==="currency"&&i.indexOf(":")<0?r.currency||(r.currency=i.trim()):t==="relativetime"&&i.indexOf(":")<0?r.range||(r.range=i.trim()):i.split(";").forEach(o=>{if(o){let[s,...c]=o.split(":"),u=c.join(":").trim().replace(/^'+|'+$/g,""),l=s.trim();r[l]||(r[l]=u),u==="false"&&(r[l]=!1),u==="true"&&(r[l]=!0),isNaN(u)||(r[l]=parseInt(u,10))}})}return{formatName:t,formatOptions:r}},z$t=e=>{let t={};return(r,n,i)=>{let a=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(a={...a,[i.interpolationkey]:void 0});let o=n+JSON.stringify(a),s=t[o];return s||(s=e(Bj(n),i),t[o]=s),s(r)}},IRn=e=>(t,r,n)=>e(Bj(r),n)(t),lwe=class{constructor(t={}){this.logger=Wm.create("formatter"),this.options=t,this.init(t)}init(t,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";let n=r.cacheInBuiltFormats?z$t:IRn;this.formats={number:n((i,a)=>{let o=new Intl.NumberFormat(i,{...a});return s=>o.format(s)}),currency:n((i,a)=>{let o=new Intl.NumberFormat(i,{...a,style:"currency"});return s=>o.format(s)}),datetime:n((i,a)=>{let o=new Intl.DateTimeFormat(i,{...a});return s=>o.format(s)}),relativetime:n((i,a)=>{let o=new Intl.RelativeTimeFormat(i,{...a});return s=>o.format(s,a.range||"day")}),list:n((i,a)=>{let o=new Intl.ListFormat(i,{...a});return s=>o.format(s)})}}add(t,r){this.formats[t.toLowerCase().trim()]=r}addCached(t,r){this.formats[t.toLowerCase().trim()]=z$t(r)}format(t,r,n,i={}){let a=r.split(this.formatSeparator);if(a.length>1&&a[0].indexOf("(")>1&&a[0].indexOf(")")<0&&a.find(s=>s.indexOf(")")>-1)){let s=a.findIndex(c=>c.indexOf(")")>-1);a[0]=[a[0],...a.splice(1,s)].join(this.formatSeparator)}return a.reduce((s,c)=>{let{formatName:u,formatOptions:l}=NRn(c);if(this.formats[u]){let p=s;try{let f=i?.formatParams?.[i.interpolationkey]||{},d=f.locale||f.lng||i.locale||i.lng||n;p=this.formats[u](s,d,{...l,...i,...f})}catch(f){this.logger.warn(f)}return p}else this.logger.warn(`there was no format function for ${u}`);return s},t)}},RRn=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)},pwe=class extends PD{constructor(t,r,n,i={}){super(),this.backend=t,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=i,this.logger=Wm.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(n,i.backend,i)}queueLoad(t,r,n,i){let a={},o={},s={},c={};return t.forEach(u=>{let l=!0;r.forEach(p=>{let f=`${u}|${p}`;!n.reload&&this.store.hasResourceBundle(u,p)?this.state[f]=2:this.state[f]<0||(this.state[f]===1?o[f]===void 0&&(o[f]=!0):(this.state[f]=1,l=!1,o[f]===void 0&&(o[f]=!0),a[f]===void 0&&(a[f]=!0),c[p]===void 0&&(c[p]=!0)))}),l||(s[u]=!0)}),(Object.keys(a).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(a),pending:Object.keys(o),toLoadLanguages:Object.keys(s),toLoadNamespaces:Object.keys(c)}}loaded(t,r,n){let i=t.split("|"),a=i[0],o=i[1];r&&this.emit("failedLoading",a,o,r),!r&&n&&this.store.addResourceBundle(a,o,n,void 0,void 0,{skipCopy:!0}),this.state[t]=r?-1:2,r&&n&&(this.state[t]=0);let s={};this.queue.forEach(c=>{xRn(c.loaded,[a],o),RRn(c,t),r&&c.errors.push(r),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(u=>{s[u]||(s[u]={});let l=c.loaded[u];l.length&&l.forEach(p=>{s[u][p]===void 0&&(s[u][p]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",s),this.queue=this.queue.filter(c=>!c.done)}read(t,r,n,i=0,a=this.retryTimeout,o){if(!t.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:r,fcName:n,tried:i,wait:a,callback:o});return}this.readingCalls++;let s=(u,l)=>{if(this.readingCalls--,this.waitingReads.length>0){let p=this.waitingReads.shift();this.read(p.lng,p.ns,p.fcName,p.tried,p.wait,p.callback)}if(u&&l&&i<this.maxRetries){setTimeout(()=>{this.read.call(this,t,r,n,i+1,a*2,o)},a);return}o(u,l)},c=this.backend[n].bind(this.backend);if(c.length===2){try{let u=c(t,r);u&&typeof u.then=="function"?u.then(l=>s(null,l)).catch(s):s(null,u)}catch(u){s(u)}return}return c(t,r,s)}prepareLoading(t,r,n={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();rr(t)&&(t=this.languageUtils.toResolveHierarchy(t)),rr(r)&&(r=[r]);let a=this.queueLoad(t,r,n,i);if(!a.toLoad.length)return a.pending.length||i(),null;a.toLoad.forEach(o=>{this.loadOne(o)})}load(t,r,n){this.prepareLoading(t,r,{},n)}reload(t,r,n){this.prepareLoading(t,r,{reload:!0},n)}loadOne(t,r=""){let n=t.split("|"),i=n[0],a=n[1];this.read(i,a,"read",void 0,void 0,(o,s)=>{o&&this.logger.warn(`${r}loading namespace ${a} for language ${i} failed`,o),!o&&s&&this.logger.log(`${r}loaded namespace ${a} for language ${i}`,s),this.loaded(t,o,s)})}saveMissing(t,r,n,i,a,o={},s=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(r)){this.logger.warn(`did not save key "${n}" as the namespace "${r}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(n==null||n==="")){if(this.backend?.create){let c={...o,isUpdate:a},u=this.backend.create.bind(this.backend);if(u.length<6)try{let l;u.length===5?l=u(t,r,n,i,c):l=u(t,r,n,i),l&&typeof l.then=="function"?l.then(p=>s(null,p)).catch(s):s(null,l)}catch(l){s(l)}else u(t,r,n,i,s,c)}!t||!t[0]||this.store.addResource(t[0],r,n,i)}}},H$t=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),rr(e[1])&&(t.defaultValue=e[1]),rr(e[2])&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){let r=e[3]||e[2];Object.keys(r).forEach(n=>{t[n]=r[n]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),G$t=e=>(rr(e.ns)&&(e.ns=[e.ns]),rr(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),rr(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs?.indexOf?.("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),typeof e.initImmediate=="boolean"&&(e.initAsync=e.initImmediate),e),EX=()=>{},LRn=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(r=>{typeof e[r]=="function"&&(e[r]=e[r].bind(e))})},SX=class e extends PD{constructor(t={},r){if(super(),this.options=G$t(t),this.services={},this.logger=Wm,this.modules={external:[]},LRn(this),r&&!this.isInitialized&&!t.isClone){if(!this.options.initAsync)return this.init(t,r),this;setTimeout(()=>{this.init(t,r)},0)}}init(t={},r){this.isInitializing=!0,typeof t=="function"&&(r=t,t={}),t.defaultNS==null&&t.ns&&(rr(t.ns)?t.defaultNS=t.ns:t.ns.indexOf("translation")<0&&(t.defaultNS=t.ns[0]));let n=H$t();this.options={...n,...this.options,...G$t(t)},this.options.interpolation={...n.interpolation,...this.options.interpolation},t.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=t.keySeparator),t.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=t.nsSeparator);let i=u=>u?typeof u=="function"?new u:u:null;if(!this.options.isClone){this.modules.logger?Wm.init(i(this.modules.logger),this.options):Wm.init(null,this.options);let u;this.modules.formatter?u=this.modules.formatter:u=lwe;let l=new OX(this.options);this.store=new TX(this.options.resources,this.options);let p=this.services;p.logger=Wm,p.resourceStore=this.store,p.languageUtils=l,p.pluralResolver=new cwe(l,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),u&&(!this.options.interpolation.format||this.options.interpolation.format===n.interpolation.format)&&(p.formatter=i(u),p.formatter.init(p,this.options),this.options.interpolation.format=p.formatter.format.bind(p.formatter)),p.interpolator=new uwe(this.options),p.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},p.backendConnector=new pwe(i(this.modules.backend),p.resourceStore,p,this.options),p.backendConnector.on("*",(f,...d)=>{this.emit(f,...d)}),this.modules.languageDetector&&(p.languageDetector=i(this.modules.languageDetector),p.languageDetector.init&&p.languageDetector.init(p,this.options.detection,this.options)),this.modules.i18nFormat&&(p.i18nFormat=i(this.modules.i18nFormat),p.i18nFormat.init&&p.i18nFormat.init(this)),this.translator=new xX(this.services,this.options),this.translator.on("*",(f,...d)=>{this.emit(f,...d)}),this.modules.external.forEach(f=>{f.init&&f.init(this)})}if(this.format=this.options.interpolation.format,r||(r=EX),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){let u=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);u.length>0&&u[0]!=="dev"&&(this.options.lng=u[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(u=>{this[u]=(...l)=>this.store[u](...l)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(u=>{this[u]=(...l)=>(this.store[u](...l),this)});let s=qj(),c=()=>{let u=(l,p)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),s.resolve(p),r(l,p)};if(this.languages&&!this.isInitialized)return u(null,this.t.bind(this));this.changeLanguage(this.options.lng,u)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),s}loadResources(t,r=EX){let n=r,i=rr(t)?t:this.language;if(typeof t=="function"&&(n=t),!this.options.resources||this.options.partialBundledLanguages){if(i?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();let a=[],o=s=>{if(!s||s==="cimode")return;this.services.languageUtils.toResolveHierarchy(s).forEach(u=>{u!=="cimode"&&a.indexOf(u)<0&&a.push(u)})};i?o(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>o(c)),this.options.preload?.forEach?.(s=>o(s)),this.services.backendConnector.load(a,this.options.ns,s=>{!s&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(s)})}else n(null)}reloadResources(t,r,n){let i=qj();return typeof t=="function"&&(n=t,t=void 0),typeof r=="function"&&(n=r,r=void 0),t||(t=this.languages),r||(r=this.options.ns),n||(n=EX),this.services.backendConnector.reload(t,r,a=>{i.resolve(),n(a)}),i}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&Y$t.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-1)){for(let r=0;r<this.languages.length;r++){let n=this.languages[r];if(!(["cimode","dev"].indexOf(n)>-1)&&this.store.hasLanguageSomeTranslations(n)){this.resolvedLanguage=n;break}}!this.resolvedLanguage&&this.languages.indexOf(t)<0&&this.store.hasLanguageSomeTranslations(t)&&(this.resolvedLanguage=t,this.languages.unshift(t))}}changeLanguage(t,r){this.isLanguageChangingTo=t;let n=qj();this.emit("languageChanging",t);let i=s=>{this.language=s,this.languages=this.services.languageUtils.toResolveHierarchy(s),this.resolvedLanguage=void 0,this.setResolvedLanguage(s)},a=(s,c)=>{c?this.isLanguageChangingTo===t&&(i(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,n.resolve((...u)=>this.t(...u)),r&&r(s,(...u)=>this.t(...u))},o=s=>{!t&&!s&&this.services.languageDetector&&(s=[]);let c=rr(s)?s:s&&s[0],u=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(rr(s)?[s]:s);u&&(this.language||i(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector?.cacheUserLanguage?.(u)),this.loadResources(u,l=>{a(l,u)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?o(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(t),n}getFixedT(t,r,n){let i=(a,o,...s)=>{let c;typeof o!="object"?c=this.options.overloadTranslationOptionHandler([a,o].concat(s)):c={...o},c.lng=c.lng||i.lng,c.lngs=c.lngs||i.lngs,c.ns=c.ns||i.ns,c.keyPrefix!==""&&(c.keyPrefix=c.keyPrefix||n||i.keyPrefix);let u=this.options.keySeparator||".",l;return c.keyPrefix&&Array.isArray(a)?l=a.map(p=>`${c.keyPrefix}${u}${p}`):l=c.keyPrefix?`${c.keyPrefix}${u}${a}`:a,this.t(l,c)};return rr(t)?i.lng=t:i.lngs=t,i.ns=r,i.keyPrefix=n,i}t(...t){return this.translator?.translate(...t)}exists(...t){return this.translator?.exists(...t)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t,r={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;let n=r.lng||this.resolvedLanguage||this.languages[0],i=this.options?this.options.fallbackLng:!1,a=this.languages[this.languages.length-1];if(n.toLowerCase()==="cimode")return!0;let o=(s,c)=>{let u=this.services.backendConnector.state[`${s}|${c}`];return u===-1||u===0||u===2};if(r.precheck){let s=r.precheck(this,o);if(s!==void 0)return s}return!!(this.hasResourceBundle(n,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(n,t)&&(!i||o(a,t)))}loadNamespaces(t,r){let n=qj();return this.options.ns?(rr(t)&&(t=[t]),t.forEach(i=>{this.options.ns.indexOf(i)<0&&this.options.ns.push(i)}),this.loadResources(i=>{n.resolve(),r&&r(i)}),n):(r&&r(),Promise.resolve())}loadLanguages(t,r){let n=qj();rr(t)&&(t=[t]);let i=this.options.preload||[],a=t.filter(o=>i.indexOf(o)<0&&this.services.languageUtils.isSupportedCode(o));return a.length?(this.options.preload=i.concat(a),this.loadResources(o=>{n.resolve(),r&&r(o)}),n):(r&&r(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!t)return"rtl";if(Intl.Locale){let i=new Intl.Locale(t);if(i&&i.getTextInfo){let a=i.getTextInfo();if(a&&a.direction)return a.direction}}let r=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],n=this.services?.languageUtils||new OX(H$t());return t.toLowerCase().indexOf("-latn")>1?"ltr":r.indexOf(n.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(t={},r){return new e(t,r)}cloneInstance(t={},r=EX){let n=t.forkResourceStore;n&&delete t.forkResourceStore;let i={...this.options,...t,isClone:!0},a=new e(i);if((t.debug!==void 0||t.prefix!==void 0)&&(a.logger=a.logger.clone(t)),["store","services","language"].forEach(s=>{a[s]=this[s]}),a.services={...this.services},a.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},n){let s=Object.keys(this.store.data).reduce((c,u)=>(c[u]={...this.store.data[u]},c[u]=Object.keys(c[u]).reduce((l,p)=>(l[p]={...c[u][p]},l),c[u]),c),{});a.store=new TX(s,i),a.services.resourceStore=a.store}return a.translator=new xX(a.services,i),a.translator.on("*",(s,...c)=>{a.emit(s,...c)}),a.init(i,r),a.translator.options=i,a.translator.backendConnector.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},a}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}},vt=SX.createInstance();vt.createInstance=SX.createInstance;var U5i=vt.createInstance,B5i=vt.dir,z5i=vt.init,H5i=vt.loadResources,G5i=vt.reloadResources,K5i=vt.use,Y5i=vt.changeLanguage,W5i=vt.getFixedT,X5i=vt.t,J5i=vt.exists,Z5i=vt.setDefaultNamespace,Q5i=vt.hasLoadedNamespace,ezi=vt.loadNamespaces,tzi=vt.loadLanguages;var zj=dt(Pc());var W$t="genericActions";var AX="DataFieldForAction",CX="DataFieldForIntentBasedNavigation",X$t="DataFieldForActionGroup",fwe="::",Hj="customView(";var dwe=new Map([[zj.v2.TableTypeV2.ResponsiveTable,"ResponsiveTableColumnsExtension"],[zj.v2.TableTypeV2.GridTable,"GridTableColumnsExtension"],[zj.v2.TableTypeV2.AnalyticalTable,"AnalyticalTableColumnsExtension"],[zj.v2.TableTypeV2.TreeTable,"TreeTableColumnsExtension"]]),DD="annotation",go="schema";var hwe="Facet ID: ",J$t=new Map([...dwe.entries()].map(([e,t])=>[t,e]));var Z$t="@com.sap.vocabularies.UI.v1";var Q$t="annotation",eMt="service",tMt="ui5";var wX=class{schema;value;pattern;freeText;disabled;state=0;description;required;isAtomic;i18nClassification;name;displayName;artifactType;minimum;messages;locations;constructor(t,r){this.schema=structuredClone(t),this.name=r}};function VE(e){return e?.tooComplex===!0}var nMt=new Map;nMt.set("com.sap.vocabularies.UI.v1.HeaderInfo",new Set(["com.sap.vocabularies.UI.v1.HeaderFacets","com.sap.vocabularies.UI.v1.Identification"]));var kRn=["com.sap.vocabularies.UI.v1.DeleteHidden","com.sap.vocabularies.UI.v1.UpdateHidden"],rMt=e=>(e||"").split("/@").pop()||"";function iMt(e,t){let r=e.nodes.find(n=>n?.nodeId&&n.nodeId[0]===t[0]);for(let n=1;n<t.length;n++){if(r&&VE(r))return r;r=r?.subnodes.find(i=>i.nodeId[n]===t[n])}return r}function aMt(e){return VE(e)?e.tooComplexLocations??[]:e.location?[e.location]:[]}function mwe(e,t,r,n){let i=$Rn(t,n);for(let a of i){let o=t[a],s=o.annotationPath.split("/").map((c,u)=>u===1?c.split(".").slice(-1)[0]??c:c).join("/");if(e===o.annotationPath||e===s)return o;if(!r&&!VE(o)&&o.subnodes.length>0){let c=mwe(e,o.subnodes,void 0,n);if(c)return c}}}function oMt(e,t,r,n,i){let a=rMt(e),o=mwe(e,r,void 0,i);return!o&&kRn.includes(a)&&(o=t.find(c=>c.nodeType===W$t)?.subnodes.find(c=>c.annotationPath===e)),!o&&nMt.get(rMt(n))?.has(a)&&(o=mwe(e,t,!0,i)),o}function $Rn(e,t){let r=[];t!==void 0&&e.length>t&&r.push(t);for(let n=0;n<e.length;n++)n!==t&&r.push(n);return r}var gwe="i18n",MRn=(e="",t=!1,r)=>{if(/^{{[^\\{}:]+}}$/.exec(e)&&(!t||r))return e.toString().substring(2,e.length-2);let n=t?`(${gwe}|@${gwe})`:`${gwe}`,i=t?2:1,a=new RegExp(`^{${n}>([^\\{}:]+)}$`).exec(e);return a?a[i]:void 0},ywe=(e,t={})=>{let r=MRn(e,!0,!0);if(r){let n=t[r];if(n?.length>0)return n[0].value?.value}},sMt=(e,t,r,n="EDMXBackend")=>["CAPJava","CAPNodejs"].includes(n)&&!e&&t?eMt:r?Q$t:tMt;var UO=(e,t)=>!e||!t?e===t:e.length===t.length&&e.every(function(r,n){return r===t[n]}),vwe=(e,t)=>{if(!e||!t||t.length>e.length)return!1;let r=e.length-1,n=t.length-1;for(;n>=0;){if(t[n]!==e[r])return!1;r--,n--}return!0},BO=(e,t)=>{let r=e;for(let n of t)if(n!==void 0)if(typeof r=="object"&&n in r)r=r[n];else return;return r};var FRn=()=>({bundles:{annotation:{},app:{},service:{},ui5:{}}}),ND=(e,t=!1)=>{let r=e[e.length-1];if(r){let n=r.toString(),i=n.includes(":::")?":::":"::",a=r.toString().split(i);if(n=a[0],!t&&a.length>1&&(a.splice(0,1),n=a.join("/")),n)return n}},uMt=(e,t)=>{let r,n=0,i=!1;for(let o in e.aggregations)e.aggregations[o].custom?i=!0:(r=n>0?void 0:e.aggregations[o],n++);if(!i||!r?.actions)return;let a=r.actions.findIndex(o=>o==="Delete"||typeof o=="object"&&o.type==="Delete");if(a!==-1){let o=r.actions[a];typeof o!="object"&&(o={type:o}),o.disabled=!0,o.title=vt.t(t),r.actions[a]=o}},Sv=(e,t,r,n)=>{t||(e.state=1,e.messages=[{text:r,type:"warning"}],e.inactive=!0,n&&e.properties[n]&&bwe(e.properties[n],[{text:r}]))},ID=(e,t=e.value)=>{let r=t&&typeof t=="object"?t:{},n="key"in r&&!!r.key;Sv(e,n,vt.t("PAGE_EDITOR_CUSTOM_EXTENSION_NO_KEY"),"key")};var DX=(e,t)=>{let r=e.name==="position"?e.parent?.name:e.name;if(t.enum){let n={...t,enum:[...t.enum]},i=n.enum.findIndex(a=>a===r);return i!==-1&&n.enum.splice(i,1),n}else if(t.oneOf){let n=FRn(),i={...t,oneOf:[...t.oneOf]};for(let a=0;a<i.oneOf.length;a++){let o=i.oneOf[a];o.bundle=sMt(o.custom,!0,!!o.annotationNodeId,n.projectType),o.const===r&&(i.oneOf[a]={...o,hidden:!0})}return i}return t};function bwe(e,t){e.messages??=[],e.messages.push(...t)}function Ewe(e){let t="",r=!0;for(let n=0;n<e.length;n++){let i=e[n];if(i==="_"||i==="-"||i===" "){t.endsWith(" ")||(t+=" "),r=!0;continue}let a=e[n-1],o=e[n+1];n>0&&(a>="a"&&a<="z"&&i>="A"&&i<="Z"||a>="A"&&a<="Z"&&i>="A"&&i<="Z"&&o&&o>="a"&&o<="z")&&(t+=" ",r=!0),r?(t+=i.toUpperCase(),r=!1):t+=i}return t.trim()}var lMt={top:["header","filterBar"]},_we=["anchor","relatedFacet"],Gt=class e{path=[];aggregations={};properties={};additionalProperties;variants=[];childClass;additionalText;locations;actions;inactive;schema;annotationCreationForms=[];allowedAnnotationCreationForms=[];schemaCreationForms=[];formSchema;sortableList;sortableItem;sortableReadonlyTooltip;sortableConfigOnly;order;description;i18nKey;state=0;messages;value;type="Object";parent;custom=!1;isViewNode;isTable=!1;pattern;name;union;sortableCollection;annotationNodeId;dropUINodes;pending;hidden;artifactType;virtual;icon;isAtomic;constructor(t,r){t&&(this.aggregations=t.aggregations,this.properties=t.properties),r&&(this.schema=r)}addAggregation(t,r,n,i,a){if(this.aggregations[t]&&!a)return this.aggregations[t];if(r.name=t,i!==void 0&&!Number.isNaN(i)){for(let o in this.aggregations){let s=this.aggregations[o].order;s!==void 0&&!Number.isNaN(s)&&s>=i&&(this.aggregations[o].order=s+1)}r.order=i}else r.order=Object.keys(this.aggregations).length;return Object.defineProperty(r,"parent",{value:this,writable:!1}),this.aggregations[t]=r,this.updatePath(this.aggregations[t],n),r}addProperty(t,r){_we.includes(t)&&(r=DX(this,r));let n=r.displayName||Ewe(t),i=new wX(r,n);return this.properties[t]=i,i}getDisplayName(t={}){let r=[()=>{let i=this.getRawDisplayName(),a=ywe(i,t);return a||i},this.getTechnicalName.bind(this),()=>{let i=this.getFormattedName();return i?Ewe(i):void 0}],n="";for(let i of r)if(n=i()||"",n)break;return n}getSupportedActions(){let t=[...this.actions??[]];return this.locations?.length&&t.push("OpenSource"),t}getKeys(){if(this.schema?.keys)return this.schema.keys}getValueOfSchemaKey(t){return this.getKeys()?.find(n=>n.name===t)?.value}getTechnicalName(){}getRawDisplayName(){if(this.isViewNode){let t=this.formatTextForDisplay(this.description);if(t)return t}return this.formatTextForDisplay(this.schema?.title)}formatTextForDisplay(t=""){return t.trim()}updateValues(t){let r=Object.keys(this.properties),n=Object.keys(this.aggregations);if(t)for(let i in t)r.includes(i)&&(this.properties[i].value=t[i]),n.includes(i)&&(this.aggregations[i].value=t[i])}updatePropertiesValues(t,r,n,i,a,o){this.updateValues(t),this.updateAnnotationData(a),this.annotationCreationForms=this.getNativeNodeCreationForms(a);for(let s in this.aggregations){let c=this.type==="Array"?Number.parseInt(s,10):s,u=this.aggregations[s].union?.originalNames||[s];for(let l of u)this.aggregations[s].updatePropertiesValues(t?.[l],r,n,i.concat([c]),a,o);this.aggregations[s].onPropertiesUpdated()}this.isAtomic&&this.handleAtomicObject(t,i)}onPropertiesUpdated(){}updateAnnotationData(t){let r=this.getCurrentUINode(t),n=r?.direct?r.node:void 0;this.setAllowedParents(t,n),this.updateLocations(t,n),r?.node&&!VE(r.node)&&r.node.readonly&&this.applyReadonlyAnnotationNode(r.node.readonlyTooltip),!this.custom&&this.sortableItem==="Enabled"&&!this.annotationNodeId&&(this.sortableItem="Readonly",this.removeAction("Delete"))}setAllowedParents(t,r){r&&(this.dropUINodes=r?.allowedParentNodes)}updateLocations(t,r){this.locations=this.locations||[];let n=this.locations.length;if(!r||n&&this.isMacrosNode())return;let i=aMt(r);if(i.length>0){if(n)for(let a of this.locations)i.some(o=>o.fileUri!==a.fileUri)&&i.push(a);this.locations=i}}getNativeNodeCreationForms(t){return!this.name||!t?[]:this.annotationNodeId||this.getParentAnnotationNodeId()?[]:this.getDefaultNativeCreationForms(t)}getDefaultNativeCreationForms(t){return[]}getParentAnnotationNodeId(){let t=this.parent;for(;t;){if(t.annotationNodeId)return t.annotationNodeId;t=t?t.parent:void 0}}getProperties(){return this.properties}getCopy(t=e){let r=JSON.parse(JSON.stringify(this,(i,a)=>{if(i!=="parent")return a})),n=new t(r);return this.createAggregations(n,t),new t(n)}createAggregations(t,r=e){if(t.aggregations){for(let n in t.aggregations)t.aggregations[n]=new r(t.aggregations[n]),this.createAggregations(t.aggregations[n]);t.additionalProperties?.aggregations&&(t.additionalProperties=new r(t.additionalProperties))}}aggregationOrderSorter(t,r){let n=this.aggregations[t]&&this.aggregations[t].order||-1,i=this.aggregations[r]&&this.aggregations[r].order||-1;return n===i?0:n>i?1:-1}getAggregationKeys(t=!1,r){let n=Object.keys(this.aggregations).sort(this.aggregationOrderSorter.bind(this));return this.sortableList||(n=n.sort((i,a)=>{let o=lMt.top.indexOf(i),s=lMt.top.indexOf(a);return o!==-1&&s!==-1&&o>s?1:o!==-1?-1:s!==-1?1:0})),t&&(n=n.filter(i=>this.aggregations[i].isViewNode&&!this.aggregations[i].hidden)),r==="ViewNode"&&(n=n.sort(this.getViewNodeSorter.bind(this))),n}getViewNodeSorter(t,r){let n=this.aggregations[t].isViewNode,i=this.aggregations[r].isViewNode;return n===i&&!n?t===r?0:t>r?1:-1:this.aggregations[t].isViewNode===this.aggregations[r].isViewNode?0:this.aggregations[t].isViewNode?1:-1}updatePath(t,r){if(t.setPath(r),t.aggregations)for(let n in t.aggregations)this.updatePath(t.aggregations[n],r.concat([n]))}setPath(t){this.path=t}getMaxOrder(){let t=0;for(let r in this.aggregations){let n=this.aggregations[r].order||0;t<n&&(t=n)}return t}findMatchingParent(t=e){let r=this.parent;for(;r;){if(r instanceof t)return r;r=r?r.parent:void 0}}addUnionName(t,r){let n=this.union?.originalNames||[];n.includes(r)||n.push(r),this.union={name:t,originalNames:n}}getFormattedName(){return this.name}getCurrentUINode(t){if(this.name&&t){let r=this.annotationNodeId||this.getParentAnnotationNodeId();if(r){let n=iMt(t,r);if(n)return{node:n,direct:!!this.annotationNodeId}}}}applyReadonlyAnnotationNode(t){let r=i=>{for(let a=0;a<i.length;a++){let o=i[a];typeof o=="string"&&(i[a]=o={type:o}),o.disabled=!0,o.title=t}},n=i=>{i.sortableItem="Readonly",t&&(i.sortableReadonlyTooltip=t)};for(let i in this.aggregations){let a=this.aggregations[i];a.actions&&!a.custom&&r(a.actions),a.sortableItem==="Enabled"&&n(a)}this.actions&&r(this.actions),this.sortableItem==="Enabled"&&n(this)}removeAction(t){if(this.actions){let r=this.actions.indexOf(t);r!==-1&&this.actions.splice(r,1)}}nodeIdToString(t){return`[${t.join(",")}]`}findDropableCollectionsByCollection(t,r){let n=[];if(t.sortableList&&t.sortableCollection===r)n.push(t);else for(let i in t.aggregations){let a=t.aggregations[i],o=this.findDropableCollectionsByCollection(a,r);n.push(...o)}return n}getAllowedDropRange(t){}findAllowedDropAggregations(t,r=this){let{dropUINodes:n={},sortableCollection:i}=t,a=[];if(r.annotationNodeId&&n[this.nodeIdToString(r.annotationNodeId)]){let o=this.findDropableCollectionsByCollection(r,i);a.push(...o.map(s=>{let c=s.getAllowedDropRange(t);return{path:s.path,range:c}}))}for(let o in r.aggregations){let s=r.aggregations[o],c=this.findAllowedDropAggregations(t,s);a.push(...c)}return a}isMacrosNode(){return!!this.schema?.metadata}convertAtomicPropertyToAggregation(t,r){let n=new e,i=t.toString();this.properties[t]&&(n.properties[i]=this.properties[t],n.properties[i].isAtomic=!0),this.addAggregation(t.toString(),n,r.concat(t))}handleAtomicObject(t,r){if(typeof t=="object"){if(Array.isArray(t))for(let n=0;n<t.length;n++)this.convertAtomicPropertyToAggregation(n,r);else for(let n in t)this.convertAtomicPropertyToAggregation(n,r);this.properties={}}}};var zO=class extends Gt{actions=["Delete"];sortableItem="Enabled";isViewNode=!0;sortableCollection="actions";data;getTechnicalName(){let t=this.path[this.path.length-1];if(t&&typeof t=="string"){let r=t.split("::"),n="";if(r[r.length-1].includes("."))for(let i=0;i<r.length;i++)r[i]===AX&&r[i+1]&&(n=r[i+1]);else n=r[r.length-1];if(n){let i=n.split(".");return i[i.length-1]}}return super.getTechnicalName()}markAsCustomAction(){this.custom=!0,this.actions=["OpenSource"],this.sortableItem="Enabled",this.additionalText=vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_ACTION"),this.i18nKey=this.parent?.i18nKey,this.isMacrosNode()?ID(this):this.actions.push("Delete");let t=this.aggregations.position?.properties.anchor;t?.value&&((t.schema.oneOf||[]).some(n=>n.const===t.value)||Sv(this,!1,vt.t("PAGE_EDITOR_CUSTOM_EXTENSION_NO_ANCHOR")))}markAsStandardAction(){this.sortableItem="Readonly",this.additionalText=vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_STANDARD_ACTION"),this.i18nKey=this.parent?.i18nKey,this.removeAction("Delete")}getActionType(){return typeof this.schema?.actionType=="string"?this.schema.actionType:void 0}};var NX=class extends Gt{sortableList=!0;childClass=zO;allowedAnnotationCreationForms=["NativeAction","NativeNavigation"];sortableCollection="actions";i18nKey="ACTIONS";constructor(t,r){super(t,r),r?.properties&&this.schema?.additionalProperties&&this.schema?.metadata?.type!=="Aggregation"&&(this.schemaCreationForms=[{name:"CustomAction",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_ACTIONS_TITLE",disabled:!1}])}addAggregation(t,r,n,i,a){if(r=super.addAggregation(t,r,n,i,a),r instanceof zO&&r.name)switch(r.schema?.actionType){case"Standard":{r.markAsStandardAction();break}case"Copy":{r.sortableItem="Readonly";break}}return r}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),this.formSchema=this.additionalProperties?.aggregations.actions;let o=t||{};for(let s in o){let c=this.aggregations[s];c?.name&&c.schema?.actionType==="Standard"?c.markAsStandardAction():c?.schema&&(c.schema.actionType==="Custom"||!c.schema.annotationPath)&&c.markAsCustomAction()}}getNativeNodeCreationForms(t){return this.parent&&this.parent.name==="footer"&&(this.allowedAnnotationCreationForms=["NativeAction"]),super.getNativeNodeCreationForms(t)}getActionType(t){let r=t.schema?.actionType;return r?r==="Standard"&&!t.schema?.annotationPath?"StandardWithoutAnnotation":r:t.custom?"Custom":"Annotation"}calculateDropRangeEdges(t,r){let n={top:-1,bottom:-1},i={top:["Standard","Copy","Annotation"],bottom:["Criticality","Standard","Copy"]};for(let a=0;a<t.length;a++){let o=t[a],s=this.aggregations[o],c=this.getActionType(s);if(c&&i.top.includes(c)){n.top=a;break}}if(r!=="Custom")for(let a=0;a<t.length;a++){let o=t[a],s=this.aggregations[o],c=this.getActionType(s);c&&i.bottom.includes(c)&&(n.bottom=a+1)}else n.bottom=n.top;return n}getActionsContainers(t){let r=this.getAggregationKeys(!0),n=0;for(let a=r.length-1;a>=0;a--){let o=r[a],s=this.aggregations[o];if(this.getActionType(s)!=="StandardWithoutAnnotation")break;n++}if(t==="Custom"&&n===0)return;let i=this.calculateDropRangeEdges(r,t);if(i.top===-1&&(i.top=i.bottom),i.bottom===-1&&(i.bottom=i.top),!(i.top===-1||i.bottom===-1))return{top:{from:0,to:i.top},bottom:{from:i.bottom,to:r.length-n}}}getAllowedDropRange(t){let r=this.getActionType(t),n=this.getActionsContainers(r),i;if(n)switch(r){case"Custom":{i=[n.top,n.bottom];break}case"Copy":case"Standard":case"StandardWithoutAnnotation":{i=[];break}case"Criticality":{i=[n.top];break}case"Annotation":{i=[n.bottom];break}}return i}};var IX=class extends Gt{actions=["Delete"];getDisplayName(){return this.name?this.name:super.getDisplayName()}};var RX=class extends Gt{sortableList=!1;childClass=IX;i18nKey="ADDITIONALOBJECTS";constructor(t,r){super(t,r),this.schemaCreationForms=[{name:"Generic",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_GENERIC_TITLE",disabled:!1}]}addAggregation(t,r,n,i,a){return r.custom=!0,super.addAggregation(t,r,n,i,a)}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),this.name&&(this.formSchema=this.additionalProperties?.aggregations[this.name])}};var LX=class{validate(t,r){if(t.state===0&&t.variants.length>=1){let n=this.validateVariants(t.variants,t);for(let i in n){let a=t.properties[i]||t.aggregations[i];a&&(a.state=n[i],a.state===1&&bwe(a,[{text:vt.t("PAGE_EDITOR_PROPERTIES_PROPERTY_WARNING_PROPERTY_NOT_ALLOWED",{name:i}),deletable:!0}]))}}for(let n in t.aggregations)this.validate(t.aggregations[n],r?r[n]:{})}validateVariants(t,r){let n={};for(let s in r.properties)r.properties[s].value!==void 0&&(n[s]=r.properties[s].value);for(let s in r.aggregations)r.aggregations[s].value!==void 0&&(n[s]=r.aggregations[s].value);let i=[...t];for(let s in n)i=i.filter(c=>this.validateVariant(c,r,s)===0);if(i.length===0){i=[...t];for(let s in n)i=i.filter(c=>this.validateVariant(c,r,s,!0)===0)}this.unifyVariants(r,i);let a={},o=[...Object.keys(r.properties),...Object.keys(r.aggregations)];for(let s of o)i.some(u=>s in u.properties||s in u.aggregations)?a[s]=0:s in n?a[s]=1:a[s]=2;return a}validateVariant(t,r,n,i=!1){let a=t.aggregations[n]||t.properties[n];if(a===void 0)return i?0:2;let s=(r.properties[n]||r.aggregations[n]||{}).value;if(a.schema){if(a.schema.pattern&&!new RegExp(a.schema.pattern).exec(s.toString()))return 2;if(a.schema.enum&&!a.schema.enum.includes(s)&&!a.freeText)return 2}return 0}*iterateVariantAggregations(t){for(let r of t)for(let[n,i]of Object.entries(r.aggregations))yield[n,i]}unifyVariants(t,r){let n={};for(let[i,a]of this.iterateVariantAggregations(r))a.union&&!n[i]&&(this.applyContextPath(t.aggregations[i],a.path),t.aggregations[i].name=a.path[a.path.length-1].toString(),n[i]=!0);if(Object.keys(n).length){for(let i in n)t.aggregations[i].variants=[];for(let i of r)for(let a in n){let o=i.aggregations[a];o&&(t.aggregations[a].variants=[...t.aggregations[a].variants,...o.variants.length?o.variants:[o]])}}}applyContextPath(t,r){t.path=t.path.slice();for(let n=0;n<r.length;n++)t.path[n]=r[n];for(let n in t.aggregations)this.applyContextPath(t.aggregations[n],r)}};var Gj=class extends Gt{type="Array";constructor(t,r){super(t,r),this.schemaCreationForms=[{name:"Generic",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_GENERIC_TITLE",disabled:!1}]}addAggregation(t,r,n,i){return super.addAggregation(t,r,n,i),this.sortableList=!0,r.sortableItem="Enabled",r.actions=["Delete"],r.schema&&!r.schema.title&&(r.schema.title=vt.t("PAGE_EDITOR_OUTLINE_ARRAY_ITEM",{name:Number.parseInt(t,10)+1})),r.custom=!0,r}updatePropertiesValues(t,r,n,i){if(super.updatePropertiesValues(t,r,n,i),!!Array.isArray(t))for(let a=0;a<t.length;a++){let o=this.aggregations[a];if(!o)continue;let s;if(this.isAtomic)s=t[a];else{let c=this.getPrimaryKey(o);s=c?t[a][c]:void 0}typeof s!="object"&&(o.additionalText=s)}}getPrimaryKey(t){let r=["id","title","key","name"],n=t.schema?t.schema.properties||{}:{},i;for(let a of r)if(a in n){i=a;break}for(let a in n)if(n[a].type==="string"){i=a;break}return i}};var qE=class extends Gt{allowedAnnotationCreationForms=["AnalyticalChart"];name="root";getDefaultNativeCreationForms(){return this.annotationCreationForms}updateAnnotationData(t){this.annotationCreationForms=[],super.updateAnnotationData(t);let r=!!this.aggregations.chart?.isViewNode;if(!!(this.aggregations.table?.aggregations.views?.isViewNode&&!r)&&t?.dialogsContext?.analyticalChartSupport!==void 0){let i={name:"AnalyticalChart",title:t.dialogsContext.analyticalChartSupport.creationTooltip,disabled:!t.dialogsContext.analyticalChartSupport.creationEnabled,kind:DD,visualizationIcon:"Add",buttonText:vt.t("ADD_CHART"),buttonId:"add-chart"};i.disabled&&(i.disabledTitle=i.title),this.annotationCreationForms.push(i)}}};var kX=class extends Gt{updateAnnotationData(t){let r=t?.dialogsContext?.analyticalChartSupport;if(this.actions=[],r){let n=this.getDeletionSupport(r),i={type:"Delete",title:n.deletionTooltip};i.disabled=!n.deletionEnabled,this.actions.push(i)}super.updateAnnotationData(t)}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),!!this.schema?.properties?.annotationPath&&!t?.annotationPath&&(this.hidden=!0)}getDeletionSupport(t={}){if(t?.deletionEnabled){let r=this.findMatchingParent(qE);if(!r?.schema?.properties?.defaultTemplateAnnotationPath&&r){let i=r.aggregations.table?.value;if(typeof i=="object"){let a=i?.annotationPath;this.isComplexScenario(a)&&(t={deletionEnabled:!1,deletionTooltip:vt.t("CHART_DELETION_UNSUPPORTED_BY_SPEC")})}}}return t}isComplexScenario(t){let r=t.split("."),n=r[r.length-1]||"";return n.startsWith("SelectionPresentationVariant")||n.startsWith("PresentationVariant#")}};var HO=class extends Gt{actions=["Delete"];sortableItem="Enabled";isViewNode=!0;sortableCollection="fields";getRawDisplayName(){let t=super.getRawDisplayName();if(!t){let r=this.getTechnicalName();if(r)return r}return t}getTechnicalName(){return ND(this.path)}};var $X=class extends Gt{sortableList=!0;childClass=HO;allowedAnnotationCreationForms=["NativeField","NativeContactField","NativeConnectedFields"];sortableCollection="fields";i18nKey="FIELDS";updateAnnotationData(t){super.updateAnnotationData(t),this.path[0]==="header"&&this.allowedAnnotationCreationForms.splice(this.allowedAnnotationCreationForms.indexOf("NativeConnectedFields"))}};var MX=class extends HO{sortableList=!0;childClass=HO};var RD=class extends Gt{actions=["Delete"];sortableItem="Enabled";isViewNode=!0;getRawDisplayName(){let t=super.getRawDisplayName();if(!t){let r=this.getTechnicalName();if(r)return r}return t}getTechnicalName(){let t=this.path[this.path.length-1];if(t){let n=t.toString().split("::"),i=n[n.length-1];if(i)return i}}markAsCustomFilterField(){this.custom=!0,this.actions=["OpenSource"],this.isMacrosNode()||this.actions.push("Delete"),this.sortableItem="Enabled",this.additionalText=vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_FILTER_FIELD"),this.i18nKey=this.parent?.i18nKey,this.isMacrosNode()&&ID(this);let t=this.properties.anchor;t?.value&&((t.schema.oneOf||[]).some(n=>n.const===t.value)||Sv(this,!1,vt.t("PAGE_EDITOR_CUSTOM_EXTENSION_NO_ANCHOR")))}addProperty(t,r){let n=super.addProperty(t,r);return t==="property"&&(n.disabled=!0),n}};var FX=class extends Gt{sortableList=!0;allowedAnnotationCreationForms=["NativeFilterFields"];childClass=RD;i18nKey="FILTER_FIELDS";constructor(t,r){super(t,r);let n=r?.additionalProperties;typeof n=="object"&&n.$ref&&!this.isMacrosNode()&&(this.schemaCreationForms=[{name:"CustomFilterField",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_FILTER_FIELDS_TITLE",disabled:!1}])}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),this.formSchema=this.additionalProperties?.aggregations.selectionFields;let o=t||{};for(let s in o){let c=this.aggregations[s];c?.schema&&!c.schema.annotationPath&&c.markAsCustomFilterField()}}};var fMt=require("node:path");var dMt=dt(Zd()),Av=class extends Gt{filePath;constructor(t,r){super(t,r),this.path=["macros"],this.isViewNode=!0,this.virtual=!0,this.allowedAnnotationCreationForms=[];let n=this.getCreationForms();this.annotationCreationForms=n.internal,this.schemaCreationForms=n.external;let i=this.schema?.metadata?.filePath;i&&this.setFilePath(i)}getCreationForms(){return{internal:[{name:"MacrosChart",kind:DD,disabled:!1,title:"ADD_BUILDING_BLOCK_CHART"},{name:"MacrosFilterBar",kind:DD,disabled:!1,title:"ADD_BUILDING_BLOCK_FILTERBAR"},{name:"MacrosTable",kind:DD,disabled:!1,title:"ADD_BUILDING_BLOCK_TABLE"}],external:[]}}getDisplayName(){return vt.t("PAGE_EDITOR_OUTLINE_NODE_BUILDING_BLOCK")}getNativeNodeCreationForms(){return this.annotationNodeId?this.annotationCreationForms:[]}setFilePath(t){this.filePath=(0,fMt.join)(dMt.DirName.Webapp,t)}updateAnnotationData(t){if(super.updateAnnotationData(t),t?.dialogsContext?.analyticalChartSupport!==void 0){let r=this.annotationCreationForms.find(n=>n.name==="MacrosChart");r&&(r.disabled=!t.dialogsContext.analyticalChartSupport.creationEnabled,r.disabled&&(r.tooltip=t.dialogsContext.analyticalChartSupport.creationTooltip))}}};var EMt=require("node:path"),kD=dt(Pc());var Jm=class extends Gt{actions=["Delete"];title;id;position;data;useDescriptionAsId;isViewNode=!0;sortableCollection="sections";constructor(t,r){super(t,r),this.sortableItem="Enabled"}setTitle(t){this.title=t}setId(t){this.id=t}getRawDisplayName(){return this.title||this.getSectionId()||super.getRawDisplayName()}getSectionId(t=!0){if(this.schema){if(this.schema.title?.startsWith(hwe)){let r=this.schema.title.split(hwe);return r.length>1?r[r.length-1]:r[0]}else if(t&&this.useDescriptionAsId&&this.schema.description)return this.schema.description}if(this.data&&"id"in this.data)return this.data.id}markAsReplaced(t){this.inactive=!0,this.additionalText=vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_SECTION_REPLACED_WITH",{section:t})}markAsCustomSection(t,r,n){this.custom=!0,this.actions=["Delete",n||"OpenSource"],this.sortableItem="Enabled",this.additionalText=vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_SECTION"),this.data=t,this.i18nKey=r}getTechnicalName(){return this.getSectionId()}getFormattedName(){let t=this.name,r=`${Z$t}.`;return t?.includes(r)&&(t=t.replace(r,"")),t}};var Bf=dt(Pc());var Kj="custom",LD=class extends Gt{customSections=[];sections=[];sortingApproach="Normal";allowedAnnotationCreationForms=void 0;sortableCollection="sections";constructor(t,r){super(t,r),this.childClass=Jm,r?.properties?.custom&&(this.schemaCreationForms=[{name:"CustomSection",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_SECTIONS_TITLE",disabled:!1}]),this.sortableList=!0,this.i18nKey="SECTIONS"}updatePropertiesValues(t,r,n,i,a,o){if(super.updatePropertiesValues(t,r,n,i,a,o),this.formSchema=this.aggregations[Kj],this.sortingApproach=this.getSortingApproach(),delete this.aggregations[Kj],this.correctSectionData(),this.formSchema&&(this.customSections=t&&Kj in t?t[Kj]:[],this.customSections.length)){this.sections=Object.keys(this.aggregations);let s=[...this.sections];for(let p in s){let f=this.aggregations[s[p]];this.traverseCustomSections(f.getSectionId()||s[p],this.customSectionFactory.bind(this,r,n,i,o))}let c=this.customSections.filter(p=>{for(let f in this.aggregations)if(this.aggregations[f].data===p)return!1;return!0});for(let p of c)this.customSectionFactory(r,n,i,o,p);let u=this.aggregations;this.aggregations={};let l=0;for(let p of this.sections)this.aggregations[p]=u[p],this.aggregations[p].order=l,l++}}onPropertiesUpdated(){this.customSections.length&&!this.isV4()&&uMt(this,"SECTION_UNDELETABLE_LAST_NATIVE_NODE")}traverseCustomSections(t,r){let n=this.customSections.filter(a=>this.isSectionMatchesRelatedFacet(a.relatedFacet,t)),i=this.sortingApproach==="WithIds";for(let a of n)r(a),i&&"id"in a&&this.traverseCustomSections(a.id,r)}customSectionFactory(t,r,n,i,a){if(!this.formSchema)return;let o=this.customSections.indexOf(a),s=this.formSchema.getCopy(Jm);if(s.markAsCustomSection(a,this.i18nKey),i){let p=a,{fragmentName:f}=p,d=i?.definitions[`CustomExtensionFragment<${f}>`];if(d&&s.aggregations.controls){let h=new Av(void 0,d);s.addAggregation("controls",h,s.path,void 0,!0),i.parse(s.aggregations.controls,d,void 0,void 0,n,{filePath:d.metadata?.filePath})}}s.updatePropertiesValues(a,t,r,n,i?.annotations),s.setTitle(a.title),s.position=a.relativePosition;let c=this.storeSection(a);this.addAggregation(c,s,this.path.concat([Kj,o]));for(let p of _we){let f=s.properties[p];f&&(f.schema=DX(s,f.schema))}let u=this.formSchema.properties.relatedFacet?.schema.oneOf?this.formSchema.properties.relatedFacet?.schema.oneOf:[],l=this.isV4()&&!a.relatedFacet?!0:u.some(p=>p.const===a.relatedFacet);Sv(s,l,vt.t("PAGE_EDITOR_CUSTOM_SECTION_NO_FACET"))}correctSectionData(){let t=this.formSchema?.properties.relatedFacet?.schema.oneOf?this.formSchema.properties.relatedFacet.schema.oneOf:[];for(let r in this.aggregations){let n=this.aggregations[r];if(n.custom)continue;this.isV4()&&(n.useDescriptionAsId=!0),n.description&&n.setTitle(n.description);let i=n.getSectionId()||r,a=t.find(o=>this.isSectionMatchesRelatedFacet(i,o.const));a?.description&&(n.setTitle(a.description),n.setId(a.const))}}isSectionMatchesRelatedFacet(t="",r=""){return t.replace(/@/g,"")===r.replace(/@/g,"")}findSectionInsertPosition(t){let{relativePosition:r,relatedFacet:n}=t,i=this.checkRelatedPosition(r,Bf.v2.SectionPosition.AfterFacet,Bf.v2.SectionPosition.ReplaceFacet),a=this.findReferenceSection(n);if(!a)return this.sections.length;let o=this.checkRelatedPosition(r,Bf.v2.SectionPosition.ReplaceFacet),s=this.checkRelatedPosition(r,Bf.v2.SectionPosition.BeforeFacet),c=o?[Bf.v2.SectionPosition.ReplaceFacet]:[Bf.v2.SectionPosition.AfterFacet,Bf.v2.SectionPosition.ReplaceFacet],u=a.index;if(i&&this.sortingApproach==="Normal")for(let l=u+1;l<this.sections.length;l++){let p=this.aggregations[this.sections[l]];if(p?.custom&&p.position&&this.checkRelatedPosition(p.position,...c))u++;else break}return u+(s?0:1)}findReferenceSection(t){for(let r=0;r<this.sections.length;r++){let n=this.sections[r],i=this.aggregations[n],a=i?.getSectionId?.()??n;if(a&&this.isSectionMatchesRelatedFacet(a,t))return{index:r,aggregation:i}}}storeSection(t){let r=this.findSectionInsertPosition(t),n=this.getFreeSectionId("id"in t&&typeof t.id=="string"?t.id:t.title);this.sections.splice(r,0,n);let i=this.findReferenceSection(t.relatedFacet);return i?.aggregation&&this.checkRelatedPosition(t.relativePosition,Bf.v2.SectionPosition.ReplaceFacet)&&i.aggregation.markAsReplaced(t.title),n}getFreeSectionId(t){let r=1,n=t??"missingId";t=n;let i=Object.keys(this.aggregations).filter(o=>this.sections.indexOf(o)===-1),a=[...this.sections,...i];for(;a.includes(t);)t=n+r,r++;return t}checkRelatedPosition(t="",...r){let n=new Map([[Bf.v2.SectionPosition.AfterFacet,"after"],[Bf.v2.SectionPosition.BeforeFacet,"before"],[Bf.v2.SectionPosition.ReplaceFacet,"replace"]]);t=t.toLowerCase();for(let i of r){let a=n.get(i);if(a&&t.includes(a))return!0}return!1}getSortingApproach(){return this.isV4()?"WithIds":"Normal"}isV4(){return!!this.formSchema?.properties.id}getNativeNodeCreationForms(t){if(!t)return[];let r=super.getNativeNodeCreationForms(t),n=r.find(i=>i.name==="AnalyticalChart");return n&&!n.disabled&&(n.disabled=!t.dialogsContext?.analyticalChartSupport?.creationEnabled,t.dialogsContext?.analyticalChartSupport?.creationTooltip&&(n.disabledTitle=t.dialogsContext.analyticalChartSupport.creationTooltip)),r}};var hMt=dt(Pc()),GO=class extends Gt{title;originalIndex;isViewNode=!0;actions=["Delete"];sortableItem="Enabled";criticality;setTitle(t){this.title=t}getRawDisplayName(){return this.title||super.getRawDisplayName()}validateColumnPositioning(){let t=this.value&&typeof this.value=="object"?this.value:{},r=this.aggregations.position?.schema?.properties?.anchor?.enum,n=this.schema?.properties?.anchor?.oneOf,i=!1;if(this.isMacrosNode()){ID(this,t);let a=n??[],o=BO(t,["anchor"]);i=o?a.some(s=>s.const===o):!0}else{let a=r??[],o=BO(t,["position","anchor"]);i=o?a.includes(o):!0}Sv(this,i,vt.t("PAGE_EDITOR_CUSTOM_EXTENSION_NO_ANCHOR"))}markAsCustomColumn(t){let{pageType:r,originalIndex:n,columnExtension:i,isExtensionTypeSupported:a,i18nKey:o,tableExtension:s="ResponsiveTableColumnsExtension",isV4:c=!1,tabkey:u}=t;this.custom=!0,this.actions=["OpenSource"],this.isMacrosNode()||this.actions.push("Delete"),this.sortableItem=!a||s===i?"Enabled":"Excluded";let l=i??"Unknown";u&&r===hMt.PageType.ListReport?this.additionalText=a?vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_COLUMN_WITH_EXTENSION_TAB",{tabkey:u,extension:vt.t(`PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_COLUMN_${l}`)}):vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_COLUMN_TAB",{tabkey:u}):this.additionalText=a?vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_COLUMN_WITH_EXTENSION",{extension:vt.t(`PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_COLUMN_${l}`)}):vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_COLUMN"),this.originalIndex=n,this.i18nKey=o,a&&s!==l&&(this.state=1,this.messages=[{text:vt.t("PAGE_EDITOR_CUSTOM_COLUMN_UNUSED_COLUMN",{tableType:J$t.get(s)}),type:"info"}],this.inactive=!0),c&&this.validateColumnPositioning()}getTechnicalName(){return ND(this.path)}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),this.updateMoveProperties()}updateMoveProperties(){(this.isActionColumn()||this.isNavigationColumn())&&(this.sortableCollection=!this.criticality||this.criticality==="None"?"actions":void 0,this.additionalText=vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_ACTION_COLUMN"))}isActionColumn(){return!!this.name?.startsWith(`${AX}${fwe}`)}isNavigationColumn(){return!!this.name?.startsWith(`${CX}${fwe}`)}};var UE=dt(Pc());var gMt=dt(Pc()),mMt=e=>!e.type||e.type===gMt.ArtifactType.Annotation,jX=e=>{let t=[],r=e.locations?[...e.locations]:[];for(let n=r.length-1;n>=0;n--){let i=r[n];mMt(i)&&(t.push(i),r.splice(n,1))}if(e.parent&&t.length){let n=e.parent.locations||[];e.parent.locations=n.filter(i=>!mMt(i)),e.parent.locations.unshift(...t)}e.locations=r};var Yj="custom",VRn=new Map([[UE.PageType.ObjectPage,"ResponsiveTableColumnsExtension"],[UE.PageType.ListReport,"ResponsiveTableColumnsExtension"],[UE.PageType.AnalyticalListPage,"AnalyticalTableColumnsExtension"]]),VX=class extends Gt{customColumns=[];columnKeys=[];tableColumnExtensionType;allowedAnnotationCreationForms=["Basic","Rating","Chart","Progress","NativeAction","Contact","NativeNavigation"];isV4;sectionId;sortableCollection="actions";constructor(t,r){if(super(t,r),this.childClass=GO,r?.properties){let n;r.properties?.custom?n="CustomColumn":typeof r.additionalProperties=="object"&&r.additionalProperties.$ref&&r.additionalProperties.$ref.indexOf("TableCustomColumn")>-1?(n="CustomColumnV4",this.isV4=!0):this.isMacrosNode()&&(this.isV4=!0),n&&(this.schemaCreationForms=[{name:n,kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_COLUMNS_TITLE",disabled:!1}])}this.sortableList=!0,this.i18nKey="COLUMNS"}groupCustomColumnsByExtension(){let t=new Map,r=[...this.customColumns].sort((n,i)=>{let a=n.columnIndex??0,o=i.columnIndex??0;return a===o?0:a>o?1:-1});for(let n of r){let i=t.get(n.extensionType);i||(i=[],t.set(n.extensionType,i)),i.push(n)}return t}ensureColumnOrder(){let t=this.getAggregationKeys();for(let r=0;r<t.length;r++){let n=this.aggregations[t[r]];n&&(n.order=r)}}updatePropertiesFromCustomAggregation(t,r,n,i){let a=this.formSchema;this.customColumns=t&&Yj in t?t[Yj]:[],n===UE.PageTypeV2.ObjectPage&&(this.sectionId=this.parent?.parent?.schema?.keys?.reduce(o=>o.name==="ID").value),this.customColumns.length&&(this.ensureColumnOrder(),this.columnKeys=Object.keys(this.aggregations),this.groupCustomColumnsByExtension().forEach(s=>{for(let c in s){let u=a?.getCopy(GO),l=s[c],p=this.customColumns.indexOf(l);u.markAsCustomColumn({pageType:n,originalIndex:p,columnExtension:l.extensionType,isExtensionTypeSupported:this.isExtensionTypeSupported(),i18nKey:this.i18nKey,tableExtension:this.tableColumnExtensionType,isV4:this.isV4,tabkey:l.tabKey}),u.updatePropertiesValues(l,r,n,i),u.setTitle(l.text);let f=this.getFreeId(l.id||l.columnKey||"customColumn",this.columnKeys);this.columnKeys.push(f);let d=this.doesColumnExtensionMatchTableType(l)?l.columnIndex:this.getMaxColumnIndex(this.customColumns)+1;this.addAggregation(f,u,this.path.concat([Yj,p]),d)}}))}updatePropertiesValues(t,r,n,i,a){if(super.updatePropertiesValues(t,r,n,i,a),this.resolveTableColumnExtensionType(r,n,i),!this.isV4)this.formSchema=this.aggregations[Yj],delete this.aggregations[Yj],this.updatePropertiesFromCustomAggregation(t,r,n,i);else{this.formSchema=this.additionalProperties?.aggregations.columns;let o=t||{};for(let s in o){let c=this.aggregations[s];c.schema&&!c.schema.annotationPath&&(c.originalIndex=c.schema.propertyIndex,c.markAsCustomColumn({pageType:n,originalIndex:c.schema.propertyIndex,columnExtension:this.tableColumnExtensionType,isExtensionTypeSupported:this.isExtensionTypeSupported(),i18nKey:this.i18nKey,tableExtension:this.tableColumnExtensionType,isV4:this.isV4,tabkey:c.properties.tabkey?.value}))}}}getFreeId(t,r){let n=1,i=t;for(;r.includes(t);)t=i+n,n++;return t}resolveTableColumnExtensionType(t,r,n){let i=n.splice(0,n.length-1);i.push("type");let a=BO(t,i);this.tableColumnExtensionType=typeof a=="string"&&a in UE.v2.TableTypeV2?dwe.get(a):VRn.get(r)}doesColumnExtensionMatchTableType(t){return!this.isExtensionTypeSupported()||t.extensionType===this.tableColumnExtensionType}isExtensionTypeSupported(){return!!this.formSchema?.properties.extensionType}getMaxColumnIndex(t){let r=this.getMaxOrder();for(let n of t)n.columnIndex!==void 0&&r<n.columnIndex&&(r=n.columnIndex);return r}updateLocations(t,r){super.updateLocations(t,r),jX(this)}};var qX=class extends Gt{getTechnicalName(){return(this.parent?ND(this.parent.path,!0):void 0)||super.getTechnicalName()}};var UX=class extends Gt{updateLocations(t,r){super.updateLocations(t,r),jX(this)}};var BX=class extends Gt{sortableCollection="visualFilters";actions=["Delete"];isViewNode=!0};var zX=class extends Gt{sortableList=!0;childClass=BX;i18nKey="VISUAL_FILTERS"};var BE=class extends LD{constructor(t,r){super(t,r);let n=r?.additionalProperties;typeof n=="object"&&n.$ref&&(this.schemaCreationForms=[{name:"CustomSection",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_SECTIONS_TITLE",disabled:!1}])}updatePropertiesValues(t,r,n,i,a,o){super.updatePropertiesValues(t,r,n,i,a,o),this.formSchema=this.additionalProperties?.aggregations?.sections;let s=t||{};this.removeObsoleteAggregations();for(let u in s){let l=this.aggregations[u];l?.schema&&!l.schema.annotationPath&&(l.markAsCustomSection(),o&&this.parseBuildingBlocks({parser:o,page:r,pageType:n},l,u,s,i))}if(this.isSectionsMerged())for(let u in this.aggregations)this.aggregations[u].custom&&(this.aggregations[u].sortableItem="Excluded")}removeObsoleteAggregations(){let t=this.schema?.properties||{};for(let r in this.aggregations)r in t||delete this.aggregations[r]}parseBuildingBlocks(t,r,n,i,a){let{parser:o,page:s,pageType:c}=t,u=i[n],{fragmentName:l}=u,p=o?.definitions[`CustomExtensionFragment<${l}>`];if(p&&r.aggregations.controls){let f=new Av(void 0,p);r.addAggregation("controls",f,a.concat(r.path[r.path.length-1],"controls"),0,!0),o.parse(f,p,void 0,void 0,f.path,{filePath:p.metadata?.filePath});let d=BO(r.value||{},["controls"]);d&&typeof d=="object"&&f.updatePropertiesValues(d,s,c,a,o?.annotations)}}isSectionsMerged(){return!1}};var HX=class extends BE{allowedAnnotationCreationForms=["NativeSection","DataPointSection","ProgressSection","RatingSection","ChartSection"];constructor(t,r){super(t,r);let n=r?.additionalProperties;typeof n=="object"&&n.$ref&&(this.schemaCreationForms=[{name:"CustomHeaderSection",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_SECTIONS_TITLE",disabled:!1}])}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),this.formSchema=this.additionalProperties?.aggregations?.sections;let o=t||{};for(let s in o){let c=this.aggregations[s];if(c?.schema&&!c.schema.annotationPath){let u=c.properties.templateEdit?.value,l=c.properties.fragmentName?.value,p;typeof l=="string"&&typeof u=="string"&&(p={type:"OpenSource",subActions:[{id:l,text:vt.t("CUSTOM_HEADER_SECTION_TEMPLATE")},{id:u,text:vt.t("CUSTOM_HEADER_SECTION_TEMPLATE_EDIT")}]}),c.markAsCustomSection(void 0,void 0,p)}}}};var GX=class extends BE{constructor(t,r){super(t,r);let n=r?.additionalProperties;typeof n=="object"&&n.$ref&&(this.schemaCreationForms=[{name:"CustomSubSection",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_SECTIONS_TITLE",disabled:!1}])}updatePropertiesValues(t,r,n,i,a,o){super.updatePropertiesValues(t,r,n,i,a,o),this.formSchema=this.additionalProperties?.aggregations?.subsections}isSectionsMerged(){let t=0;for(let r in this.aggregations){let n=this.aggregations[r];if("subsections"in n.aggregations)return!1;n.custom||t++}return t>0}};var KO=class extends Gt{title;actions=[];sortableItem="Enabled";sortableCollection="views";constructor(t,r){super(t,r),r?.key&&!r.annotationPath&&!r.properties?.annotationPath&&(r.annotationPath=`${Hj}${r.key})`)}getRawDisplayName(){return this.title||super.getRawDisplayName()}markAsCustomView(){this.custom=!0,this.actions=["Delete","OpenSource"],this.sortableItem="Enabled",this.additionalText=vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_VIEW"),this.i18nKey=this.parent?.i18nKey,this.properties.label?.value&&(this.title=this.properties.label.value)}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),this.isTableView()?this.icon="Table":this.isChartView()?this.icon="Chart":this.icon="Sections",this.isAnnotationView()&&!this.schema?.annotationPath&&this.properties.annotationPath&&(this.properties.annotationPath.messages=[{type:"warning",text:vt.t("PAGE_EDITOR_PROPERTIES_VIEW_NO_ANNOTATION_PATH")}])}isTableView(){return"columns"in this.aggregations}isChartView(){return!("columns"in this.aggregations)&&"toolBar"in this.aggregations}isAnnotationView(){return!this.custom&&"annotationPath"in this.properties||!this.custom&&this.schema?.annotationPath&&!this.schema?.annotationPath.startsWith(Hj)}};var YO=class extends Gt{sortableList=!0;childClass=KO;allowedAnnotationCreationForms=["TableView","AnalyticalChartView","CustomViewV4"];sortableCollection="views";sortableConfigOnly=!0;i18nKey="VIEWS";updateAnnotationData(t){if(super.updateAnnotationData(t),t){this.toggleChartForm(this.annotationCreationForms,t);for(let r in this.aggregations){let n=this.aggregations[r],i=this.getViewDeleteAction(n,t),a=n.actions||[];a.push(i),n.actions=a}}}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),this.formSchema=this.additionalProperties?.aggregations.views,this.formSchema?.properties?.template&&(this.schemaCreationForms=[{name:"CustomViewV4",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_VIEW_TITLE",disabled:!1}]);let o=t||{};if(Object.keys(o).length!==0)for(let s in o){let c=this.aggregations[s];c?.schema&&!c?.schema.properties?.annotationPath&&(!c.schema.annotationPath||c.schema.annotationPath.startsWith(Hj))&&c.markAsCustomView()}}getViewDeleteAction(t,r){let n=t.annotationNodeId,i=!0,a=this.getAnnotationViewCount();return n?i=UO(r.dialogsContext?.suppressTableViewDeletionNodeId||[],n):(a>1||a===1&&t.custom)&&(i=!1),{type:"Delete",disabled:i,title:vt.t(i?"TABLE_VIEW_DELETE_DISABLED_TOOLTIP":"PAGE_EDITOR_OUTLINE_DELETE_TOOLTIP")}}toggleChartForm(t,r){let n=t.find(i=>i.name==="AnalyticalChartView");n&&r.dialogsContext?.analyticalChartSupport&&(r.dialogsContext.analyticalChartSupport.addToMultiViewEnabled?(n.disabled=!1,delete n.disabledTitle):(n.disabled=!0,n.disabledTitle=r.dialogsContext.analyticalChartSupport.addToMultiViewTooltip))}getAnnotationViewCount(){let t=0;for(let r in this.aggregations){let n=this.aggregations[r];n instanceof KO&&n.isAnnotationView()&&t++}return t}};var qRn="array",yMt="object",Twe="sap.fe.macros.Table",vMt=[["table","quickVariantSelection","variants"],["table","quickVariantSelectionX","variants"]],xwe=(e,t,r)=>{let n=r,i=e.split("/").length-1,a=0;for(;a<i;)n=n?.parent,a++;return t.endsWith(`table/${e}`)||n instanceof KO&&t.endsWith(`/${e}`)},URn=(e,t,r)=>!!r?.additionalProperties?.$ref?.includes("CustomSectionActionOP")&&!!t?.name&&e.endsWith(`${t.name}/actions`),Owe=(e,t)=>t?.schema?.metadata?.controlName===e,BRn=(e,t)=>t?.metadata?.controlName===e,bMt=(e,t)=>{let r=t?.additionalProperties;return t?.metadata?.type==="Aggregation"&&typeof r=="object"&&r.$ref===`#/definitions/${e}`},zRn=[{aggregation:BE,fn:(e,t,r)=>{let i=r?.additionalProperties?.$ref?.includes("ObjectPageCustomSectionFragment");return e==="sections"&&!!i}},{aggregation:LD,fn:e=>e==="sections"},{aggregation:VX,fn:(e,t,r)=>xwe("columns",e,t)||bMt("sap.fe.macros.table.Column",r)&&Owe(Twe,t)},{aggregation:UX,fn:(e,t)=>xwe("toolBar",e,t)},{aggregation:$X,fn:e=>e.endsWith("form/fields")},{aggregation:RX,fn:e=>e.endsWith("actions/RelatedApps/additionalSemanticObjects")},{aggregation:MX,fn:(e,t,r)=>r?.dataType==="ConnectedFields"},{aggregation:NX,fn:(e,t,r)=>URn(e,t,r)||["form/actions","header/actions","footer/actions"].some(n=>e.endsWith(n))||xwe("toolBar/actions",e,t)||bMt("sap.fe.macros.table.Action",r)&&Owe(Twe,t)},{aggregation:FX,fn:(e,t)=>e.endsWith("filterBar/selectionFields")||e.endsWith("/filterFields")&&Owe("sap.fe.macros.FilterBar",t)},{aggregation:zX,fn:e=>e.endsWith("filterBar/visualFilters")},{aggregation:qX,fn:(e,t,r)=>e==="table"||e.endsWith("/table")&&t instanceof Jm||BRn(Twe,r)},{aggregation:HX,fn:e=>e.endsWith("header/sections")},{aggregation:qE,fn:e=>e===""},{aggregation:kX,fn:e=>e==="chart"},{aggregation:YO,fn:e=>e.endsWith("table/views")},{aggregation:GX,fn:(e,t)=>e.endsWith("/subsections")&&t instanceof Jm}],HRn=["annotationPath"],KX=class{name;pageType;root=this.prepareAggregation();data;originalData;definitions={};excludeProperties=["$schema"];schema;validator=new LX;pendingNodes=[];constructor(t,r,n,i,a){this.name=t,this.pageType=r,this.data=n,this.originalData={page:structuredClone(this.data),annotations:a,schema:i},this.schema=JSON.parse(i),this.init(a)}init(t){if(this.schema.definitions)for(let i in this.schema.definitions)this.definitions[`#/definitions/${i}`]=this.schema.definitions[i];let r=JSON.parse(this.originalData.schema);this.root=this.prepareAggregation(void 0,{properties:r.properties}),this.parseSchema(this.root,r,{subnodes:t.nodes},void 0,[],{filePath:this.data.$filePath}),this.readAdvancedPropertiesData(this.root,this.data);let n={definitions:this.schema.definitions,parse:this.parseSchema.bind(this),annotations:t};this.root.updatePropertiesValues(this.data,this.data,this.pageType,[],t,n),this.validator.validate(this.root,this.data),this.updateViewNodes(this.root),this.pendingNodes=[],this.afterInit(t)}updatePropertyFromSchema(t,r,n){if(!(t in r.properties))r.properties[t]=r.addProperty(t,n),r.properties[t].freeText=this.isFreeText(n);else if(n.enum){let i=r.properties[t].schema.enum;i=i?i.concat(n.enum):n.enum,r.properties[t].schema.enum=i?i.filter((a,o)=>i&&i.indexOf(a)===o):[]}}getContextForMacrosNode(t,r){for(let n in r){let i=r[n],a="subnodes"in i?i.subnodes:[];for(let o in a)if(a[o].macroNodeId===t)return i}}schemaParsers=[t=>(t.currentNode.const&&!t.currentNode.enum&&(t.currentNode.enum=[t.currentNode.const]),!0),t=>{let{currentNode:r}=t;return!r.hidden},t=>{let{currentNode:r,name:n}=t;if(n===void 0)return!0;if(this.isAggregation(r)){t.path=t.path.concat([t.aggregation.type==="Array"?Number.parseInt(n,10):n]);let i=r.displayName||n,a=r.type===yMt?"Object":"Array";if(t.aggregation=t.aggregation.addAggregation(i,t.aggregation.aggregations[i]||this.prepareAggregation(t.path,r,t.aggregation,a),t.path),t.aggregation.type==="Array")return t.aggregation.schema=r,this.updateFormSchema(t.aggregation),this.copySchemaProperties(t.aggregation,r,n),!1}else this.isProperty(r)&&this.updatePropertyFromSchema(n,t.aggregation,r);return!0},t=>{let{aggregation:r,currentNode:n}=t,i=t.currentAnnotationNode;if(r instanceof Av&&(i=this.originalData.annotations.nodes.find(a=>"nodeType"in a&&a.nodeType==="macros"),r.annotationNodeId=i?.nodeId),n.metadata?.internalId&&!i){let a=this.originalData.annotations.nodes;a=a.filter(o=>"nodeType"in o&&o.nodeType==="macros"),i=t.currentAnnotationNode=this.getContextForMacrosNode(n.metadata.internalId,a)}if(!n.$ref&&n.annotationPath){let a=[];i&&!VE(i)&&(a=i.subnodes);let o=oMt(n.annotationPath,this.originalData.annotations.nodes,a,i?.annotationPath,r.order);o&&(t.currentAnnotationNode=o,r.annotationNodeId=o.nodeId)}return!0},t=>{for(let r of Array.from(this.schemaReferenceParsers))if(r[1](t))break;return!0},t=>{let{aggregation:r,currentNode:n,name:i}=t;return this.copySchemaProperties(r,n,i),!0},t=>{let{aggregation:r,currentNode:n,currentAnnotationNode:i,name:a,path:o,context:s}=t;return typeof n.additionalProperties=="object"&&(r.additionalProperties=this.prepareAggregation(),this.parseSchema(r.additionalProperties,n.additionalProperties,i,a,o,s),this.isSchemaAtomic(n.additionalProperties)&&this.updateFormSchema(r,a)),!0},t=>{let{aggregation:r,currentNode:n,currentAnnotationNode:i,name:a,path:o,context:s}=t;return typeof n.patternProperties=="object"&&(r.pattern=Object.keys(n.patternProperties)[0],n.additionalProperties=n.patternProperties[r.pattern],r.additionalProperties=this.prepareAggregation(),this.parseSchema(r.additionalProperties,n.patternProperties[r.pattern],i,a,o,s),this.updateFormSchema(r,a)),!0},t=>{let{aggregation:r,currentNode:n}=t;if(n.required)for(let i of n.required){let a=r.properties[i];a&&(a.required=!0)}return!0},t=>{let{aggregation:r,currentNode:n,name:i}=t;return n.displayName&&i&&n.type==="object"&&r.addUnionName(n.displayName,i),!0},t=>{let{name:r="",aggregation:n,currentNode:i,context:a}=t,{metadata:o}=i,s=n.properties[r];if(a.filePath&&o){let{position:c}=o,u=[];c&&u.push({fileUri:(0,EMt.join)(kD.DirName.Webapp,a.filePath),range:{start:{line:c.startLine-1,character:c.startColumn-1},end:{line:c.endLine-1,character:c.endColumn}},relative:!0,type:kD.ArtifactType.XMLProperty}),s?s.locations=u:n.name===r&&(n.locations=u)}return!0},t=>{let{path:r,name:n="",aggregation:i}=t;return r&&vMt.some(a=>vwe(r,a))&&this.updateFormSchema(i,n),!0}];schemaReferenceParsers=new Map([["$ref",t=>{let{aggregation:r,currentNode:n,currentAnnotationNode:i,name:a,path:o,context:s}=t;if(!n.$ref)return!1;let c=this.definitions[n.$ref]?{...this.definitions[n.$ref]}:{};for(let u of Object.keys(n)){let l=HRn.includes(u);u!=="$ref"&&!(l&&c[u])&&(c[u]=n[u])}return this.parseSchema(r,c,i,a,o,s),!0}],["anyOf",t=>{let{aggregation:r,currentNode:n,currentAnnotationNode:i,name:a,path:o,context:s}=t;if(!n.anyOf)return!1;for(let c of n.anyOf)this.parseSchema(r,c,i,a,o,s);return(Object.keys(n.anyOf).length>1||Array.isArray(n.anyOf)&&n.anyOf.length>1)&&this.createAnyOfPropertiesVariations(n.anyOf,t),!0}],["properties",t=>{let{aggregation:r,currentNode:n,currentAnnotationNode:i,path:a,context:o}=t;if(!n.properties)return!1;let s=Object.keys(n.properties).filter(l=>!this.excludeProperties.includes(l)),c=n.properties,u=s.some(l=>n.properties&&n.properties[l]?.propertyIndex!==void 0);c&&s.length&&u&&s.sort(this.propertySorter.bind(this,c));for(let l of s)this.parseSchema(r,n.properties[l],i,l,a,o);return!0}],["items",t=>{let{aggregation:r,currentNode:n,currentAnnotationNode:i,path:a,context:o}=t;if(!n.items)return!1;if(Array.isArray(n.items))for(let s=0;s<n.items.length;s++)this.parseSchema(r,n.items[s],i,s.toString(),a,o);else this.parseSchema(r,n.items,i,void 0,a,o);return!0}]]);createAnyOfPropertiesVariations(t,r){let{aggregation:n,currentAnnotationNode:i,name:a,path:o,context:s}=r;for(let c of t){let u=this.prepareAggregation();this.parseSchema(u,c,i,a,o,s);let l=a;if(a&&!u.aggregations[a]){let f=Object.keys(u.aggregations);l=f.length>0?f[0]:a}let p=n;l&&(p=n.aggregations[l],u=u.aggregations[l]),u&&p&&p.variants.push({aggregations:u.aggregations,properties:u.properties})}a&&n.properties[a]&&(n.properties[a].freeText=this.isFreeText(t))}parseSchema(t,r,n,i,a,o){let s={aggregation:t,currentNode:r,currentAnnotationNode:n,name:i,path:a,context:o};for(let c of this.schemaParsers)if(!c.call(this,s))break}copySchemaProperties(t,r,n){if(n)if(t.properties[n])this.storeInnerProperties(t.properties[n],["pattern","description","i18nClassification","artifactType","minimum","displayName","messages"],r);else{let i=t.aggregations[n]||t;this.storeInnerProperties(i,["description","isViewNode","artifactType","messages"],r)}}isProperty(t){return!t.$ref&&t.type!=="object"&&t.type!=="array"&&!t.anyOf}isAggregation(t){return(t.type===yMt||t.type===qRn)&&!t.$ref}handleAdditionalProperties(t,r){let n=[...Object.keys(t.properties),...Object.keys(t.aggregations)];for(let i of Object.keys(r))if(!n.includes(i)&&t.additionalProperties){let a=t.schema?t.schema.additionalProperties||t.schema.additionalItems:void 0;if(typeof a=="object"){this.parseSchema(t,a,void 0,i,t.path,{});let o=t.aggregations[i];o?.isViewNode&&o.description&&delete o.description}}}readAdvancedPropertiesData(t,r){if(this.handleAdditionalProperties(t,r),t&&t.type==="Array"&&t.schema){let n=t.schema,i=this.getSchemaArrayItem(n);if(i&&Array.isArray(r))for(let a=0;a<r.length;a++)this.parseSchema(t,i,void 0,a.toString(),t.path,{})}for(let n in t.aggregations){let i=t.aggregations[n].union?.originalNames||[n];for(let a of i)typeof r=="object"&&a in r&&this.readAdvancedPropertiesData(t.aggregations[n],r[a])}}readPropertiesData(t,r){let n=Object.keys(t.properties);for(let i in r)n.includes(i)&&(t.properties[i].value=r[i]);for(let i in t.aggregations)i in r&&this.readPropertiesData(t.aggregations[i],r[i])}prepareAggregation(t,r,n,i="Object"){let a=(t||[]).join("/");for(let s of zRn)if(s.fn(a,n,r))return new s.aggregation(void 0,r);let o;if(n?.childClass)o=new n.childClass(void 0,r);else{let s=i==="Object"?Gt:Gj;o=new s(void 0,r)}return t&&vMt.some(s=>vwe(t,s))&&(o.isTable=!0),o}isFreeText(t){let r=n=>n.type==="string"&&!n.enum;return Array.isArray(t)?t.some(r):r(t)}storeInnerProperties(t,r,n){for(let i of r)if(n[i]!==void 0||i==="i18nClassification"&&i in n){if(!this.isCorrectSchemaProperty(i,n[i])){Nt.error(vt.t("SCHEMA_PARSING_ERROR_UNEXPECTED_VALUE",{name:i,value:JSON.stringify(n[i])}));return}t[i]=n[i]}}getSchemaArrayItem(t){let r=Array.isArray(t.items)?t.additionalItems:t.items;return typeof r=="object"?r:void 0}updateArrayFormSchema(t){let r=this.getSchemaArrayItem(t.schema||{});if(typeof r=="object"){let n=this.prepareAggregation();t.isAtomic=!!r.type,this.parseSchema(n,r,void 0,t.isAtomic?"":void 0,t.path,{}),Object.keys(n.properties).length&&(t.formSchema=n)}(!t.formSchema||!Object.keys(t.formSchema.properties).length)&&(t.schemaCreationForms=[])}updateFormSchema(t,r){if(t instanceof Gj)this.updateArrayFormSchema(t);else if(r&&t.additionalProperties?.aggregations[r]){let n=this.prepareAggregation();this.parseSchema(n,t.additionalProperties.aggregations[r].schema||{},void 0,void 0,t.path,{}),Object.keys(n.properties).length&&(t.formSchema=n)}else if(typeof t.schema?.additionalProperties=="object"&&this.isSchemaAtomic(t.schema?.additionalProperties)){t.isAtomic=!0,t.isTable=!0;let n=this.prepareAggregation();this.parseSchema(n,t.schema.additionalProperties,void 0,"",t.path,{}),Object.keys(n.properties).length&&(t.formSchema=n)}}updateViewNodes(t){for(let r in t.aggregations){let n=t.aggregations[r];this.updateViewNodes(n)&&!t.isViewNode&&(t.isViewNode=!0)}return t.isViewNode||!1}isCorrectSchemaProperty(t,r){let n=!0;switch(t){case"description":case"pattern":case"i18nClassification":{n=r===void 0||typeof r=="string";break}case"isViewNode":{n=r===void 0||typeof r=="boolean";break}}return n}propertySorter(t,r,n){let i=t[r].propertyIndex!==void 0?t[r].propertyIndex:0,a=t[n].propertyIndex!==void 0?t[n].propertyIndex:0;return i===a?0:i>a?1:-1}afterInit(t){if(this.pageType===kD.PageType.FPMCustomPage){let r=new Av(void 0,void 0);typeof this.data.$filePath=="string"&&(r.setFilePath(this.data.$filePath),r.annotationNodeId=t.nodes[0]?.nodeId),r.aggregations=this.root.aggregations,this.root.aggregations={macros:r}}}isSchemaAtomic(t){let r=["string","number","boolean"];return typeof t=="object"&&typeof t.type=="string"&&r.includes(t.type)}};var TMt=dt(Pc());var GRn="True",KRn="False",YRn=[CX,X$t];function WRn(e){return`outline-node${e.replace(/\//g,"-")}`}function xMt(e,t,r,n){return{schemaPath:n,artifactType:r.artifactType,description:r.description??"",name:e,displayName:t,type:"string",value:r.value,schema:r.schema??{}}}var _Mt=e=>!Number.isNaN(e)&&!Number.isNaN(e-0),OMt=e=>{let t=[];t.push({key:"",text:""});for(let r of e){let n=r;typeof r=="boolean"?(n=r?GRn:KRn,t.push({key:r,text:n})):typeof r=="string"?_Mt(parseFloat(r))?t.push({key:parseFloat(r),text:r?.toString()}):t.push({key:r,text:r}):typeof r=="number"&&_Mt(r)&&t.push({key:r,text:r?.toString()})}return t};function XRn(e,t){if(t.enum||t.oneOf){let r=[];t.enum?r=OMt(t.enum):t.oneOf&&(r=t.oneOf.map(n=>{let i=n.const;return{key:n.const,text:i}}),r.unshift({key:"",text:"",reset:!0})),e.options=r}}function JRn(e,t,r,n){let i=r.schema.type,a=xMt(e,t,r,n);switch(i){case"string":a.type="string",XRn(a,r.schema);break;case"number":{a.type="number";break}case"boolean":{a.type="boolean",a.options=[{key:void 0,text:""},{key:!0,text:"True"},{key:!1,text:"False"}];break}default:{r.schema.enum?OMt(r.schema.enum):Nt.warn(`Unhandled property: ${JSON.stringify(r)}`);break}}return a}function SMt(e,t=[]){let r=[],n=Object.keys(e.properties);n.length&&n.forEach(i=>{let a=e.properties[i],o=e.path.concat(i),s=JRn(i,a.name,a,o);s&&r.push(s)});for(let i in e.aggregations){let a=e.aggregations[i];if(a.isViewNode)continue;let o=xMt(i,a.name??i,a,a.path);o.type="object";let s=SMt(a,[...t,e]);s.length&&(o.properties=s),r.push(o)}return r}function AMt(e,t){let{text:r,level:n,model:i}=t,{path:a}=t,o=[],s=e.getAggregationKeys(!0),c=WRn(e===i.root?"root-node":`${a}-node`);e.virtual&&i.pageType===TMt.PageTypeV4.FPMCustomPage&&(a="");for(let l of s){let p=a+"/"+l,f=e.aggregations[l],d=f.getDisplayName(),h=AMt(f,{...t,level:n+1,path:p,text:d});o.push(h)}let u=e.annotationNodeId;return!u&&(e instanceof qE||e instanceof YO)&&(u=[]),{id:c,path:e.path.map(l=>l),children:o,text:r,additionalText:e.additionalText,moveProps:ZRn(i,e),title:e.getTechnicalName(),properties:SMt(e),annotationNodeId:u,type:eLn(e),value:e.value,schema:e.schema??{}}}function ZRn(e,t){if(e.root!==t){let n={movable:t.sortableItem==="Enabled"&&!0,allowedParents:QRn(e.root,t),allowedChildTypes:t.sortableList&&t.sortableCollection?[t.sortableCollection]:void 0,type:t.sortableCollection};return t.sortableItem==="Excluded"&&(n.dropRestricted=!0),n}}function QRn(e,t){let r;if(t.custom){let n=t.parent?.getAllowedDropRange(t);r=[],t.parent&&n&&r.push({path:t.parent.path,allowedRanges:n})}else if(t.dropUINodes){let n=e.findAllowedDropAggregations(t);YRn.some(i=>t.name?.startsWith(i))&&(n=n.filter(i=>!UO(i.path,["footer","actions"]))),r=n.map(i=>({path:i.path,allowedRanges:i.range}))}return r}function eLn(e){let t;return e.custom?e instanceof zO?t="customAction":e instanceof GO?t="customColumn":e instanceof RD?t="customFilterField":e instanceof Jm&&(t="customSection"):e.path.length===0?t="rootNode":e instanceof YO&&(t="views"),t}function Swe(e,t,r,n){let i=new KX("Root",r,t,e,n??{dynamicNodes:{},nodes:[]}),a=AMt(i.root,{level:0,path:"",text:i.name,model:i});return a.root=!0,a.schema=i.schema,a}function YX(e,t){for(let r of e){if(UO(r.path,t))return{node:r};for(let i of r.properties){if(UO(i.schemaPath,t))return{property:i};let a=CMt(i,t);if(a)return{node:r,property:a}}let n=r.children?YX(r.children,t):void 0;if(n)return n}}function CMt(e,t){if(e.properties)for(let r of e.properties){if(UO(r.schemaPath,t))return r;let n=CMt(r,t);if(n)return n}}var ch=dt(Pc()),zf=require("node:path"),Nwe=dt(Zd());var sh=dt(Zd()),Awe=dt(Pc()),Cwe=require("node:fs"),Wj=require("node:fs/promises"),wwe=require("node:path");function wMt(e){let t=e.getAppId(),r=e.project,n;if(t===void 0){let i=Object.keys(r.apps);n=r.apps[i[0]].mainService}else{let i=r.apps[t];if(!i)throw new Error("ERROR_INVALID_APP_ID");n=i.mainService}return n??"mainService"}async function $D(e){let t=wMt(e);return(e.projectType==="CAPJava"||e.projectType==="CAPNodejs")&&(t=await(0,sh.getCapServiceName)(e.project.root,e.app?.services?.[t].uri??"")),t}async function PMt(e){let t=[],r=wMt(e),n=e.app?.services?.[r];if(!n)return[];if(n.uri&&(e.projectType==="CAPJava"||e.projectType==="CAPNodejs")){let i=n?.uri??"";if(i){let a=await(0,sh.readCapServiceMetadataEdmx)(e.root,i);t.push({fileContent:a,dataSourceUri:i})}}else{if(n.local){let a=await(0,Wj.readFile)(n.local);t.push({dataSourceUri:n.local,fileContent:a.toString()})}let{annotations:i=[]}=n;for(let a of i)if(a.local){let o=await(0,Wj.readFile)(a.local);t.push({dataSourceUri:a.local,fileContent:o.toString()})}}return t}async function Xj(e){let t=await(0,sh.getWebappPath)(e.app.appRoot),r=(0,wwe.join)(t,sh.FileName.Manifest);if(!(0,Cwe.existsSync)(r))return;let n=await(0,Wj.readFile)(r);return JSON.parse(n.toString())}async function Pwe(e){let t=await Xj(e),r=t?(0,sh.getMinimumUI5Version)(t):void 0;return r!==void 0&&Number.isNaN(parseFloat(r))&&(r="latest"),r??"latest"}async function DMt(e){let t,r=(0,wwe.join)(e,sh.FileName.Package);if((0,Cwe.existsSync)(r)){let n=await(0,Wj.readFile)(r);try{t=JSON.parse(n.toString())}catch(i){Nt.error(String(i))}}return t?.sapuxLayer==="VENDOR"?Awe.FlexChangeLayer.Vendor:Awe.FlexChangeLayer.Customer}var WO=require("node:path"),Dwe=require("node:fs"),WX=require("node:fs/promises"),IMt=dt(iK()),RMt=dt(YK());function tLn(e){return e??(0,RMt.create)((0,IMt.create)())}function LMt(e,t,r){let n={},i=oLn(t),a=nLn(r);if(a)for(;a.length>0;){let o=a.pop();sLn(i,o)||o.content.newValue!==null&&(n[(0,WO.join)(e,`${o.fileName}.change`)]=o)}return aLn(e,i,n),n}async function kMt(e,t,r){r=tLn(r),await rLn(e,t,r),Object.keys(t).length>0&&!(0,Dwe.existsSync)((0,WO.join)(e))&&await(0,WX.mkdir)(e);for(let n in t){let i="";(0,Dwe.existsSync)(n)&&(i=await r.read(n));let a=JSON.stringify(t[n],void 0,4);a!==i&&await r.write(n,a)}return r}async function rLn(e,t,r){let n=Object.keys(t);try{let i=await(0,WX.readdir)(e);i=i.map(o=>(0,WO.join)(e,o));let a=i.filter(o=>!n.includes(o));for(let o of a)try{await r.delete(o)}catch(s){Nt.error(`Failed to delete deprecated file "${o}": ${s}`);continue}}catch(i){Nt.error(`Error while removing deprecated flex change files: ${i}`);return}}function nLn(e=[]){let t=[];for(let r of e){let n=$Mt(r);n&&t.push(n)}return t}function $Mt(e){try{return JSON.parse(e)}catch(t){Nt.error(`Error while prsing flex change file: ${t}`)}}function NMt(e,t){return(e.changeType==="propertyChange"||e.changeType==="propertyBindingChange")&&e.changeType===t.changeType&&e.content?.property===t.content?.property&&e.selector?.id===t.selector?.id}function iLn(e,t){for(let r=e.length-1;r>=0;r--){let n=e[r].change;t.selector.id===n.selector.id&&t.content.property===n.content.property&&e.splice(r,1)}}function aLn(e,t,r){if(t)for(let n of t)r[(0,WO.join)(e,`${n.filename}`)]=n.change}function oLn(e){let t=[];for(let r in e){let n=$Mt(e[r]);n&&t.push({filename:r,change:n})}return t}function sLn(e,t){let r=e?.filter(n=>NMt(t,n.change));if(r&&r.length>0)if(r.length===1){let n=r[0].change;if(n.content.newValue!==void 0&&t.content.newValue!==void 0&&n.content.newValue===t.content.newValue||n.content.newBinding!==void 0&&t.content.newBinding!==void 0&&n.content.newBinding===t.content.newBinding)return!0;t.fileName=(0,WO.parse)(r[0]?.filename).name;let i=e.findIndex(a=>NMt(t,a.change));e.splice(i,1)}else iLn(e,t);return!1}var jo=class{appAccess;constructor(t){this.appAccess=t}async getSpecification(){return this.appAccess.getSpecification()}getAppId(t){return t["sap.app"]?.id??""}async getVirtualFiles(){let t=await Xj(this.appAccess);if(!t)return[];let r=await this.getSpecification(),n=await PMt(this.appAccess),i=await(0,Nwe.readFlexChanges)(this.appAccess.app.changes);return r.importProject({manifest:t,annotations:n,flex:Object.values(i)})}async readApp(t){t??=await this.getVirtualFiles();let r=t.find(o=>o.dataSourceUri===ch.FileName.App),n=JSON.parse(r?.fileContent??"{}"),i=(0,zf.join)(".schemas",(0,zf.basename)((0,zf.join)(n?.$schema??""))),a=t.find(o=>(0,zf.join)(o.dataSourceUri)===i);if(a){let o=JSON.parse(a.fileContent);o.properties?.settings&&(o.properties.settings.isViewNode=!0),a.fileContent=JSON.stringify(o)}return{config:n,schema:a?.fileContent??"{}"}}async readPageData(t){try{let r=await this.getVirtualFiles(),n=(0,zf.join)(ch.DirName.Pages,`${t}.json`),i=r.find(c=>(0,zf.join)(c.dataSourceUri)===n),a=i?.fileContent?JSON.parse(i.fileContent):void 0,o=(0,zf.join)(".schemas",(0,zf.basename)((0,zf.join)(a?.$schema??""))),s=r.find(c=>(0,zf.join)(c.dataSourceUri)===o);if(a&&s){let u=(await this.readApp(r)).config.pages?.[t];if(u){let l=u.pageType;return{pageId:t,pageType:l??ch.PageTypeV4.ListReport,config:a,page:u,schema:s.fileContent,entitySet:u.entitySet,entityType:"entityType"in u&&typeof u.entityType=="string"?u.entityType:void 0,contextPath:u.contextPath}}}}catch(r){Nt.error(String(r))}}async writePage(t){let r=await Xj(this.appAccess);if(!r)return;let n=await this.getSpecification(),a={[t.pageType===ch.PageTypeV4.ObjectPage?ch.SchemaType.ObjectPage:ch.SchemaType.ListReport]:{appId:this.getAppId(r),jsonSchema:JSON.parse(t.schema),manifest:r,page:{...t.page,name:t.pageId,config:t.config}}},o=await this.getExportConfigParameters(r,a),s=n.exportConfig(o);s.manifestChangeIndicator==="Updated"&&await this.appAccess.updateManifestJSON(s.manifest);let c=this.appAccess.app.changes,u=await(0,Nwe.readFlexChanges)(this.appAccess.app.changes),l=LMt(c,u,s.flexChanges),p=await kMt(c,l);return await p.commit(()=>{}),s.flexChanges=Object.keys(p.dump()),s}async writeApp(t){let{config:r,schema:n}=t,i=await Xj(this.appAccess);if(!i)return;let a=await this.getSpecification(),o={[ch.SchemaType.Application]:{application:r,manifest:i,jsonSchema:JSON.parse(n)}},s=await this.getExportConfigParameters(i,o),c=a.exportConfig(s);return await this.appAccess.updateManifestJSON(c.manifest),c}async writeFPM(t){t.data&&(t.data.minUI5Version=await Pwe(this.appAccess));let n=await(await this.getSpecification()).generateCustomExtension(t);return await n?.commit(()=>{}),n?Object.keys(n.dump()):[]}async getExportConfigParameters(t,r){let i=t["sap.app"]?.dataSources?.mainService?.settings?.odataVersion==="2.0"?{v2:r}:{v4:r};return i.ui5Version=await Pwe(this.appAccess),i.layer=await DMt(this.appAccess.root),i}};function Iwe(e,t,r,n=!1){cLn(e,t,r!==void 0,(i,a)=>{if(typeof i!="object"||i===null)return;let o=i;r!==void 0?n&&Array.isArray(o[a])?o[a].push(r):o[a]=n?[r]:r:Array.isArray(o)?o.splice(typeof a=="string"?Number.parseInt(a,10):a,1):delete o[a]})}function cLn(e,t,r,n){let i=e;for(let a=0;a<t.length;a++)if(t[a]!==void 0){if(a===t.length-1&&n(i,t[a]),i[t[a]]===void 0&&r){let o=t[a+1]!==void 0&&typeof t[a+1]=="number";i[t[a]]=o?[]:{}}if(i=i[t[a]],!i)break}}var Cv=class{constructor(t,r){this.appAccess=t;this.pageId=r;this.ftfsIO=new jo(t)}ftfsIO;async getPageTree(t){let r={children:[],path:[],properties:[],text:"",schema:{}};if(this.pageId){let n=await this.ftfsIO.readPageData(this.pageId);n&&(r=Swe(n.schema,n.config,n.pageType,t))}else{let n=await this.ftfsIO.readApp();n&&(r=Swe(n.schema,n.config,MMt.PageTypeV4.ListReport))}return r}async changeProperty(t,r){if(this.pageId){let n=await this.ftfsIO.readPageData(this.pageId);if(n)return Iwe(n.config,t,r),this.ftfsIO.writePage(n)}else{let n=await this.ftfsIO.readApp();return Iwe(n.config,t,r),this.ftfsIO.writeApp(n)}}async getApplication(){return this.ftfsIO.readApp()}async updateApplication(t){await this.ftfsIO.writeApp(t)}};var xl=dt(Pc());var r5t=require("node:path");var Q6t=dt(A6t()),e5t=dt(Zd()),t5t=dt(Z6t()),See=class{constructor(t){this.options=t}metadataService;annotationService;nodes=[];nodesMap=new Map;namespace="";async loadMetadata(t=!1){if(!t&&this.metadataService)return;let{project:r,serviceName:n,appName:i}=this.options,a=await(0,e5t.getProject)(r.root);this.annotationService=await Q6t.FioriAnnotationService.createService(a,n,i),await this.annotationService.sync(),this.metadataService=this.annotationService.getMetadataService(),this.namespace=[...this.metadataService.getNamespaces()][0],this.metadataService.visitMetadataElements(this.visitMdElement.bind(this))}visitMdElement(t){let{path:r,name:n}=t,i=this.metadataService?.getEdmTargetKinds(r)[0]||"",a={path:r,name:n,mdElement:t,kind:i};this.nodes?.push(a),this.nodesMap.set(r,a)}async getNamespace(){return await this.loadMetadata(),this.namespace}async getAllowedEntities(t=!1){if(await this.loadMetadata(t),!this.annotationService)return[];let r=[],n=this.annotationService.getSchema(),i=(0,t5t.convert)(n);for(let a of i.entitySets)r.push({entitySet:a.name,entityType:a.entityType.name,navigations:a.entityType.navigationProperties.filter(o=>o.isCollection).map(o=>{let s=o.targetType,c=i.entitySets.find(u=>u.entityTypeName===s.name);return{name:o.name,fullyQualifiedName:o.fullyQualifiedName,entitySet:c?.name??s.name}})});return r}async getAllowedNavigations(t,r,n=!1){return(await this.getAllowedEntities(n)).find(a=>a.entitySet===t||a.entityType===r)?.navigations??[]}};var YRe=new Map;function Y9n(e){return(0,r5t.join)(e.project.root,e.appName,e.serviceName)}async function WRe(e){let t=Y9n(e);YRe.has(t)||YRe.set(t,new See(e));let r=YRe.get(t);if(!r)throw new Error(`No service: '${t}'`);return r}var id=dt(Pc()),W9n=new Map([[id.PageTypeV4.ListReport,"List"],[id.PageTypeV4.ObjectPage,id.PageTypeV4.ObjectPage],[id.PageTypeV4.CustomPage,"Page"],[id.PageTypeV4.FPMCustomPage,"Page"],[id.PageTypeV4.AnalyticalListPage,"ALP"]]);function X9n(e,t,r){let n="",i=[];if(e.pageType===id.PageTypeV4.CustomPage||e.pageType===id.PageTypeV4.FPMCustomPage){let o=(e.viewName??"").split(".");n=o[o.length-1]}else n=e.contextPath?e.contextPath.slice(1).replace(/\//g,"_"):e.entitySet;return i=[n],t&&r&&(!e.contextPath||e.contextPath.indexOf(r)===-1)&&i.push(r),i[i.length-1]+=W9n.get(e.pageType),i}function J9n(e){let t=[];return t.push(e.pageType),e.entitySet&&t.push(e.entitySet),t}function XRe(e,t,r,n,i){let a=[];n===id.FioriElementsVersion.v2?a=J9n(e):a=X9n(e,t,i);let o=a.join("_"),s=r.map(u=>u.pageId),c=0;for(;s.indexOf(o)>-1;)o+=c.toString(),c++;return o}function Tq(e){return e.config.target?.fioriElements??id.FioriElementsVersion.v4}var i5t=dt(Zd()),a5t=require("node:path");var n5t="1.136.7",L1="generate-fiori-ui-application-cap",m_="add-page",tb="delete-page",Aee="create-controller-extension",Cee=/^[A-Za-z][A-Za-z0-9_-]*$/;var g_=class{serviceName;appData;appId;applicationAccess;params;version;constructor({params:t,applicationAccess:r,appId:n,serviceName:i,appData:a}){this.params=t,this.serviceName=i,this.appData=a,this.appId=n,this.applicationAccess=r,this.version=Tq(a)}getAllowedNavigationsOutput(t){return t.map(r=>r.name).join(", ")}getMissingNavigationMessage(t,r,n){let i="";switch(t){case 1:{i="page does not have valid navigation for add";break}case 2:{i=`provided 'navigation' was not found. ${n} has following navigations available: ${this.getAllowedNavigationsOutput(r)}`;break}case 3:{i="provide 'entitySet' for very first page";break}case 4:{i=`provided 'entitySet' was not found. Following entitySets available: ${this.getAllowedNavigationsOutput(r)}`;break}}return i}calculateContextPath(t,r,n){let i;return!t||t.pageType===xl.PageTypeV4.ListReport?i=`/${n}`:t.contextPath?i=r&&t.routePattern!==":?query:"?`${t.contextPath}/${r}`:`/${n}`:t.entitySet&&(i=this.calculateContextPathBasedOnEntitySet(t,r)),i}calculateContextPathBasedOnEntitySet(t,r){let n,a=t.routePattern?.replace(":?query:","").replace(/\({[^}]*}\)/g,"");return a?n=r&&r!==""?`/${a}/${r}`:`/${a}`:n=r&&r!==""?`/${t.entitySet}/${r}`:`/${t.entitySet}`,n}createErrorResponse(t){return{functionalityId:m_,status:"Failed",message:t,parameters:[],appPath:this.params.appPath,changes:[],timestamp:new Date().toISOString()}}async validatePageCreationInput(t,r,n){if(r.length&&!t.parent)return this.createErrorResponse('Provide "parentPage" for page creation');if(t.pageType===xl.PageTypeV4.CustomPage){let i=this.validateCustomPageViewName(n);if(i)return i}return null}validateCustomPageViewName(t){let r=".view.xml",n=t?.endsWith(r)?t.slice(0,-r.length):t;return n?/^[a-z][a-z0-9_-]*$/i.exec(n)?null:this.createErrorResponse("'viewName' must not contain spaces, must start with an upper-case letter, and may contain letters, digits, and underscores."):this.createErrorResponse('Provide "viewName" for CustomPage')}async validateNavigationInput(t,r,n,i=[]){if(i.length&&!t)return this.createErrorResponse('provided "parentPage" was not found');let a=await this.getAllowedNavigations(t);if(t&&!a.length){let s=this.getMissingNavigationMessage(1,a);return this.createErrorResponse(s)}let o=this.findTargetNavigation(a,r,n);if(t&&!o){let s=this.getMissingNavigationMessage(2,a,t.pageId);return this.createErrorResponse(s)}if(!t&&!n){let s=this.getMissingNavigationMessage(3,a);return this.createErrorResponse(s)}if(!t&&!o){let s=this.getMissingNavigationMessage(4,a);return this.createErrorResponse(s)}return null}findTargetNavigation(t,r,n){return t.find(i=>{let a=i.name.toLocaleLowerCase();return a===r?.toLocaleLowerCase()||a===n?.toLocaleLowerCase()})}async generatePageV4(t,r,n,i,a,o){let s=r?{sourceEntity:r.entitySet,sourcePage:r.pageId,navEntity:n?.name,navKey:!0}:void 0,c=this.calculateContextPath(r,n?.name,n?.entitySet??o),u=XRe({entitySet:n?.entitySet??o??"",pageId:"",pageType:t.pageType,contextPath:c,viewName:a},r?.pageId,i,this.version,n?.name),l={id:u,entity:n?.entitySet??o??"",navigation:s,contextPath:c,name:t.pageType===xl.PageTypeV4.CustomPage?a:void 0},p=await this.writeFPM(t.pageType,l,a);return{pageID:u,changes:p}}async generatePageV2(t,r,n,i,a,o){let s=this.appData.config;s.pages||(s.pages={});let c=XRe({entitySet:n?.entitySet??o??"",pageId:"",pageType:t.pageType,contextPath:"",viewName:a},r?.pageId,i,this.version,n?.name);s.pages[c]={pageType:t.pageType,entitySet:n?.entitySet??o,navigationProperty:n?.name,navigation:{}};let u=r?s.pages[r.pageId]:void 0;if(u){u.navigation||(u.navigation={});let p=u.entitySet??"";u.navigation[c]=n?.name?`${p}.${n.name}`:p}return await new jo(this.applicationAccess).writeApp(this.appData),{pageID:c,changes:[this.applicationAccess.app.manifest]}}async writeFPM(t,r,n){let i=new jo(this.applicationAccess),a=xl.CustomExtensionType.ListReport;t===xl.PageTypeV4.ObjectPage&&(a=xl.CustomExtensionType.ObjectPage),t===xl.PageTypeV4.CustomPage&&n&&(a=xl.CustomExtensionType.CustomPage);let o=XY(i5t.DirName.View);return i.writeFPM({customExtension:a,basePath:(0,a5t.join)(this.applicationAccess.project.root,this.appId),data:{...r,folder:o}})}deleteNavigationLinks(t,r){if(t){for(let n in t)if(this.findPageByNavigation(t,n)===r){delete t[n];break}}}findPageByNavigation(t,r){let n=t?.[r];return typeof n=="string"?r:n?.route}deletePageRecursively(t,r){if(!r)return;let{pages:n}=t,i=t.settings??{};if(n?.[r]){let a=n?.[r];delete n[r];let o=`${a.pageType}#${r}`;if(i.controllerExtensions?.[o]&&delete i.controllerExtensions[o],a.navigation)for(let s in a.navigation){let c=this.findPageByNavigation(a.navigation,s);this.deletePageRecursively(t,c)}}}getPages(){let{config:t}=this.appData,{pages:r={}}=t,n=[];for(let i in r){let a=r[i];n.push({pageId:i,pageType:a.pageType??xl.PageTypeV4.ListReport,entitySet:a.entitySet??"",contextPath:a.contextPath,routePattern:"routePattern"in a&&typeof a.routePattern=="string"?a.routePattern:void 0})}return n}async getAllowedNavigations(t,r=!1){return!t||t?.pageType==="ListReport"?this.getRootPageNavigationOptions(r):(await(await WRe({appName:this.appId,project:this.applicationAccess.project,serviceName:this.serviceName})).getAllowedNavigations(t?.entitySet,t?.entitySet,r)).map(i=>({...i,isNavigation:!0}))}async getRootPageNavigationOptions(t=!1){return(await(await WRe({appName:this.appId,project:this.applicationAccess.project,serviceName:this.serviceName})).getAllowedEntities(t)).map(i=>({entitySet:i.entitySet,name:i.entitySet}))}async getCreationNavigationOptions(){let t={navigations:{}},r=this.getPages();if(r.length){let n=!0;for(let i of r)t.navigations[i.pageId]=await this.getAllowedNavigations(i,n),n=!1}else t.entities=await this.getAllowedNavigations();return t}async createPage(t){let{parent:r,navigation:n,pageType:i,entitySet:a}=t,o=t.pageType===xl.PageTypeV4.CustomPage?t.viewName:void 0,s=this.getPages(),c=await this.validatePageCreationInput(t,s,o);if(c)return c;let u=s.find(v=>v.pageId===r),l=await this.validateNavigationInput(u,n,a,s);if(l)return l;let p=await this.getAllowedNavigations(u),f=this.findTargetNavigation(p,n,a),d=this.version===xl.FioriElementsVersion.v2?this.generatePageV2:this.generatePageV4,{pageID:h,changes:m}=await d.call(this,t,u,f,s,o,a);return{functionalityId:m_,status:m.length?"success":"skipped",message:m.length?`Page with id '${h}' of type '${i}' was created successfully in application '${this.appId}'`:`No changes were made for '${i}'`,parameters:[],appPath:this.params.appPath,changes:m,timestamp:new Date().toISOString()}}async deletePage(t){let{pageId:r}=t,n=structuredClone(this.appData),{config:i}=n,a=!1,{pages:o={}}=i;if(o?.[r]){for(let s in o)o[s].navigation&&this.deleteNavigationLinks(o[s].navigation,r);this.deletePageRecursively(i,r),a=!0}return Object.keys(o).length===0&&delete i.home,a?(await new jo(this.applicationAccess).writeApp(n),{functionalityId:tb,status:"success",message:`Page with id '${r}' was deleted successfully in application '${this.appId}'`,parameters:[],appPath:this.params.appPath,changes:[],timestamp:new Date().toISOString()}):{functionalityId:tb,status:"unchanged",message:`Page with id '${r}' was not found in application '${this.appId}'`,parameters:[],appPath:this.params.appPath,changes:[],timestamp:new Date().toISOString()}}};var ad=dt(Pc());var o5t=Fn([ad.PageTypeV4.ListReport,ad.PageTypeV4.ObjectPage,ad.PageTypeV4.CustomPage]),s5t=Fn([ad.PageTypeV4.ObjectPage]),Z9n=(e,t)=>{let r=t===ad.FioriElementsVersion.v2?s5t:o5t;return Ae({pageType:r.describe("Type of page to be created. First try to extract page type from user input, if not possible suggest content defined in options."),entitySet:Fn(e.map(n=>n.name)).describe("Entity set for the new page. First try to extract entity from user input, if not possible suggest content defined in options.")})},Q9n=(e,t,r)=>{let n=r===ad.FioriElementsVersion.v2?s5t:o5t,i={parentPage:ht(e).describe("Parent page is id/name of parent page. First try to extract parent page from user input, if not possible suggest content defined in options"),pageNavigation:Fn(t.map(o=>o.name)),pageType:n.describe("Type of page to be created. First try to extract page type from user input, if not possible suggest content defined in options.")};r===ad.FioriElementsVersion.v4&&(i.pageViewName=re().regex(Cee).optional().describe('Required if pageType is "CustomPage". Name of custom view file. First try to extract view name from user input that satisfies the pattern, if not possible ask user to provide view name'));let a=Ae(i);return r===ad.FioriElementsVersion.v4&&(a=a.refine(o=>!(o.pageType===ad.PageTypeV4.CustomPage&&!o.pageViewName),{path:["pageViewName"],message:"A pageViewName must be provided when using PageTypeV4.CustomPage"})),a};function wee(e,t=[],r=ad.FioriElementsVersion.v4){let n=Object.keys(e);return n.length?hn(n.map(i=>Q9n(i,e[i],r))):Z9n(t,r)}function Pee(e=[]){let t=e.map(r=>r.pageId);return Ae({pageId:Fn(t).describe("Page id to be deleted. First try to extract page id from user input, if not possible suggest content defined in options")})}var c5t=dt(Pc());var xq={functionalityId:m_,name:"Add new page to application by updating manifest.json",description:"Create new fiori elements page like ListReport, ObjectPage, CustomPage",parameters:Oa(wee({}))};async function eHn(e){let{appPath:t}=e,r=await fu(t);if(!r?.applicationAccess)return{...xq,parameters:{},name:"Invalid Project Root or Application Path",description:`To add a new page, provide a valid project root or application path. "${t}" is not valid`};let{appId:n,applicationAccess:i}=r,o=await new jo(i).readApp(),s=await $D(i),u=await new g_({params:e,applicationAccess:i,serviceName:s,appId:n,appData:o}).getCreationNavigationOptions();return{...xq,parameters:Oa(wee(u.navigations,u.entities,Tq(o)))}}async function tHn(e){let{appPath:t,parameters:r}=e,n=await fu(t);if(!n?.applicationAccess)return{functionalityId:m_,status:"Failed",message:`Project root not found for app path: ${t}`,parameters:[],appPath:t,changes:[],timestamp:new Date().toISOString()};let{appId:i,applicationAccess:a}=n,s=await new jo(a).readApp(),c=await $D(a),u=new g_({params:e,applicationAccess:a,serviceName:c,appId:i,appData:s}),l=await u.getCreationNavigationOptions(),p=wee(l.navigations,l.entities,Tq(s)),f=wm(p,r),d=f.pageType??c5t.PageTypeV4.ObjectPage,h="parentPage"in f?f.parentPage:void 0,m="entitySet"in f?f.entitySet?.toString():void 0,v="pageNavigation"in f?f.pageNavigation.toString():void 0,_="pageViewName"in f&&f.pageViewName&&typeof f.pageViewName=="string"?f.pageViewName:"";return u.createPage({pageType:d,parent:h,navigation:v,entitySet:m,viewName:_})}var JRe={getFunctionalityDetails:eHn,executeFunctionality:tHn};var Dee={functionalityId:tb,name:"Delete page from application by updating manifest.json",description:"Remove existing fiori elements page from the application",parameters:Oa(Pee())};async function rHn(e){let{appPath:t}=e,r=await fu(t);if(!r?.applicationAccess)return{functionalityId:tb,name:"Invalid Project Root or Application Path",description:`To delete a page, provide a valid project root or application path. "${t}" is not valid`,parameters:{}};let{appId:n,applicationAccess:i}=r,o=await new jo(i).readApp(),s=await $D(i),c=new g_({params:e,applicationAccess:i,serviceName:s,appId:n,appData:o});return{...Dee,parameters:Oa(Pee(c.getPages()))}}async function nHn(e){let{appPath:t,parameters:r}=e,n=await fu(t);if(!n?.applicationAccess)return{functionalityId:tb,status:"Failed",message:`Project root not found for app path: ${t}`,parameters:[],appPath:t,changes:[],timestamp:new Date().toISOString()};let{appId:i,applicationAccess:a}=n,s=await new jo(a).readApp(),c=await $D(a),u=new g_({params:e,applicationAccess:a,serviceName:c,appId:i,appData:s}),l=Pee(u.getPages()),p=wm(l,r);return u.deletePage({pageId:p.pageId})}var ZRe={getFunctionalityDetails:rHn,executeFunctionality:nHn};var Iee=dt(Pc());var u5t=require("node:path");var Nee=Ae({pageType:Fn(["ListReport","ObjectPage"]).describe("Type of page").default("ListReport"),controllerName:re().regex(Cee).describe("Name of new controller extension file")});async function QRe(e){let t=[];if(e){let r=await e.readApp();t=Object.keys(r.config.pages??{})}return t.length>0?Nee.extend({pageId:Fn(t).optional().describe("If controller extension should be assigned for specific page, then pageId should be provided")}):Nee}var eLe={functionalityId:Aee,name:"Add new controller extension by creating javascript or typescript file and updates manifest.json with entry",description:"Add new controller extension by creating javascript or typescript file and updates manifest.json with entry. Controller extensions allow users to extensiate default behaviour with custom controllers code.",parameters:Oa(Nee)};async function iHn(e){let t=await fu(e.appPath);if(!t?.applicationAccess)throw new Error("Invalid Project Root or Application Path");let r=new jo(t.applicationAccess);return{...eLe,parameters:Oa(await QRe(r))}}async function aHn(e){let{parameters:t,appPath:r}=e,n=await fu(r),i=[];if(n?.applicationAccess){let{appId:a,root:o}=n,s=new jo(n.applicationAccess),c=await QRe(s),u=wm(c,t),{pageId:l,controllerName:p,pageType:f}=u,d=await oHn(s,f,l);if(d&&typeof d=="string"){let h={pageId:typeof l=="string"?l:void 0,pageType:d};i=await s.writeFPM({customExtension:Iee.CustomExtensionType.ControllerExtension,basePath:(0,u5t.join)(o,a),data:{extension:h,folder:XY(Iee.DirName.Controller),name:p}})}}return{functionalityId:e.functionalityId,status:i.length?"success":"skipped",message:i.length?"Controller extension is created":"Controller extension is not created",parameters:t,appPath:r,changes:i,timestamp:new Date().toISOString()}}async function oHn(e,t,r){if(r&&typeof r=="string"&&(t=(await e.readApp()).config.pages?.[r]?.pageType),t&&typeof t=="string")return t}var l5t={getFunctionalityDetails:iHn,executeFunctionality:aHn};var UN=require("node:fs"),Oq=require("node:path");var k1={version:"0.2",telemetryData:{generationSourceName:$2.name,generationSourceVersion:$2.version},project:{sapux:!0}},Ree=ht(["FE_FPM","FE_LROP","FE_OVP","FE_ALP","FE_FEOP","FE_WORKLIST","FF_SIMPLE"]).describe("SAP Fiori Elements floor plan type."),Lee=Ae({name:re().describe("Must be lowercase with dashes, e.g., 'sales-order-management'.").regex(/^[a-z0-9-]+$/),title:pt(re()),description:re(),targetFolder:re().describe("Absolute path to the project folder (projectPath)."),ui5Version:re().default(n5t)}),p5t=Ae({servicePath:re().describe("The odata endpoint. If the parameter is not provided, the agent should ask the user for it.").meta({examples:["odata/v4/<servicename>/","odata/v4/MyRiskService/","odata/v4/MyOdataV4Service/","odata/v4/<relative '@path' annotation from service cds file>/","<absolute '@path' annotation from service cds file>/","myAbsolutePathFromServiceCdsFile/"]}),host:Ppe().describe("The host of the OData service. Must be an HTTPS endpoint. If the parameter is not provided, the agent should ask the user for it."),client:pt(re().describe("The client to be used for the OData service.")),metadataFilePath:pt(re().describe("Path to a local metadata.xml file."))}),f5t=Ae({capService:Ae({projectPath:re(),serviceName:re(),serviceCdsPath:re().describe("The path to the service cds file").meta({examples:["srv/service.cds","srv/my-service.cds","path/to/srv/service.cds","path/to/srv/my-service.cds"]}),capType:pt(ht(["Node.js","Java"]))})}),kee=Ae({mainEntity:Ae({entityName:re().describe("The name of the main entity. EntitySet Name attribute in OData Metadata.").meta({examples:["'SalesOrder'","'PurchaseOrderHeader'","'MyEntity'"]})}),generateFormAnnotations:Qi().describe("Whether to generate form annotations for the main entity if none exist.").default(!0),generateLROPAnnotations:Qi().describe("Whether to generate LROP annotations for the main entity if none exist.").default(!0)});var tLe=KT.object({entityConfig:kee,floorplan:Ree,project:Lee,service:p5t}).describe(`The configuration that will be used for the Application UI generation.
1658
+ `;return c}else return{query:r,searchType:"hybrid",results:s.map(c=>({title:c.document.title,category:c.document.category,path:c.document.path,score:c.score,matches:[],excerpt:c.document.metadata?.excerpt,content:c.document.content,uri:`sap-fiori://docs/${c.document.category}/${c.document.id}`})),total:s.length}}catch(i){return Nt.warn(`Embeddings data not available, providing limited search capability: ${i}`),{query:r,searchType:"limited_fallback",error:"Embeddings data not available. Please install @sap-ux/fiori-docs-embeddings for full search capabilities.",results:[],total:0,suggestion:"Try running: npm install -g @sap-ux/fiori-docs-embeddings"}}}var sX=dt(Zd()),sLt=require("node:path");async function WCe(e){let{searchPath:t=[]}=e,n=(await(0,sX.findFioriArtifacts)({wsFolders:t,artifacts:["applications"]})).applications??[];return{applications:await Promise.all(n.map(async i=>{let a=await(0,sX.getProjectType)(i.projectRoot);return{name:i.manifest["sap.app"]?.id??(0,sLt.basename)(i.appRoot),appPath:i.appRoot,projectPath:i.projectRoot,projectType:a,odataVersion:i.manifest["sap.app"]?.dataSources?.mainService?.settings?.odataVersion??"4.0"}}))??[]}}var MMt=dt(Pc());var rr=e=>typeof e=="string",qj=()=>{let e,t,r=new Promise((n,i)=>{e=n,t=i});return r.resolve=e,r.reject=t,r},k$t=e=>e==null?"":""+e,_Rn=(e,t,r)=>{e.forEach(n=>{t[n]&&(r[n]=t[n])})},TRn=/###/g,$$t=e=>e&&e.indexOf("###")>-1?e.replace(TRn,"."):e,M$t=e=>!e||rr(e),Uj=(e,t,r)=>{let n=rr(t)?t.split("."):t,i=0;for(;i<n.length-1;){if(M$t(e))return{};let a=$$t(n[i]);!e[a]&&r&&(e[a]=new r),Object.prototype.hasOwnProperty.call(e,a)?e=e[a]:e={},++i}return M$t(e)?{}:{obj:e,k:$$t(n[i])}},F$t=(e,t,r)=>{let{obj:n,k:i}=Uj(e,t,Object);if(n!==void 0||t.length===1){n[i]=r;return}let a=t[t.length-1],o=t.slice(0,t.length-1),s=Uj(e,o,Object);for(;s.obj===void 0&&o.length;)a=`${o[o.length-1]}.${a}`,o=o.slice(0,o.length-1),s=Uj(e,o,Object),s?.obj&&typeof s.obj[`${s.k}.${a}`]<"u"&&(s.obj=void 0);s.obj[`${s.k}.${a}`]=r},xRn=(e,t,r,n)=>{let{obj:i,k:a}=Uj(e,t,Object);i[a]=i[a]||[],i[a].push(r)},_X=(e,t)=>{let{obj:r,k:n}=Uj(e,t);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},ORn=(e,t,r)=>{let n=_X(e,r);return n!==void 0?n:_X(t,r)},K$t=(e,t,r)=>{for(let n in t)n!=="__proto__"&&n!=="constructor"&&(n in e?rr(e[n])||e[n]instanceof String||rr(t[n])||t[n]instanceof String?r&&(e[n]=t[n]):K$t(e[n],t[n],r):e[n]=t[n]);return e},wD=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),SRn={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"},ARn=e=>rr(e)?e.replace(/[&<>"'\/]/g,t=>SRn[t]):e,awe=class{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){let r=this.regExpMap.get(t);if(r!==void 0)return r;let n=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,n),this.regExpQueue.push(t),n}},CRn=[" ",",","?","!",";"],wRn=new awe(20),PRn=(e,t,r)=>{t=t||"",r=r||"";let n=CRn.filter(o=>t.indexOf(o)<0&&r.indexOf(o)<0);if(n.length===0)return!0;let i=wRn.getRegExp(`(${n.map(o=>o==="?"?"\\?":o).join("|")})`),a=!i.test(e);if(!a){let o=e.indexOf(r);o>0&&!i.test(e.substring(0,o))&&(a=!0)}return a},owe=(e,t,r=".")=>{if(!e)return;if(e[t])return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;let n=t.split(r),i=e;for(let a=0;a<n.length;){if(!i||typeof i!="object")return;let o,s="";for(let c=a;c<n.length;++c)if(c!==a&&(s+=r),s+=n[c],o=i[s],o!==void 0){if(["string","number","boolean"].indexOf(typeof o)>-1&&c<n.length-1)continue;a+=c-a+1;break}i=o}return i},Bj=e=>e?.replace("_","-"),DRn={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console?.[e]?.apply?.(console,t)}},swe=class e{constructor(t,r={}){this.init(t,r)}init(t,r={}){this.prefix=r.prefix||"i18next:",this.logger=t||DRn,this.options=r,this.debug=r.debug}log(...t){return this.forward(t,"log","",!0)}warn(...t){return this.forward(t,"warn","",!0)}error(...t){return this.forward(t,"error","")}deprecate(...t){return this.forward(t,"warn","WARNING DEPRECATED: ",!0)}forward(t,r,n,i){return i&&!this.debug?null:(rr(t[0])&&(t[0]=`${n}${this.prefix} ${t[0]}`),this.logger[r](t))}create(t){return new e(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return t=t||this.options,t.prefix=t.prefix||this.prefix,new e(this.logger,t)}},Wm=new swe,PD=class{constructor(){this.observers={}}on(t,r){return t.split(" ").forEach(n=>{this.observers[n]||(this.observers[n]=new Map);let i=this.observers[n].get(r)||0;this.observers[n].set(r,i+1)}),this}off(t,r){if(this.observers[t]){if(!r){delete this.observers[t];return}this.observers[t].delete(r)}}emit(t,...r){this.observers[t]&&Array.from(this.observers[t].entries()).forEach(([i,a])=>{for(let o=0;o<a;o++)i(...r)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([i,a])=>{for(let o=0;o<a;o++)i.apply(i,[t,...r])})}},TX=class extends PD{constructor(t,r={ns:["translation"],defaultNS:"translation"}){super(),this.data=t||{},this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){let r=this.options.ns.indexOf(t);r>-1&&this.options.ns.splice(r,1)}getResource(t,r,n,i={}){let a=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,o=i.ignoreJSONStructure!==void 0?i.ignoreJSONStructure:this.options.ignoreJSONStructure,s;t.indexOf(".")>-1?s=t.split("."):(s=[t,r],n&&(Array.isArray(n)?s.push(...n):rr(n)&&a?s.push(...n.split(a)):s.push(n)));let c=_X(this.data,s);return!c&&!r&&!n&&t.indexOf(".")>-1&&(t=s[0],r=s[1],n=s.slice(2).join(".")),c||!o||!rr(n)?c:owe(this.data?.[t]?.[r],n,a)}addResource(t,r,n,i,a={silent:!1}){let o=a.keySeparator!==void 0?a.keySeparator:this.options.keySeparator,s=[t,r];n&&(s=s.concat(o?n.split(o):n)),t.indexOf(".")>-1&&(s=t.split("."),i=r,r=s[1]),this.addNamespaces(r),F$t(this.data,s,i),a.silent||this.emit("added",t,r,n,i)}addResources(t,r,n,i={silent:!1}){for(let a in n)(rr(n[a])||Array.isArray(n[a]))&&this.addResource(t,r,a,n[a],{silent:!0});i.silent||this.emit("added",t,r,n)}addResourceBundle(t,r,n,i,a,o={silent:!1,skipCopy:!1}){let s=[t,r];t.indexOf(".")>-1&&(s=t.split("."),i=n,n=r,r=s[1]),this.addNamespaces(r);let c=_X(this.data,s)||{};o.skipCopy||(n=JSON.parse(JSON.stringify(n))),i?K$t(c,n,a):c={...c,...n},F$t(this.data,s,c),o.silent||this.emit("added",t,r,n)}removeResourceBundle(t,r){this.hasResourceBundle(t,r)&&delete this.data[t][r],this.removeNamespaces(r),this.emit("removed",t,r)}hasResourceBundle(t,r){return this.getResource(t,r)!==void 0}getResourceBundle(t,r){return r||(r=this.options.defaultNS),this.getResource(t,r)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){let r=this.getDataByLanguage(t);return!!(r&&Object.keys(r)||[]).find(i=>r[i]&&Object.keys(r[i]).length>0)}toJSON(){return this.data}},Y$t={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,r,n,i){return e.forEach(a=>{t=this.processors[a]?.process(t,r,n,i)??t}),t}},j$t={},V$t=e=>!rr(e)&&typeof e!="boolean"&&typeof e!="number",xX=class e extends PD{constructor(t,r={}){super(),_Rn(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Wm.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t,r={interpolation:{}}){let n={...r};return t==null?!1:this.resolve(t,n)?.res!==void 0}extractFromKey(t,r){let n=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;n===void 0&&(n=":");let i=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator,a=r.ns||this.options.defaultNS||[],o=n&&t.indexOf(n)>-1,s=!this.options.userDefinedKeySeparator&&!r.keySeparator&&!this.options.userDefinedNsSeparator&&!r.nsSeparator&&!PRn(t,n,i);if(o&&!s){let c=t.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:t,namespaces:rr(a)?[a]:a};let u=t.split(n);(n!==i||n===i&&this.options.ns.indexOf(u[0])>-1)&&(a=u.shift()),t=u.join(i)}return{key:t,namespaces:rr(a)?[a]:a}}translate(t,r,n){let i=typeof r=="object"?{...r}:r;if(typeof i!="object"&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof options=="object"&&(i={...i}),i||(i={}),t==null)return"";Array.isArray(t)||(t=[String(t)]);let a=i.returnDetails!==void 0?i.returnDetails:this.options.returnDetails,o=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,{key:s,namespaces:c}=this.extractFromKey(t[t.length-1],i),u=c[c.length-1],l=i.nsSeparator!==void 0?i.nsSeparator:this.options.nsSeparator;l===void 0&&(l=":");let p=i.lng||this.language,f=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(p?.toLowerCase()==="cimode")return f?a?{res:`${u}${l}${s}`,usedKey:s,exactUsedKey:s,usedLng:p,usedNS:u,usedParams:this.getUsedParamsDetails(i)}:`${u}${l}${s}`:a?{res:s,usedKey:s,exactUsedKey:s,usedLng:p,usedNS:u,usedParams:this.getUsedParamsDetails(i)}:s;let d=this.resolve(t,i),h=d?.res,m=d?.usedKey||s,v=d?.exactUsedKey||s,_=["[object Number]","[object Function]","[object RegExp]"],O=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,x=!this.i18nFormat||this.i18nFormat.handleAsObject,S=i.count!==void 0&&!rr(i.count),A=e.hasDefaultValue(i),P=S?this.pluralResolver.getSuffix(p,i.count,i):"",k=i.ordinal&&S?this.pluralResolver.getSuffix(p,i.count,{ordinal:!1}):"",D=S&&!i.ordinal&&i.count===0,F=D&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${P}`]||i[`defaultValue${k}`]||i.defaultValue,K=h;x&&!h&&A&&(K=F);let $=V$t(K),H=Object.prototype.toString.apply(K);if(x&&K&&$&&_.indexOf(H)<0&&!(rr(O)&&Array.isArray(K))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");let Q=this.options.returnedObjectHandler?this.options.returnedObjectHandler(m,K,{...i,ns:c}):`key '${s} (${this.language})' returned an object instead of string.`;return a?(d.res=Q,d.usedParams=this.getUsedParamsDetails(i),d):Q}if(o){let Q=Array.isArray(K),ee=Q?[]:{},z=Q?v:m;for(let q in K)if(Object.prototype.hasOwnProperty.call(K,q)){let Y=`${z}${o}${q}`;A&&!h?ee[q]=this.translate(Y,{...i,defaultValue:V$t(F)?F[q]:void 0,joinArrays:!1,ns:c}):ee[q]=this.translate(Y,{...i,joinArrays:!1,ns:c}),ee[q]===Y&&(ee[q]=K[q])}h=ee}}else if(x&&rr(O)&&Array.isArray(h))h=h.join(O),h&&(h=this.extendTranslation(h,t,i,n));else{let Q=!1,ee=!1;!this.isValidLookup(h)&&A&&(Q=!0,h=F),this.isValidLookup(h)||(ee=!0,h=s);let q=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&ee?void 0:h,Y=A&&F!==h&&this.options.updateMissing;if(ee||Q||Y){if(this.logger.log(Y?"updateKey":"missingKey",p,u,s,Y?F:h),o){let de=this.resolve(s,{...i,keySeparator:!1});de&&de.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let X=[],me=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&me&&me[0])for(let de=0;de<me.length;de++)X.push(me[de]);else this.options.saveMissingTo==="all"?X=this.languageUtils.toResolveHierarchy(i.lng||this.language):X.push(i.lng||this.language);let ke=(de,Ge,mt)=>{let St=A&&mt!==h?mt:q;this.options.missingKeyHandler?this.options.missingKeyHandler(de,u,Ge,St,Y,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(de,u,Ge,St,Y,i),this.emit("missingKey",de,u,Ge,h)};this.options.saveMissing&&(this.options.saveMissingPlurals&&S?X.forEach(de=>{let Ge=this.pluralResolver.getSuffixes(de,i);D&&i[`defaultValue${this.options.pluralSeparator}zero`]&&Ge.indexOf(`${this.options.pluralSeparator}zero`)<0&&Ge.push(`${this.options.pluralSeparator}zero`),Ge.forEach(mt=>{ke([de],s+mt,i[`defaultValue${mt}`]||F)})}):ke(X,s,F))}h=this.extendTranslation(h,t,i,d,n),ee&&h===s&&this.options.appendNamespaceToMissingKey&&(h=`${u}${l}${s}`),(ee||Q)&&this.options.parseMissingKeyHandler&&(h=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${u}${l}${s}`:s,Q?h:void 0,i))}return a?(d.res=h,d.usedParams=this.getUsedParamsDetails(i),d):h}extendTranslation(t,r,n,i,a){if(this.i18nFormat?.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});let c=rr(t)&&(n?.interpolation?.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables),u;if(c){let p=t.match(this.interpolator.nestingRegexp);u=p&&p.length}let l=n.replace&&!rr(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(l={...this.options.interpolation.defaultVariables,...l}),t=this.interpolator.interpolate(t,l,n.lng||this.language||i.usedLng,n),c){let p=t.match(this.interpolator.nestingRegexp),f=p&&p.length;u<f&&(n.nest=!1)}!n.lng&&i&&i.res&&(n.lng=this.language||i.usedLng),n.nest!==!1&&(t=this.interpolator.nest(t,(...p)=>a?.[0]===p[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${p[0]} in key: ${r[0]}`),null):this.translate(...p,r),n)),n.interpolation&&this.interpolator.reset()}let o=n.postProcess||this.options.postProcess,s=rr(o)?[o]:o;return t!=null&&s?.length&&n.applyPostProcessor!==!1&&(t=Y$t.handle(s,t,r,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),t}resolve(t,r={}){let n,i,a,o,s;return rr(t)&&(t=[t]),t.forEach(c=>{if(this.isValidLookup(n))return;let u=this.extractFromKey(c,r),l=u.key;i=l;let p=u.namespaces;this.options.fallbackNS&&(p=p.concat(this.options.fallbackNS));let f=r.count!==void 0&&!rr(r.count),d=f&&!r.ordinal&&r.count===0,h=r.context!==void 0&&(rr(r.context)||typeof r.context=="number")&&r.context!=="",m=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);p.forEach(v=>{this.isValidLookup(n)||(s=v,!j$t[`${m[0]}-${v}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(s)&&(j$t[`${m[0]}-${v}`]=!0,this.logger.warn(`key "${i}" for languages "${m.join(", ")}" won't get resolved as namespace "${s}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),m.forEach(_=>{if(this.isValidLookup(n))return;o=_;let O=[l];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(O,l,_,v,r);else{let S;f&&(S=this.pluralResolver.getSuffix(_,r.count,r));let A=`${this.options.pluralSeparator}zero`,P=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(O.push(l+S),r.ordinal&&S.indexOf(P)===0&&O.push(l+S.replace(P,this.options.pluralSeparator)),d&&O.push(l+A)),h){let k=`${l}${this.options.contextSeparator}${r.context}`;O.push(k),f&&(O.push(k+S),r.ordinal&&S.indexOf(P)===0&&O.push(k+S.replace(P,this.options.pluralSeparator)),d&&O.push(k+A))}}let x;for(;x=O.pop();)this.isValidLookup(n)||(a=x,n=this.getResource(_,v,x,r))}))})}),{res:n,usedKey:i,exactUsedKey:a,usedLng:o,usedNS:s}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,r,n,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(t,r,n,i):this.resourceStore.getResource(t,r,n,i)}getUsedParamsDetails(t={}){let r=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=t.replace&&!rr(t.replace),i=n?t.replace:t;if(n&&typeof t.count<"u"&&(i.count=t.count),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!n){i={...i};for(let a of r)delete i[a]}return i}static hasDefaultValue(t){let r="defaultValue";for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&r===n.substring(0,r.length)&&t[n]!==void 0)return!0;return!1}},OX=class{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Wm.create("languageUtils")}getScriptPartFromCode(t){if(t=Bj(t),!t||t.indexOf("-")<0)return null;let r=t.split("-");return r.length===2||(r.pop(),r[r.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(r.join("-"))}getLanguagePartFromCode(t){if(t=Bj(t),!t||t.indexOf("-")<0)return t;let r=t.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(t){if(rr(t)&&t.indexOf("-")>-1){let r;try{r=Intl.getCanonicalLocales(t)[0]}catch{}return r&&this.options.lowerCaseLng&&(r=r.toLowerCase()),r||(this.options.lowerCaseLng?t.toLowerCase():t)}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let r;return t.forEach(n=>{if(r)return;let i=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(i))&&(r=i)}),!r&&this.options.supportedLngs&&t.forEach(n=>{if(r)return;let i=this.getScriptPartFromCode(n);if(this.isSupportedCode(i))return r=i;let a=this.getLanguagePartFromCode(n);if(this.isSupportedCode(a))return r=a;r=this.options.supportedLngs.find(o=>{if(o===a)return o;if(!(o.indexOf("-")<0&&a.indexOf("-")<0)&&(o.indexOf("-")>0&&a.indexOf("-")<0&&o.substring(0,o.indexOf("-"))===a||o.indexOf(a)===0&&a.length>1))return o})}),r||(r=this.getFallbackCodes(this.options.fallbackLng)[0]),r}getFallbackCodes(t,r){if(!t)return[];if(typeof t=="function"&&(t=t(r)),rr(t)&&(t=[t]),Array.isArray(t))return t;if(!r)return t.default||[];let n=t[r];return n||(n=t[this.getScriptPartFromCode(r)]),n||(n=t[this.formatLanguageCode(r)]),n||(n=t[this.getLanguagePartFromCode(r)]),n||(n=t.default),n||[]}toResolveHierarchy(t,r){let n=this.getFallbackCodes((r===!1?[]:r)||this.options.fallbackLng||[],t),i=[],a=o=>{o&&(this.isSupportedCode(o)?i.push(o):this.logger.warn(`rejecting language code not found in supportedLngs: ${o}`))};return rr(t)&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&a(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&a(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&a(this.getLanguagePartFromCode(t))):rr(t)&&a(this.formatLanguageCode(t)),n.forEach(o=>{i.indexOf(o)<0&&a(this.formatLanguageCode(o))}),i}},q$t={zero:0,one:1,two:2,few:3,many:4,other:5},U$t={select:e=>e===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})},cwe=class{constructor(t,r={}){this.languageUtils=t,this.options=r,this.logger=Wm.create("pluralResolver"),this.pluralRulesCache={}}addRule(t,r){this.rules[t]=r}clearCache(){this.pluralRulesCache={}}getRule(t,r={}){let n=Bj(t==="dev"?"en":t),i=r.ordinal?"ordinal":"cardinal",a=JSON.stringify({cleanedCode:n,type:i});if(a in this.pluralRulesCache)return this.pluralRulesCache[a];let o;try{o=new Intl.PluralRules(n,{type:i})}catch{if(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),U$t;if(!t.match(/-|_/))return U$t;let c=this.languageUtils.getLanguagePartFromCode(t);o=this.getRule(c,r)}return this.pluralRulesCache[a]=o,o}needsPlural(t,r={}){let n=this.getRule(t,r);return n||(n=this.getRule("dev",r)),n?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(t,r,n={}){return this.getSuffixes(t,n).map(i=>`${r}${i}`)}getSuffixes(t,r={}){let n=this.getRule(t,r);return n||(n=this.getRule("dev",r)),n?n.resolvedOptions().pluralCategories.sort((i,a)=>q$t[i]-q$t[a]).map(i=>`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(t,r,n={}){let i=this.getRule(t,n);return i?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i.select(r)}`:(this.logger.warn(`no plural rule found for: ${t}`),this.getSuffix("dev",r,n))}},B$t=(e,t,r,n=".",i=!0)=>{let a=ORn(e,t,r);return!a&&i&&rr(r)&&(a=owe(e,r,n),a===void 0&&(a=owe(t,r,n))),a},iwe=e=>e.replace(/\$/g,"$$$$"),uwe=class{constructor(t={}){this.logger=Wm.create("interpolator"),this.options=t,this.format=t?.interpolation?.format||(r=>r),this.init(t)}init(t={}){t.interpolation||(t.interpolation={escapeValue:!0});let{escape:r,escapeValue:n,useRawValueToEscape:i,prefix:a,prefixEscaped:o,suffix:s,suffixEscaped:c,formatSeparator:u,unescapeSuffix:l,unescapePrefix:p,nestingPrefix:f,nestingPrefixEscaped:d,nestingSuffix:h,nestingSuffixEscaped:m,nestingOptionsSeparator:v,maxReplaces:_,alwaysFormat:O}=t.interpolation;this.escape=r!==void 0?r:ARn,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=a?wD(a):o||"{{",this.suffix=s?wD(s):c||"}}",this.formatSeparator=u||",",this.unescapePrefix=l?"":p||"-",this.unescapeSuffix=this.unescapePrefix?"":l||"",this.nestingPrefix=f?wD(f):d||wD("$t("),this.nestingSuffix=h?wD(h):m||wD(")"),this.nestingOptionsSeparator=v||",",this.maxReplaces=_||1e3,this.alwaysFormat=O!==void 0?O:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){let t=(r,n)=>r?.source===n?(r.lastIndex=0,r):new RegExp(n,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}(.+?)${this.nestingSuffix}`)}interpolate(t,r,n,i){let a,o,s,c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},u=d=>{if(d.indexOf(this.formatSeparator)<0){let _=B$t(r,c,d,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(_,void 0,n,{...i,...r,interpolationkey:d}):_}let h=d.split(this.formatSeparator),m=h.shift().trim(),v=h.join(this.formatSeparator).trim();return this.format(B$t(r,c,m,this.options.keySeparator,this.options.ignoreJSONStructure),v,n,{...i,...r,interpolationkey:m})};this.resetRegExp();let l=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,p=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:d=>iwe(d)},{regex:this.regexp,safeValue:d=>this.escapeValue?iwe(this.escape(d)):iwe(d)}].forEach(d=>{for(s=0;a=d.regex.exec(t);){let h=a[1].trim();if(o=u(h),o===void 0)if(typeof l=="function"){let v=l(t,a,i);o=rr(v)?v:""}else if(i&&Object.prototype.hasOwnProperty.call(i,h))o="";else if(p){o=a[0];continue}else this.logger.warn(`missed to pass in variable ${h} for interpolating ${t}`),o="";else!rr(o)&&!this.useRawValueToEscape&&(o=k$t(o));let m=d.safeValue(o);if(t=t.replace(a[0],m),p?(d.regex.lastIndex+=o.length,d.regex.lastIndex-=a[0].length):d.regex.lastIndex=0,s++,s>=this.maxReplaces)break}}),t}nest(t,r,n={}){let i,a,o,s=(c,u)=>{let l=this.nestingOptionsSeparator;if(c.indexOf(l)<0)return c;let p=c.split(new RegExp(`${l}[ ]*{`)),f=`{${p[1]}`;c=p[0],f=this.interpolate(f,o);let d=f.match(/'/g),h=f.match(/"/g);((d?.length??0)%2===0&&!h||h.length%2!==0)&&(f=f.replace(/'/g,'"'));try{o=JSON.parse(f),u&&(o={...u,...o})}catch(m){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,m),`${c}${l}${f}`}return o.defaultValue&&o.defaultValue.indexOf(this.prefix)>-1&&delete o.defaultValue,c};for(;i=this.nestingRegexp.exec(t);){let c=[];o={...n},o=o.replace&&!rr(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;let u=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(u!==-1&&(c=i[1].slice(u).split(this.formatSeparator).map(l=>l.trim()).filter(Boolean),i[1]=i[1].slice(0,u)),a=r(s.call(this,i[1].trim(),o),o),a&&i[0]===t&&!rr(a))return a;rr(a)||(a=k$t(a)),a||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${t}`),a=""),c.length&&(a=c.reduce((l,p)=>this.format(l,p,n.lng,{...n,interpolationkey:i[1].trim()}),a.trim())),t=t.replace(i[0],a),this.regexp.lastIndex=0}return t}},NRn=e=>{let t=e.toLowerCase().trim(),r={};if(e.indexOf("(")>-1){let n=e.split("(");t=n[0].toLowerCase().trim();let i=n[1].substring(0,n[1].length-1);t==="currency"&&i.indexOf(":")<0?r.currency||(r.currency=i.trim()):t==="relativetime"&&i.indexOf(":")<0?r.range||(r.range=i.trim()):i.split(";").forEach(o=>{if(o){let[s,...c]=o.split(":"),u=c.join(":").trim().replace(/^'+|'+$/g,""),l=s.trim();r[l]||(r[l]=u),u==="false"&&(r[l]=!1),u==="true"&&(r[l]=!0),isNaN(u)||(r[l]=parseInt(u,10))}})}return{formatName:t,formatOptions:r}},z$t=e=>{let t={};return(r,n,i)=>{let a=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(a={...a,[i.interpolationkey]:void 0});let o=n+JSON.stringify(a),s=t[o];return s||(s=e(Bj(n),i),t[o]=s),s(r)}},IRn=e=>(t,r,n)=>e(Bj(r),n)(t),lwe=class{constructor(t={}){this.logger=Wm.create("formatter"),this.options=t,this.init(t)}init(t,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";let n=r.cacheInBuiltFormats?z$t:IRn;this.formats={number:n((i,a)=>{let o=new Intl.NumberFormat(i,{...a});return s=>o.format(s)}),currency:n((i,a)=>{let o=new Intl.NumberFormat(i,{...a,style:"currency"});return s=>o.format(s)}),datetime:n((i,a)=>{let o=new Intl.DateTimeFormat(i,{...a});return s=>o.format(s)}),relativetime:n((i,a)=>{let o=new Intl.RelativeTimeFormat(i,{...a});return s=>o.format(s,a.range||"day")}),list:n((i,a)=>{let o=new Intl.ListFormat(i,{...a});return s=>o.format(s)})}}add(t,r){this.formats[t.toLowerCase().trim()]=r}addCached(t,r){this.formats[t.toLowerCase().trim()]=z$t(r)}format(t,r,n,i={}){let a=r.split(this.formatSeparator);if(a.length>1&&a[0].indexOf("(")>1&&a[0].indexOf(")")<0&&a.find(s=>s.indexOf(")")>-1)){let s=a.findIndex(c=>c.indexOf(")")>-1);a[0]=[a[0],...a.splice(1,s)].join(this.formatSeparator)}return a.reduce((s,c)=>{let{formatName:u,formatOptions:l}=NRn(c);if(this.formats[u]){let p=s;try{let f=i?.formatParams?.[i.interpolationkey]||{},d=f.locale||f.lng||i.locale||i.lng||n;p=this.formats[u](s,d,{...l,...i,...f})}catch(f){this.logger.warn(f)}return p}else this.logger.warn(`there was no format function for ${u}`);return s},t)}},RRn=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)},pwe=class extends PD{constructor(t,r,n,i={}){super(),this.backend=t,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=i,this.logger=Wm.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(n,i.backend,i)}queueLoad(t,r,n,i){let a={},o={},s={},c={};return t.forEach(u=>{let l=!0;r.forEach(p=>{let f=`${u}|${p}`;!n.reload&&this.store.hasResourceBundle(u,p)?this.state[f]=2:this.state[f]<0||(this.state[f]===1?o[f]===void 0&&(o[f]=!0):(this.state[f]=1,l=!1,o[f]===void 0&&(o[f]=!0),a[f]===void 0&&(a[f]=!0),c[p]===void 0&&(c[p]=!0)))}),l||(s[u]=!0)}),(Object.keys(a).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(a),pending:Object.keys(o),toLoadLanguages:Object.keys(s),toLoadNamespaces:Object.keys(c)}}loaded(t,r,n){let i=t.split("|"),a=i[0],o=i[1];r&&this.emit("failedLoading",a,o,r),!r&&n&&this.store.addResourceBundle(a,o,n,void 0,void 0,{skipCopy:!0}),this.state[t]=r?-1:2,r&&n&&(this.state[t]=0);let s={};this.queue.forEach(c=>{xRn(c.loaded,[a],o),RRn(c,t),r&&c.errors.push(r),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(u=>{s[u]||(s[u]={});let l=c.loaded[u];l.length&&l.forEach(p=>{s[u][p]===void 0&&(s[u][p]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",s),this.queue=this.queue.filter(c=>!c.done)}read(t,r,n,i=0,a=this.retryTimeout,o){if(!t.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:r,fcName:n,tried:i,wait:a,callback:o});return}this.readingCalls++;let s=(u,l)=>{if(this.readingCalls--,this.waitingReads.length>0){let p=this.waitingReads.shift();this.read(p.lng,p.ns,p.fcName,p.tried,p.wait,p.callback)}if(u&&l&&i<this.maxRetries){setTimeout(()=>{this.read.call(this,t,r,n,i+1,a*2,o)},a);return}o(u,l)},c=this.backend[n].bind(this.backend);if(c.length===2){try{let u=c(t,r);u&&typeof u.then=="function"?u.then(l=>s(null,l)).catch(s):s(null,u)}catch(u){s(u)}return}return c(t,r,s)}prepareLoading(t,r,n={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();rr(t)&&(t=this.languageUtils.toResolveHierarchy(t)),rr(r)&&(r=[r]);let a=this.queueLoad(t,r,n,i);if(!a.toLoad.length)return a.pending.length||i(),null;a.toLoad.forEach(o=>{this.loadOne(o)})}load(t,r,n){this.prepareLoading(t,r,{},n)}reload(t,r,n){this.prepareLoading(t,r,{reload:!0},n)}loadOne(t,r=""){let n=t.split("|"),i=n[0],a=n[1];this.read(i,a,"read",void 0,void 0,(o,s)=>{o&&this.logger.warn(`${r}loading namespace ${a} for language ${i} failed`,o),!o&&s&&this.logger.log(`${r}loaded namespace ${a} for language ${i}`,s),this.loaded(t,o,s)})}saveMissing(t,r,n,i,a,o={},s=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(r)){this.logger.warn(`did not save key "${n}" as the namespace "${r}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(n==null||n==="")){if(this.backend?.create){let c={...o,isUpdate:a},u=this.backend.create.bind(this.backend);if(u.length<6)try{let l;u.length===5?l=u(t,r,n,i,c):l=u(t,r,n,i),l&&typeof l.then=="function"?l.then(p=>s(null,p)).catch(s):s(null,l)}catch(l){s(l)}else u(t,r,n,i,s,c)}!t||!t[0]||this.store.addResource(t[0],r,n,i)}}},H$t=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),rr(e[1])&&(t.defaultValue=e[1]),rr(e[2])&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){let r=e[3]||e[2];Object.keys(r).forEach(n=>{t[n]=r[n]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),G$t=e=>(rr(e.ns)&&(e.ns=[e.ns]),rr(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),rr(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs?.indexOf?.("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),typeof e.initImmediate=="boolean"&&(e.initAsync=e.initImmediate),e),EX=()=>{},LRn=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(r=>{typeof e[r]=="function"&&(e[r]=e[r].bind(e))})},SX=class e extends PD{constructor(t={},r){if(super(),this.options=G$t(t),this.services={},this.logger=Wm,this.modules={external:[]},LRn(this),r&&!this.isInitialized&&!t.isClone){if(!this.options.initAsync)return this.init(t,r),this;setTimeout(()=>{this.init(t,r)},0)}}init(t={},r){this.isInitializing=!0,typeof t=="function"&&(r=t,t={}),t.defaultNS==null&&t.ns&&(rr(t.ns)?t.defaultNS=t.ns:t.ns.indexOf("translation")<0&&(t.defaultNS=t.ns[0]));let n=H$t();this.options={...n,...this.options,...G$t(t)},this.options.interpolation={...n.interpolation,...this.options.interpolation},t.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=t.keySeparator),t.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=t.nsSeparator);let i=u=>u?typeof u=="function"?new u:u:null;if(!this.options.isClone){this.modules.logger?Wm.init(i(this.modules.logger),this.options):Wm.init(null,this.options);let u;this.modules.formatter?u=this.modules.formatter:u=lwe;let l=new OX(this.options);this.store=new TX(this.options.resources,this.options);let p=this.services;p.logger=Wm,p.resourceStore=this.store,p.languageUtils=l,p.pluralResolver=new cwe(l,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),u&&(!this.options.interpolation.format||this.options.interpolation.format===n.interpolation.format)&&(p.formatter=i(u),p.formatter.init(p,this.options),this.options.interpolation.format=p.formatter.format.bind(p.formatter)),p.interpolator=new uwe(this.options),p.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},p.backendConnector=new pwe(i(this.modules.backend),p.resourceStore,p,this.options),p.backendConnector.on("*",(f,...d)=>{this.emit(f,...d)}),this.modules.languageDetector&&(p.languageDetector=i(this.modules.languageDetector),p.languageDetector.init&&p.languageDetector.init(p,this.options.detection,this.options)),this.modules.i18nFormat&&(p.i18nFormat=i(this.modules.i18nFormat),p.i18nFormat.init&&p.i18nFormat.init(this)),this.translator=new xX(this.services,this.options),this.translator.on("*",(f,...d)=>{this.emit(f,...d)}),this.modules.external.forEach(f=>{f.init&&f.init(this)})}if(this.format=this.options.interpolation.format,r||(r=EX),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){let u=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);u.length>0&&u[0]!=="dev"&&(this.options.lng=u[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(u=>{this[u]=(...l)=>this.store[u](...l)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(u=>{this[u]=(...l)=>(this.store[u](...l),this)});let s=qj(),c=()=>{let u=(l,p)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),s.resolve(p),r(l,p)};if(this.languages&&!this.isInitialized)return u(null,this.t.bind(this));this.changeLanguage(this.options.lng,u)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),s}loadResources(t,r=EX){let n=r,i=rr(t)?t:this.language;if(typeof t=="function"&&(n=t),!this.options.resources||this.options.partialBundledLanguages){if(i?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();let a=[],o=s=>{if(!s||s==="cimode")return;this.services.languageUtils.toResolveHierarchy(s).forEach(u=>{u!=="cimode"&&a.indexOf(u)<0&&a.push(u)})};i?o(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>o(c)),this.options.preload?.forEach?.(s=>o(s)),this.services.backendConnector.load(a,this.options.ns,s=>{!s&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(s)})}else n(null)}reloadResources(t,r,n){let i=qj();return typeof t=="function"&&(n=t,t=void 0),typeof r=="function"&&(n=r,r=void 0),t||(t=this.languages),r||(r=this.options.ns),n||(n=EX),this.services.backendConnector.reload(t,r,a=>{i.resolve(),n(a)}),i}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&Y$t.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-1)){for(let r=0;r<this.languages.length;r++){let n=this.languages[r];if(!(["cimode","dev"].indexOf(n)>-1)&&this.store.hasLanguageSomeTranslations(n)){this.resolvedLanguage=n;break}}!this.resolvedLanguage&&this.languages.indexOf(t)<0&&this.store.hasLanguageSomeTranslations(t)&&(this.resolvedLanguage=t,this.languages.unshift(t))}}changeLanguage(t,r){this.isLanguageChangingTo=t;let n=qj();this.emit("languageChanging",t);let i=s=>{this.language=s,this.languages=this.services.languageUtils.toResolveHierarchy(s),this.resolvedLanguage=void 0,this.setResolvedLanguage(s)},a=(s,c)=>{c?this.isLanguageChangingTo===t&&(i(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,n.resolve((...u)=>this.t(...u)),r&&r(s,(...u)=>this.t(...u))},o=s=>{!t&&!s&&this.services.languageDetector&&(s=[]);let c=rr(s)?s:s&&s[0],u=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(rr(s)?[s]:s);u&&(this.language||i(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector?.cacheUserLanguage?.(u)),this.loadResources(u,l=>{a(l,u)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?o(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(t),n}getFixedT(t,r,n){let i=(a,o,...s)=>{let c;typeof o!="object"?c=this.options.overloadTranslationOptionHandler([a,o].concat(s)):c={...o},c.lng=c.lng||i.lng,c.lngs=c.lngs||i.lngs,c.ns=c.ns||i.ns,c.keyPrefix!==""&&(c.keyPrefix=c.keyPrefix||n||i.keyPrefix);let u=this.options.keySeparator||".",l;return c.keyPrefix&&Array.isArray(a)?l=a.map(p=>`${c.keyPrefix}${u}${p}`):l=c.keyPrefix?`${c.keyPrefix}${u}${a}`:a,this.t(l,c)};return rr(t)?i.lng=t:i.lngs=t,i.ns=r,i.keyPrefix=n,i}t(...t){return this.translator?.translate(...t)}exists(...t){return this.translator?.exists(...t)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t,r={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;let n=r.lng||this.resolvedLanguage||this.languages[0],i=this.options?this.options.fallbackLng:!1,a=this.languages[this.languages.length-1];if(n.toLowerCase()==="cimode")return!0;let o=(s,c)=>{let u=this.services.backendConnector.state[`${s}|${c}`];return u===-1||u===0||u===2};if(r.precheck){let s=r.precheck(this,o);if(s!==void 0)return s}return!!(this.hasResourceBundle(n,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(n,t)&&(!i||o(a,t)))}loadNamespaces(t,r){let n=qj();return this.options.ns?(rr(t)&&(t=[t]),t.forEach(i=>{this.options.ns.indexOf(i)<0&&this.options.ns.push(i)}),this.loadResources(i=>{n.resolve(),r&&r(i)}),n):(r&&r(),Promise.resolve())}loadLanguages(t,r){let n=qj();rr(t)&&(t=[t]);let i=this.options.preload||[],a=t.filter(o=>i.indexOf(o)<0&&this.services.languageUtils.isSupportedCode(o));return a.length?(this.options.preload=i.concat(a),this.loadResources(o=>{n.resolve(),r&&r(o)}),n):(r&&r(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!t)return"rtl";if(Intl.Locale){let i=new Intl.Locale(t);if(i&&i.getTextInfo){let a=i.getTextInfo();if(a&&a.direction)return a.direction}}let r=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],n=this.services?.languageUtils||new OX(H$t());return t.toLowerCase().indexOf("-latn")>1?"ltr":r.indexOf(n.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(t={},r){return new e(t,r)}cloneInstance(t={},r=EX){let n=t.forkResourceStore;n&&delete t.forkResourceStore;let i={...this.options,...t,isClone:!0},a=new e(i);if((t.debug!==void 0||t.prefix!==void 0)&&(a.logger=a.logger.clone(t)),["store","services","language"].forEach(s=>{a[s]=this[s]}),a.services={...this.services},a.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},n){let s=Object.keys(this.store.data).reduce((c,u)=>(c[u]={...this.store.data[u]},c[u]=Object.keys(c[u]).reduce((l,p)=>(l[p]={...c[u][p]},l),c[u]),c),{});a.store=new TX(s,i),a.services.resourceStore=a.store}return a.translator=new xX(a.services,i),a.translator.on("*",(s,...c)=>{a.emit(s,...c)}),a.init(i,r),a.translator.options=i,a.translator.backendConnector.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},a}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}},vt=SX.createInstance();vt.createInstance=SX.createInstance;var U5i=vt.createInstance,B5i=vt.dir,z5i=vt.init,H5i=vt.loadResources,G5i=vt.reloadResources,K5i=vt.use,Y5i=vt.changeLanguage,W5i=vt.getFixedT,X5i=vt.t,J5i=vt.exists,Z5i=vt.setDefaultNamespace,Q5i=vt.hasLoadedNamespace,ezi=vt.loadNamespaces,tzi=vt.loadLanguages;var zj=dt(Pc());var W$t="genericActions";var AX="DataFieldForAction",CX="DataFieldForIntentBasedNavigation",X$t="DataFieldForActionGroup",fwe="::",Hj="customView(";var dwe=new Map([[zj.v2.TableTypeV2.ResponsiveTable,"ResponsiveTableColumnsExtension"],[zj.v2.TableTypeV2.GridTable,"GridTableColumnsExtension"],[zj.v2.TableTypeV2.AnalyticalTable,"AnalyticalTableColumnsExtension"],[zj.v2.TableTypeV2.TreeTable,"TreeTableColumnsExtension"]]),DD="annotation",go="schema";var hwe="Facet ID: ",J$t=new Map([...dwe.entries()].map(([e,t])=>[t,e]));var Z$t="@com.sap.vocabularies.UI.v1";var Q$t="annotation",eMt="service",tMt="ui5";var wX=class{schema;value;pattern;freeText;disabled;state=0;description;required;isAtomic;i18nClassification;name;displayName;artifactType;minimum;messages;locations;constructor(t,r){this.schema=structuredClone(t),this.name=r}};function VE(e){return e?.tooComplex===!0}var nMt=new Map;nMt.set("com.sap.vocabularies.UI.v1.HeaderInfo",new Set(["com.sap.vocabularies.UI.v1.HeaderFacets","com.sap.vocabularies.UI.v1.Identification"]));var kRn=["com.sap.vocabularies.UI.v1.DeleteHidden","com.sap.vocabularies.UI.v1.UpdateHidden"],rMt=e=>(e||"").split("/@").pop()||"";function iMt(e,t){let r=e.nodes.find(n=>n?.nodeId&&n.nodeId[0]===t[0]);for(let n=1;n<t.length;n++){if(r&&VE(r))return r;r=r?.subnodes.find(i=>i.nodeId[n]===t[n])}return r}function aMt(e){return VE(e)?e.tooComplexLocations??[]:e.location?[e.location]:[]}function mwe(e,t,r,n){let i=$Rn(t,n);for(let a of i){let o=t[a],s=o.annotationPath.split("/").map((c,u)=>u===1?c.split(".").slice(-1)[0]??c:c).join("/");if(e===o.annotationPath||e===s)return o;if(!r&&!VE(o)&&o.subnodes.length>0){let c=mwe(e,o.subnodes,void 0,n);if(c)return c}}}function oMt(e,t,r,n,i){let a=rMt(e),o=mwe(e,r,void 0,i);return!o&&kRn.includes(a)&&(o=t.find(c=>c.nodeType===W$t)?.subnodes.find(c=>c.annotationPath===e)),!o&&nMt.get(rMt(n))?.has(a)&&(o=mwe(e,t,!0,i)),o}function $Rn(e,t){let r=[];t!==void 0&&e.length>t&&r.push(t);for(let n=0;n<e.length;n++)n!==t&&r.push(n);return r}var gwe="i18n",MRn=(e="",t=!1,r)=>{if(/^{{[^\\{}:]+}}$/.exec(e)&&(!t||r))return e.toString().substring(2,e.length-2);let n=t?`(${gwe}|@${gwe})`:`${gwe}`,i=t?2:1,a=new RegExp(`^{${n}>([^\\{}:]+)}$`).exec(e);return a?a[i]:void 0},ywe=(e,t={})=>{let r=MRn(e,!0,!0);if(r){let n=t[r];if(n?.length>0)return n[0].value?.value}},sMt=(e,t,r,n="EDMXBackend")=>["CAPJava","CAPNodejs"].includes(n)&&!e&&t?eMt:r?Q$t:tMt;var UO=(e,t)=>!e||!t?e===t:e.length===t.length&&e.every(function(r,n){return r===t[n]}),vwe=(e,t)=>{if(!e||!t||t.length>e.length)return!1;let r=e.length-1,n=t.length-1;for(;n>=0;){if(t[n]!==e[r])return!1;r--,n--}return!0},BO=(e,t)=>{let r=e;for(let n of t)if(n!==void 0)if(typeof r=="object"&&n in r)r=r[n];else return;return r};var FRn=()=>({bundles:{annotation:{},app:{},service:{},ui5:{}}}),ND=(e,t=!1)=>{let r=e[e.length-1];if(r){let n=r.toString(),i=n.includes(":::")?":::":"::",a=r.toString().split(i);if(n=a[0],!t&&a.length>1&&(a.splice(0,1),n=a.join("/")),n)return n}},uMt=(e,t)=>{let r,n=0,i=!1;for(let o in e.aggregations)e.aggregations[o].custom?i=!0:(r=n>0?void 0:e.aggregations[o],n++);if(!i||!r?.actions)return;let a=r.actions.findIndex(o=>o==="Delete"||typeof o=="object"&&o.type==="Delete");if(a!==-1){let o=r.actions[a];typeof o!="object"&&(o={type:o}),o.disabled=!0,o.title=vt.t(t),r.actions[a]=o}},Sv=(e,t,r,n)=>{t||(e.state=1,e.messages=[{text:r,type:"warning"}],e.inactive=!0,n&&e.properties[n]&&bwe(e.properties[n],[{text:r}]))},ID=(e,t=e.value)=>{let r=t&&typeof t=="object"?t:{},n="key"in r&&!!r.key;Sv(e,n,vt.t("PAGE_EDITOR_CUSTOM_EXTENSION_NO_KEY"),"key")};var DX=(e,t)=>{let r=e.name==="position"?e.parent?.name:e.name;if(t.enum){let n={...t,enum:[...t.enum]},i=n.enum.findIndex(a=>a===r);return i!==-1&&n.enum.splice(i,1),n}else if(t.oneOf){let n=FRn(),i={...t,oneOf:[...t.oneOf]};for(let a=0;a<i.oneOf.length;a++){let o=i.oneOf[a];o.bundle=sMt(o.custom,!0,!!o.annotationNodeId,n.projectType),o.const===r&&(i.oneOf[a]={...o,hidden:!0})}return i}return t};function bwe(e,t){e.messages??=[],e.messages.push(...t)}function Ewe(e){let t="",r=!0;for(let n=0;n<e.length;n++){let i=e[n];if(i==="_"||i==="-"||i===" "){t.endsWith(" ")||(t+=" "),r=!0;continue}let a=e[n-1],o=e[n+1];n>0&&(a>="a"&&a<="z"&&i>="A"&&i<="Z"||a>="A"&&a<="Z"&&i>="A"&&i<="Z"&&o&&o>="a"&&o<="z")&&(t+=" ",r=!0),r?(t+=i.toUpperCase(),r=!1):t+=i}return t.trim()}var lMt={top:["header","filterBar"]},_we=["anchor","relatedFacet"],Gt=class e{path=[];aggregations={};properties={};additionalProperties;variants=[];childClass;additionalText;locations;actions;inactive;schema;annotationCreationForms=[];allowedAnnotationCreationForms=[];schemaCreationForms=[];formSchema;sortableList;sortableItem;sortableReadonlyTooltip;sortableConfigOnly;order;description;i18nKey;state=0;messages;value;type="Object";parent;custom=!1;isViewNode;isTable=!1;pattern;name;union;sortableCollection;annotationNodeId;dropUINodes;pending;hidden;artifactType;virtual;icon;isAtomic;constructor(t,r){t&&(this.aggregations=t.aggregations,this.properties=t.properties),r&&(this.schema=r)}addAggregation(t,r,n,i,a){if(this.aggregations[t]&&!a)return this.aggregations[t];if(r.name=t,i!==void 0&&!Number.isNaN(i)){for(let o in this.aggregations){let s=this.aggregations[o].order;s!==void 0&&!Number.isNaN(s)&&s>=i&&(this.aggregations[o].order=s+1)}r.order=i}else r.order=Object.keys(this.aggregations).length;return Object.defineProperty(r,"parent",{value:this,writable:!1}),this.aggregations[t]=r,this.updatePath(this.aggregations[t],n),r}addProperty(t,r){_we.includes(t)&&(r=DX(this,r));let n=r.displayName||Ewe(t),i=new wX(r,n);return this.properties[t]=i,i}getDisplayName(t={}){let r=[()=>{let i=this.getRawDisplayName(),a=ywe(i,t);return a||i},this.getTechnicalName.bind(this),()=>{let i=this.getFormattedName();return i?Ewe(i):void 0}],n="";for(let i of r)if(n=i()||"",n)break;return n}getSupportedActions(){let t=[...this.actions??[]];return this.locations?.length&&t.push("OpenSource"),t}getKeys(){if(this.schema?.keys)return this.schema.keys}getValueOfSchemaKey(t){return this.getKeys()?.find(n=>n.name===t)?.value}getTechnicalName(){}getRawDisplayName(){if(this.isViewNode){let t=this.formatTextForDisplay(this.description);if(t)return t}return this.formatTextForDisplay(this.schema?.title)}formatTextForDisplay(t=""){return t.trim()}updateValues(t){let r=Object.keys(this.properties),n=Object.keys(this.aggregations);if(t)for(let i in t)r.includes(i)&&(this.properties[i].value=t[i]),n.includes(i)&&(this.aggregations[i].value=t[i])}updatePropertiesValues(t,r,n,i,a,o){this.updateValues(t),this.updateAnnotationData(a),this.annotationCreationForms=this.getNativeNodeCreationForms(a);for(let s in this.aggregations){let c=this.type==="Array"?Number.parseInt(s,10):s,u=this.aggregations[s].union?.originalNames||[s];for(let l of u)this.aggregations[s].updatePropertiesValues(t?.[l],r,n,i.concat([c]),a,o);this.aggregations[s].onPropertiesUpdated()}this.isAtomic&&this.handleAtomicObject(t,i)}onPropertiesUpdated(){}updateAnnotationData(t){let r=this.getCurrentUINode(t),n=r?.direct?r.node:void 0;this.setAllowedParents(t,n),this.updateLocations(t,n),r?.node&&!VE(r.node)&&r.node.readonly&&this.applyReadonlyAnnotationNode(r.node.readonlyTooltip),!this.custom&&this.sortableItem==="Enabled"&&!this.annotationNodeId&&(this.sortableItem="Readonly",this.removeAction("Delete"))}setAllowedParents(t,r){r&&(this.dropUINodes=r?.allowedParentNodes)}updateLocations(t,r){this.locations=this.locations||[];let n=this.locations.length;if(!r||n&&this.isMacrosNode())return;let i=aMt(r);if(i.length>0){if(n)for(let a of this.locations)i.some(o=>o.fileUri!==a.fileUri)&&i.push(a);this.locations=i}}getNativeNodeCreationForms(t){return!this.name||!t?[]:this.annotationNodeId||this.getParentAnnotationNodeId()?[]:this.getDefaultNativeCreationForms(t)}getDefaultNativeCreationForms(t){return[]}getParentAnnotationNodeId(){let t=this.parent;for(;t;){if(t.annotationNodeId)return t.annotationNodeId;t=t?t.parent:void 0}}getProperties(){return this.properties}getCopy(t=e){let r=JSON.parse(JSON.stringify(this,(i,a)=>{if(i!=="parent")return a})),n=new t(r);return this.createAggregations(n,t),new t(n)}createAggregations(t,r=e){if(t.aggregations){for(let n in t.aggregations)t.aggregations[n]=new r(t.aggregations[n]),this.createAggregations(t.aggregations[n]);t.additionalProperties?.aggregations&&(t.additionalProperties=new r(t.additionalProperties))}}aggregationOrderSorter(t,r){let n=this.aggregations[t]&&this.aggregations[t].order||-1,i=this.aggregations[r]&&this.aggregations[r].order||-1;return n===i?0:n>i?1:-1}getAggregationKeys(t=!1,r){let n=Object.keys(this.aggregations).sort(this.aggregationOrderSorter.bind(this));return this.sortableList||(n=n.sort((i,a)=>{let o=lMt.top.indexOf(i),s=lMt.top.indexOf(a);return o!==-1&&s!==-1&&o>s?1:o!==-1?-1:s!==-1?1:0})),t&&(n=n.filter(i=>this.aggregations[i].isViewNode&&!this.aggregations[i].hidden)),r==="ViewNode"&&(n=n.sort(this.getViewNodeSorter.bind(this))),n}getViewNodeSorter(t,r){let n=this.aggregations[t].isViewNode,i=this.aggregations[r].isViewNode;return n===i&&!n?t===r?0:t>r?1:-1:this.aggregations[t].isViewNode===this.aggregations[r].isViewNode?0:this.aggregations[t].isViewNode?1:-1}updatePath(t,r){if(t.setPath(r),t.aggregations)for(let n in t.aggregations)this.updatePath(t.aggregations[n],r.concat([n]))}setPath(t){this.path=t}getMaxOrder(){let t=0;for(let r in this.aggregations){let n=this.aggregations[r].order||0;t<n&&(t=n)}return t}findMatchingParent(t=e){let r=this.parent;for(;r;){if(r instanceof t)return r;r=r?r.parent:void 0}}addUnionName(t,r){let n=this.union?.originalNames||[];n.includes(r)||n.push(r),this.union={name:t,originalNames:n}}getFormattedName(){return this.name}getCurrentUINode(t){if(this.name&&t){let r=this.annotationNodeId||this.getParentAnnotationNodeId();if(r){let n=iMt(t,r);if(n)return{node:n,direct:!!this.annotationNodeId}}}}applyReadonlyAnnotationNode(t){let r=i=>{for(let a=0;a<i.length;a++){let o=i[a];typeof o=="string"&&(i[a]=o={type:o}),o.disabled=!0,o.title=t}},n=i=>{i.sortableItem="Readonly",t&&(i.sortableReadonlyTooltip=t)};for(let i in this.aggregations){let a=this.aggregations[i];a.actions&&!a.custom&&r(a.actions),a.sortableItem==="Enabled"&&n(a)}this.actions&&r(this.actions),this.sortableItem==="Enabled"&&n(this)}removeAction(t){if(this.actions){let r=this.actions.indexOf(t);r!==-1&&this.actions.splice(r,1)}}nodeIdToString(t){return`[${t.join(",")}]`}findDropableCollectionsByCollection(t,r){let n=[];if(t.sortableList&&t.sortableCollection===r)n.push(t);else for(let i in t.aggregations){let a=t.aggregations[i],o=this.findDropableCollectionsByCollection(a,r);n.push(...o)}return n}getAllowedDropRange(t){}findAllowedDropAggregations(t,r=this){let{dropUINodes:n={},sortableCollection:i}=t,a=[];if(r.annotationNodeId&&n[this.nodeIdToString(r.annotationNodeId)]){let o=this.findDropableCollectionsByCollection(r,i);a.push(...o.map(s=>{let c=s.getAllowedDropRange(t);return{path:s.path,range:c}}))}for(let o in r.aggregations){let s=r.aggregations[o],c=this.findAllowedDropAggregations(t,s);a.push(...c)}return a}isMacrosNode(){return!!this.schema?.metadata}convertAtomicPropertyToAggregation(t,r){let n=new e,i=t.toString();this.properties[t]&&(n.properties[i]=this.properties[t],n.properties[i].isAtomic=!0),this.addAggregation(t.toString(),n,r.concat(t))}handleAtomicObject(t,r){if(typeof t=="object"){if(Array.isArray(t))for(let n=0;n<t.length;n++)this.convertAtomicPropertyToAggregation(n,r);else for(let n in t)this.convertAtomicPropertyToAggregation(n,r);this.properties={}}}};var zO=class extends Gt{actions=["Delete"];sortableItem="Enabled";isViewNode=!0;sortableCollection="actions";data;getTechnicalName(){let t=this.path[this.path.length-1];if(t&&typeof t=="string"){let r=t.split("::"),n="";if(r[r.length-1].includes("."))for(let i=0;i<r.length;i++)r[i]===AX&&r[i+1]&&(n=r[i+1]);else n=r[r.length-1];if(n){let i=n.split(".");return i[i.length-1]}}return super.getTechnicalName()}markAsCustomAction(){this.custom=!0,this.actions=["OpenSource"],this.sortableItem="Enabled",this.additionalText=vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_ACTION"),this.i18nKey=this.parent?.i18nKey,this.isMacrosNode()?ID(this):this.actions.push("Delete");let t=this.aggregations.position?.properties.anchor;t?.value&&((t.schema.oneOf||[]).some(n=>n.const===t.value)||Sv(this,!1,vt.t("PAGE_EDITOR_CUSTOM_EXTENSION_NO_ANCHOR")))}markAsStandardAction(){this.sortableItem="Readonly",this.additionalText=vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_STANDARD_ACTION"),this.i18nKey=this.parent?.i18nKey,this.removeAction("Delete")}getActionType(){return typeof this.schema?.actionType=="string"?this.schema.actionType:void 0}};var NX=class extends Gt{sortableList=!0;childClass=zO;allowedAnnotationCreationForms=["NativeAction","NativeNavigation"];sortableCollection="actions";i18nKey="ACTIONS";constructor(t,r){super(t,r),r?.properties&&this.schema?.additionalProperties&&this.schema?.metadata?.type!=="Aggregation"&&(this.schemaCreationForms=[{name:"CustomAction",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_ACTIONS_TITLE",disabled:!1}])}addAggregation(t,r,n,i,a){if(r=super.addAggregation(t,r,n,i,a),r instanceof zO&&r.name)switch(r.schema?.actionType){case"Standard":{r.markAsStandardAction();break}case"Copy":{r.sortableItem="Readonly";break}}return r}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),this.formSchema=this.additionalProperties?.aggregations.actions;let o=t||{};for(let s in o){let c=this.aggregations[s];c?.name&&c.schema?.actionType==="Standard"?c.markAsStandardAction():c?.schema&&(c.schema.actionType==="Custom"||!c.schema.annotationPath)&&c.markAsCustomAction()}}getNativeNodeCreationForms(t){return this.parent&&this.parent.name==="footer"&&(this.allowedAnnotationCreationForms=["NativeAction"]),super.getNativeNodeCreationForms(t)}getActionType(t){let r=t.schema?.actionType;return r?r==="Standard"&&!t.schema?.annotationPath?"StandardWithoutAnnotation":r:t.custom?"Custom":"Annotation"}calculateDropRangeEdges(t,r){let n={top:-1,bottom:-1},i={top:["Standard","Copy","Annotation"],bottom:["Criticality","Standard","Copy"]};for(let a=0;a<t.length;a++){let o=t[a],s=this.aggregations[o],c=this.getActionType(s);if(c&&i.top.includes(c)){n.top=a;break}}if(r!=="Custom")for(let a=0;a<t.length;a++){let o=t[a],s=this.aggregations[o],c=this.getActionType(s);c&&i.bottom.includes(c)&&(n.bottom=a+1)}else n.bottom=n.top;return n}getActionsContainers(t){let r=this.getAggregationKeys(!0),n=0;for(let a=r.length-1;a>=0;a--){let o=r[a],s=this.aggregations[o];if(this.getActionType(s)!=="StandardWithoutAnnotation")break;n++}if(t==="Custom"&&n===0)return;let i=this.calculateDropRangeEdges(r,t);if(i.top===-1&&(i.top=i.bottom),i.bottom===-1&&(i.bottom=i.top),!(i.top===-1||i.bottom===-1))return{top:{from:0,to:i.top},bottom:{from:i.bottom,to:r.length-n}}}getAllowedDropRange(t){let r=this.getActionType(t),n=this.getActionsContainers(r),i;if(n)switch(r){case"Custom":{i=[n.top,n.bottom];break}case"Copy":case"Standard":case"StandardWithoutAnnotation":{i=[];break}case"Criticality":{i=[n.top];break}case"Annotation":{i=[n.bottom];break}}return i}};var IX=class extends Gt{actions=["Delete"];getDisplayName(){return this.name?this.name:super.getDisplayName()}};var RX=class extends Gt{sortableList=!1;childClass=IX;i18nKey="ADDITIONALOBJECTS";constructor(t,r){super(t,r),this.schemaCreationForms=[{name:"Generic",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_GENERIC_TITLE",disabled:!1}]}addAggregation(t,r,n,i,a){return r.custom=!0,super.addAggregation(t,r,n,i,a)}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),this.name&&(this.formSchema=this.additionalProperties?.aggregations[this.name])}};var LX=class{validate(t,r){if(t.state===0&&t.variants.length>=1){let n=this.validateVariants(t.variants,t);for(let i in n){let a=t.properties[i]||t.aggregations[i];a&&(a.state=n[i],a.state===1&&bwe(a,[{text:vt.t("PAGE_EDITOR_PROPERTIES_PROPERTY_WARNING_PROPERTY_NOT_ALLOWED",{name:i}),deletable:!0}]))}}for(let n in t.aggregations)this.validate(t.aggregations[n],r?r[n]:{})}validateVariants(t,r){let n={};for(let s in r.properties)r.properties[s].value!==void 0&&(n[s]=r.properties[s].value);for(let s in r.aggregations)r.aggregations[s].value!==void 0&&(n[s]=r.aggregations[s].value);let i=[...t];for(let s in n)i=i.filter(c=>this.validateVariant(c,r,s)===0);if(i.length===0){i=[...t];for(let s in n)i=i.filter(c=>this.validateVariant(c,r,s,!0)===0)}this.unifyVariants(r,i);let a={},o=[...Object.keys(r.properties),...Object.keys(r.aggregations)];for(let s of o)i.some(u=>s in u.properties||s in u.aggregations)?a[s]=0:s in n?a[s]=1:a[s]=2;return a}validateVariant(t,r,n,i=!1){let a=t.aggregations[n]||t.properties[n];if(a===void 0)return i?0:2;let s=(r.properties[n]||r.aggregations[n]||{}).value;if(a.schema){if(a.schema.pattern&&!new RegExp(a.schema.pattern).exec(s.toString()))return 2;if(a.schema.enum&&!a.schema.enum.includes(s)&&!a.freeText)return 2}return 0}*iterateVariantAggregations(t){for(let r of t)for(let[n,i]of Object.entries(r.aggregations))yield[n,i]}unifyVariants(t,r){let n={};for(let[i,a]of this.iterateVariantAggregations(r))a.union&&!n[i]&&(this.applyContextPath(t.aggregations[i],a.path),t.aggregations[i].name=a.path[a.path.length-1].toString(),n[i]=!0);if(Object.keys(n).length){for(let i in n)t.aggregations[i].variants=[];for(let i of r)for(let a in n){let o=i.aggregations[a];o&&(t.aggregations[a].variants=[...t.aggregations[a].variants,...o.variants.length?o.variants:[o]])}}}applyContextPath(t,r){t.path=t.path.slice();for(let n=0;n<r.length;n++)t.path[n]=r[n];for(let n in t.aggregations)this.applyContextPath(t.aggregations[n],r)}};var Gj=class extends Gt{type="Array";constructor(t,r){super(t,r),this.schemaCreationForms=[{name:"Generic",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_GENERIC_TITLE",disabled:!1}]}addAggregation(t,r,n,i){return super.addAggregation(t,r,n,i),this.sortableList=!0,r.sortableItem="Enabled",r.actions=["Delete"],r.schema&&!r.schema.title&&(r.schema.title=vt.t("PAGE_EDITOR_OUTLINE_ARRAY_ITEM",{name:Number.parseInt(t,10)+1})),r.custom=!0,r}updatePropertiesValues(t,r,n,i){if(super.updatePropertiesValues(t,r,n,i),!!Array.isArray(t))for(let a=0;a<t.length;a++){let o=this.aggregations[a];if(!o)continue;let s;if(this.isAtomic)s=t[a];else{let c=this.getPrimaryKey(o);s=c?t[a][c]:void 0}typeof s!="object"&&(o.additionalText=s)}}getPrimaryKey(t){let r=["id","title","key","name"],n=t.schema?t.schema.properties||{}:{},i;for(let a of r)if(a in n){i=a;break}for(let a in n)if(n[a].type==="string"){i=a;break}return i}};var qE=class extends Gt{allowedAnnotationCreationForms=["AnalyticalChart"];name="root";getDefaultNativeCreationForms(){return this.annotationCreationForms}updateAnnotationData(t){this.annotationCreationForms=[],super.updateAnnotationData(t);let r=!!this.aggregations.chart?.isViewNode;if(!!(this.aggregations.table?.aggregations.views?.isViewNode&&!r)&&t?.dialogsContext?.analyticalChartSupport!==void 0){let i={name:"AnalyticalChart",title:t.dialogsContext.analyticalChartSupport.creationTooltip,disabled:!t.dialogsContext.analyticalChartSupport.creationEnabled,kind:DD,visualizationIcon:"Add",buttonText:vt.t("ADD_CHART"),buttonId:"add-chart"};i.disabled&&(i.disabledTitle=i.title),this.annotationCreationForms.push(i)}}};var kX=class extends Gt{updateAnnotationData(t){let r=t?.dialogsContext?.analyticalChartSupport;if(this.actions=[],r){let n=this.getDeletionSupport(r),i={type:"Delete",title:n.deletionTooltip};i.disabled=!n.deletionEnabled,this.actions.push(i)}super.updateAnnotationData(t)}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),!!this.schema?.properties?.annotationPath&&!t?.annotationPath&&(this.hidden=!0)}getDeletionSupport(t={}){if(t?.deletionEnabled){let r=this.findMatchingParent(qE);if(!r?.schema?.properties?.defaultTemplateAnnotationPath&&r){let i=r.aggregations.table?.value;if(typeof i=="object"){let a=i?.annotationPath;this.isComplexScenario(a)&&(t={deletionEnabled:!1,deletionTooltip:vt.t("CHART_DELETION_UNSUPPORTED_BY_SPEC")})}}}return t}isComplexScenario(t){let r=t.split("."),n=r[r.length-1]||"";return n.startsWith("SelectionPresentationVariant")||n.startsWith("PresentationVariant#")}};var HO=class extends Gt{actions=["Delete"];sortableItem="Enabled";isViewNode=!0;sortableCollection="fields";getRawDisplayName(){let t=super.getRawDisplayName();if(!t){let r=this.getTechnicalName();if(r)return r}return t}getTechnicalName(){return ND(this.path)}};var $X=class extends Gt{sortableList=!0;childClass=HO;allowedAnnotationCreationForms=["NativeField","NativeContactField","NativeConnectedFields"];sortableCollection="fields";i18nKey="FIELDS";updateAnnotationData(t){super.updateAnnotationData(t),this.path[0]==="header"&&this.allowedAnnotationCreationForms.splice(this.allowedAnnotationCreationForms.indexOf("NativeConnectedFields"))}};var MX=class extends HO{sortableList=!0;childClass=HO};var RD=class extends Gt{actions=["Delete"];sortableItem="Enabled";isViewNode=!0;getRawDisplayName(){let t=super.getRawDisplayName();if(!t){let r=this.getTechnicalName();if(r)return r}return t}getTechnicalName(){let t=this.path[this.path.length-1];if(t){let n=t.toString().split("::"),i=n[n.length-1];if(i)return i}}markAsCustomFilterField(){this.custom=!0,this.actions=["OpenSource"],this.isMacrosNode()||this.actions.push("Delete"),this.sortableItem="Enabled",this.additionalText=vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_FILTER_FIELD"),this.i18nKey=this.parent?.i18nKey,this.isMacrosNode()&&ID(this);let t=this.properties.anchor;t?.value&&((t.schema.oneOf||[]).some(n=>n.const===t.value)||Sv(this,!1,vt.t("PAGE_EDITOR_CUSTOM_EXTENSION_NO_ANCHOR")))}addProperty(t,r){let n=super.addProperty(t,r);return t==="property"&&(n.disabled=!0),n}};var FX=class extends Gt{sortableList=!0;allowedAnnotationCreationForms=["NativeFilterFields"];childClass=RD;i18nKey="FILTER_FIELDS";constructor(t,r){super(t,r);let n=r?.additionalProperties;typeof n=="object"&&n.$ref&&!this.isMacrosNode()&&(this.schemaCreationForms=[{name:"CustomFilterField",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_FILTER_FIELDS_TITLE",disabled:!1}])}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),this.formSchema=this.additionalProperties?.aggregations.selectionFields;let o=t||{};for(let s in o){let c=this.aggregations[s];c?.schema&&!c.schema.annotationPath&&c.markAsCustomFilterField()}}};var fMt=require("node:path");var dMt=dt(Zd()),Av=class extends Gt{filePath;constructor(t,r){super(t,r),this.path=["macros"],this.isViewNode=!0,this.virtual=!0,this.allowedAnnotationCreationForms=[];let n=this.getCreationForms();this.annotationCreationForms=n.internal,this.schemaCreationForms=n.external;let i=this.schema?.metadata?.filePath;i&&this.setFilePath(i)}getCreationForms(){return{internal:[{name:"MacrosChart",kind:DD,disabled:!1,title:"ADD_BUILDING_BLOCK_CHART"},{name:"MacrosFilterBar",kind:DD,disabled:!1,title:"ADD_BUILDING_BLOCK_FILTERBAR"},{name:"MacrosTable",kind:DD,disabled:!1,title:"ADD_BUILDING_BLOCK_TABLE"}],external:[]}}getDisplayName(){return vt.t("PAGE_EDITOR_OUTLINE_NODE_BUILDING_BLOCK")}getNativeNodeCreationForms(){return this.annotationNodeId?this.annotationCreationForms:[]}setFilePath(t){this.filePath=(0,fMt.join)(dMt.DirName.Webapp,t)}updateAnnotationData(t){if(super.updateAnnotationData(t),t?.dialogsContext?.analyticalChartSupport!==void 0){let r=this.annotationCreationForms.find(n=>n.name==="MacrosChart");r&&(r.disabled=!t.dialogsContext.analyticalChartSupport.creationEnabled,r.disabled&&(r.tooltip=t.dialogsContext.analyticalChartSupport.creationTooltip))}}};var EMt=require("node:path"),kD=dt(Pc());var Jm=class extends Gt{actions=["Delete"];title;id;position;data;useDescriptionAsId;isViewNode=!0;sortableCollection="sections";constructor(t,r){super(t,r),this.sortableItem="Enabled"}setTitle(t){this.title=t}setId(t){this.id=t}getRawDisplayName(){return this.title||this.getSectionId()||super.getRawDisplayName()}getSectionId(t=!0){if(this.schema){if(this.schema.title?.startsWith(hwe)){let r=this.schema.title.split(hwe);return r.length>1?r[r.length-1]:r[0]}else if(t&&this.useDescriptionAsId&&this.schema.description)return this.schema.description}if(this.data&&"id"in this.data)return this.data.id}markAsReplaced(t){this.inactive=!0,this.additionalText=vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_SECTION_REPLACED_WITH",{section:t})}markAsCustomSection(t,r,n){this.custom=!0,this.actions=["Delete",n||"OpenSource"],this.sortableItem="Enabled",this.additionalText=vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_SECTION"),this.data=t,this.i18nKey=r}getTechnicalName(){return this.getSectionId()}getFormattedName(){let t=this.name,r=`${Z$t}.`;return t?.includes(r)&&(t=t.replace(r,"")),t}};var Bf=dt(Pc());var Kj="custom",LD=class extends Gt{customSections=[];sections=[];sortingApproach="Normal";allowedAnnotationCreationForms=void 0;sortableCollection="sections";constructor(t,r){super(t,r),this.childClass=Jm,r?.properties?.custom&&(this.schemaCreationForms=[{name:"CustomSection",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_SECTIONS_TITLE",disabled:!1}]),this.sortableList=!0,this.i18nKey="SECTIONS"}updatePropertiesValues(t,r,n,i,a,o){if(super.updatePropertiesValues(t,r,n,i,a,o),this.formSchema=this.aggregations[Kj],this.sortingApproach=this.getSortingApproach(),delete this.aggregations[Kj],this.correctSectionData(),this.formSchema&&(this.customSections=t&&Kj in t?t[Kj]:[],this.customSections.length)){this.sections=Object.keys(this.aggregations);let s=[...this.sections];for(let p in s){let f=this.aggregations[s[p]];this.traverseCustomSections(f.getSectionId()||s[p],this.customSectionFactory.bind(this,r,n,i,o))}let c=this.customSections.filter(p=>{for(let f in this.aggregations)if(this.aggregations[f].data===p)return!1;return!0});for(let p of c)this.customSectionFactory(r,n,i,o,p);let u=this.aggregations;this.aggregations={};let l=0;for(let p of this.sections)this.aggregations[p]=u[p],this.aggregations[p].order=l,l++}}onPropertiesUpdated(){this.customSections.length&&!this.isV4()&&uMt(this,"SECTION_UNDELETABLE_LAST_NATIVE_NODE")}traverseCustomSections(t,r){let n=this.customSections.filter(a=>this.isSectionMatchesRelatedFacet(a.relatedFacet,t)),i=this.sortingApproach==="WithIds";for(let a of n)r(a),i&&"id"in a&&this.traverseCustomSections(a.id,r)}customSectionFactory(t,r,n,i,a){if(!this.formSchema)return;let o=this.customSections.indexOf(a),s=this.formSchema.getCopy(Jm);if(s.markAsCustomSection(a,this.i18nKey),i){let p=a,{fragmentName:f}=p,d=i?.definitions[`CustomExtensionFragment<${f}>`];if(d&&s.aggregations.controls){let h=new Av(void 0,d);s.addAggregation("controls",h,s.path,void 0,!0),i.parse(s.aggregations.controls,d,void 0,void 0,n,{filePath:d.metadata?.filePath})}}s.updatePropertiesValues(a,t,r,n,i?.annotations),s.setTitle(a.title),s.position=a.relativePosition;let c=this.storeSection(a);this.addAggregation(c,s,this.path.concat([Kj,o]));for(let p of _we){let f=s.properties[p];f&&(f.schema=DX(s,f.schema))}let u=this.formSchema.properties.relatedFacet?.schema.oneOf?this.formSchema.properties.relatedFacet?.schema.oneOf:[],l=this.isV4()&&!a.relatedFacet?!0:u.some(p=>p.const===a.relatedFacet);Sv(s,l,vt.t("PAGE_EDITOR_CUSTOM_SECTION_NO_FACET"))}correctSectionData(){let t=this.formSchema?.properties.relatedFacet?.schema.oneOf?this.formSchema.properties.relatedFacet.schema.oneOf:[];for(let r in this.aggregations){let n=this.aggregations[r];if(n.custom)continue;this.isV4()&&(n.useDescriptionAsId=!0),n.description&&n.setTitle(n.description);let i=n.getSectionId()||r,a=t.find(o=>this.isSectionMatchesRelatedFacet(i,o.const));a?.description&&(n.setTitle(a.description),n.setId(a.const))}}isSectionMatchesRelatedFacet(t="",r=""){return t.replace(/@/g,"")===r.replace(/@/g,"")}findSectionInsertPosition(t){let{relativePosition:r,relatedFacet:n}=t,i=this.checkRelatedPosition(r,Bf.v2.SectionPosition.AfterFacet,Bf.v2.SectionPosition.ReplaceFacet),a=this.findReferenceSection(n);if(!a)return this.sections.length;let o=this.checkRelatedPosition(r,Bf.v2.SectionPosition.ReplaceFacet),s=this.checkRelatedPosition(r,Bf.v2.SectionPosition.BeforeFacet),c=o?[Bf.v2.SectionPosition.ReplaceFacet]:[Bf.v2.SectionPosition.AfterFacet,Bf.v2.SectionPosition.ReplaceFacet],u=a.index;if(i&&this.sortingApproach==="Normal")for(let l=u+1;l<this.sections.length;l++){let p=this.aggregations[this.sections[l]];if(p?.custom&&p.position&&this.checkRelatedPosition(p.position,...c))u++;else break}return u+(s?0:1)}findReferenceSection(t){for(let r=0;r<this.sections.length;r++){let n=this.sections[r],i=this.aggregations[n],a=i?.getSectionId?.()??n;if(a&&this.isSectionMatchesRelatedFacet(a,t))return{index:r,aggregation:i}}}storeSection(t){let r=this.findSectionInsertPosition(t),n=this.getFreeSectionId("id"in t&&typeof t.id=="string"?t.id:t.title);this.sections.splice(r,0,n);let i=this.findReferenceSection(t.relatedFacet);return i?.aggregation&&this.checkRelatedPosition(t.relativePosition,Bf.v2.SectionPosition.ReplaceFacet)&&i.aggregation.markAsReplaced(t.title),n}getFreeSectionId(t){let r=1,n=t??"missingId";t=n;let i=Object.keys(this.aggregations).filter(o=>this.sections.indexOf(o)===-1),a=[...this.sections,...i];for(;a.includes(t);)t=n+r,r++;return t}checkRelatedPosition(t="",...r){let n=new Map([[Bf.v2.SectionPosition.AfterFacet,"after"],[Bf.v2.SectionPosition.BeforeFacet,"before"],[Bf.v2.SectionPosition.ReplaceFacet,"replace"]]);t=t.toLowerCase();for(let i of r){let a=n.get(i);if(a&&t.includes(a))return!0}return!1}getSortingApproach(){return this.isV4()?"WithIds":"Normal"}isV4(){return!!this.formSchema?.properties.id}getNativeNodeCreationForms(t){if(!t)return[];let r=super.getNativeNodeCreationForms(t),n=r.find(i=>i.name==="AnalyticalChart");return n&&!n.disabled&&(n.disabled=!t.dialogsContext?.analyticalChartSupport?.creationEnabled,t.dialogsContext?.analyticalChartSupport?.creationTooltip&&(n.disabledTitle=t.dialogsContext.analyticalChartSupport.creationTooltip)),r}};var hMt=dt(Pc()),GO=class extends Gt{title;originalIndex;isViewNode=!0;actions=["Delete"];sortableItem="Enabled";criticality;setTitle(t){this.title=t}getRawDisplayName(){return this.title||super.getRawDisplayName()}validateColumnPositioning(){let t=this.value&&typeof this.value=="object"?this.value:{},r=this.aggregations.position?.schema?.properties?.anchor?.enum,n=this.schema?.properties?.anchor?.oneOf,i=!1;if(this.isMacrosNode()){ID(this,t);let a=n??[],o=BO(t,["anchor"]);i=o?a.some(s=>s.const===o):!0}else{let a=r??[],o=BO(t,["position","anchor"]);i=o?a.includes(o):!0}Sv(this,i,vt.t("PAGE_EDITOR_CUSTOM_EXTENSION_NO_ANCHOR"))}markAsCustomColumn(t){let{pageType:r,originalIndex:n,columnExtension:i,isExtensionTypeSupported:a,i18nKey:o,tableExtension:s="ResponsiveTableColumnsExtension",isV4:c=!1,tabkey:u}=t;this.custom=!0,this.actions=["OpenSource"],this.isMacrosNode()||this.actions.push("Delete"),this.sortableItem=!a||s===i?"Enabled":"Excluded";let l=i??"Unknown";u&&r===hMt.PageType.ListReport?this.additionalText=a?vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_COLUMN_WITH_EXTENSION_TAB",{tabkey:u,extension:vt.t(`PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_COLUMN_${l}`)}):vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_COLUMN_TAB",{tabkey:u}):this.additionalText=a?vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_COLUMN_WITH_EXTENSION",{extension:vt.t(`PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_COLUMN_${l}`)}):vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_COLUMN"),this.originalIndex=n,this.i18nKey=o,a&&s!==l&&(this.state=1,this.messages=[{text:vt.t("PAGE_EDITOR_CUSTOM_COLUMN_UNUSED_COLUMN",{tableType:J$t.get(s)}),type:"info"}],this.inactive=!0),c&&this.validateColumnPositioning()}getTechnicalName(){return ND(this.path)}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),this.updateMoveProperties()}updateMoveProperties(){(this.isActionColumn()||this.isNavigationColumn())&&(this.sortableCollection=!this.criticality||this.criticality==="None"?"actions":void 0,this.additionalText=vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_ACTION_COLUMN"))}isActionColumn(){return!!this.name?.startsWith(`${AX}${fwe}`)}isNavigationColumn(){return!!this.name?.startsWith(`${CX}${fwe}`)}};var UE=dt(Pc());var gMt=dt(Pc()),mMt=e=>!e.type||e.type===gMt.ArtifactType.Annotation,jX=e=>{let t=[],r=e.locations?[...e.locations]:[];for(let n=r.length-1;n>=0;n--){let i=r[n];mMt(i)&&(t.push(i),r.splice(n,1))}if(e.parent&&t.length){let n=e.parent.locations||[];e.parent.locations=n.filter(i=>!mMt(i)),e.parent.locations.unshift(...t)}e.locations=r};var Yj="custom",VRn=new Map([[UE.PageType.ObjectPage,"ResponsiveTableColumnsExtension"],[UE.PageType.ListReport,"ResponsiveTableColumnsExtension"],[UE.PageType.AnalyticalListPage,"AnalyticalTableColumnsExtension"]]),VX=class extends Gt{customColumns=[];columnKeys=[];tableColumnExtensionType;allowedAnnotationCreationForms=["Basic","Rating","Chart","Progress","NativeAction","Contact","NativeNavigation"];isV4;sectionId;sortableCollection="actions";constructor(t,r){if(super(t,r),this.childClass=GO,r?.properties){let n;r.properties?.custom?n="CustomColumn":typeof r.additionalProperties=="object"&&r.additionalProperties.$ref&&r.additionalProperties.$ref.indexOf("TableCustomColumn")>-1?(n="CustomColumnV4",this.isV4=!0):this.isMacrosNode()&&(this.isV4=!0),n&&(this.schemaCreationForms=[{name:n,kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_COLUMNS_TITLE",disabled:!1}])}this.sortableList=!0,this.i18nKey="COLUMNS"}groupCustomColumnsByExtension(){let t=new Map,r=[...this.customColumns].sort((n,i)=>{let a=n.columnIndex??0,o=i.columnIndex??0;return a===o?0:a>o?1:-1});for(let n of r){let i=t.get(n.extensionType);i||(i=[],t.set(n.extensionType,i)),i.push(n)}return t}ensureColumnOrder(){let t=this.getAggregationKeys();for(let r=0;r<t.length;r++){let n=this.aggregations[t[r]];n&&(n.order=r)}}updatePropertiesFromCustomAggregation(t,r,n,i){let a=this.formSchema;this.customColumns=t&&Yj in t?t[Yj]:[],n===UE.PageTypeV2.ObjectPage&&(this.sectionId=this.parent?.parent?.schema?.keys?.reduce(o=>o.name==="ID").value),this.customColumns.length&&(this.ensureColumnOrder(),this.columnKeys=Object.keys(this.aggregations),this.groupCustomColumnsByExtension().forEach(s=>{for(let c in s){let u=a?.getCopy(GO),l=s[c],p=this.customColumns.indexOf(l);u.markAsCustomColumn({pageType:n,originalIndex:p,columnExtension:l.extensionType,isExtensionTypeSupported:this.isExtensionTypeSupported(),i18nKey:this.i18nKey,tableExtension:this.tableColumnExtensionType,isV4:this.isV4,tabkey:l.tabKey}),u.updatePropertiesValues(l,r,n,i),u.setTitle(l.text);let f=this.getFreeId(l.id||l.columnKey||"customColumn",this.columnKeys);this.columnKeys.push(f);let d=this.doesColumnExtensionMatchTableType(l)?l.columnIndex:this.getMaxColumnIndex(this.customColumns)+1;this.addAggregation(f,u,this.path.concat([Yj,p]),d)}}))}updatePropertiesValues(t,r,n,i,a){if(super.updatePropertiesValues(t,r,n,i,a),this.resolveTableColumnExtensionType(r,n,i),!this.isV4)this.formSchema=this.aggregations[Yj],delete this.aggregations[Yj],this.updatePropertiesFromCustomAggregation(t,r,n,i);else{this.formSchema=this.additionalProperties?.aggregations.columns;let o=t||{};for(let s in o){let c=this.aggregations[s];c.schema&&!c.schema.annotationPath&&(c.originalIndex=c.schema.propertyIndex,c.markAsCustomColumn({pageType:n,originalIndex:c.schema.propertyIndex,columnExtension:this.tableColumnExtensionType,isExtensionTypeSupported:this.isExtensionTypeSupported(),i18nKey:this.i18nKey,tableExtension:this.tableColumnExtensionType,isV4:this.isV4,tabkey:c.properties.tabkey?.value}))}}}getFreeId(t,r){let n=1,i=t;for(;r.includes(t);)t=i+n,n++;return t}resolveTableColumnExtensionType(t,r,n){let i=n.splice(0,n.length-1);i.push("type");let a=BO(t,i);this.tableColumnExtensionType=typeof a=="string"&&a in UE.v2.TableTypeV2?dwe.get(a):VRn.get(r)}doesColumnExtensionMatchTableType(t){return!this.isExtensionTypeSupported()||t.extensionType===this.tableColumnExtensionType}isExtensionTypeSupported(){return!!this.formSchema?.properties.extensionType}getMaxColumnIndex(t){let r=this.getMaxOrder();for(let n of t)n.columnIndex!==void 0&&r<n.columnIndex&&(r=n.columnIndex);return r}updateLocations(t,r){super.updateLocations(t,r),jX(this)}};var qX=class extends Gt{getTechnicalName(){return(this.parent?ND(this.parent.path,!0):void 0)||super.getTechnicalName()}};var UX=class extends Gt{updateLocations(t,r){super.updateLocations(t,r),jX(this)}};var BX=class extends Gt{sortableCollection="visualFilters";actions=["Delete"];isViewNode=!0};var zX=class extends Gt{sortableList=!0;childClass=BX;i18nKey="VISUAL_FILTERS"};var BE=class extends LD{constructor(t,r){super(t,r);let n=r?.additionalProperties;typeof n=="object"&&n.$ref&&(this.schemaCreationForms=[{name:"CustomSection",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_SECTIONS_TITLE",disabled:!1}])}updatePropertiesValues(t,r,n,i,a,o){super.updatePropertiesValues(t,r,n,i,a,o),this.formSchema=this.additionalProperties?.aggregations?.sections;let s=t||{};this.removeObsoleteAggregations();for(let u in s){let l=this.aggregations[u];l?.schema&&!l.schema.annotationPath&&(l.markAsCustomSection(),o&&this.parseBuildingBlocks({parser:o,page:r,pageType:n},l,u,s,i))}if(this.isSectionsMerged())for(let u in this.aggregations)this.aggregations[u].custom&&(this.aggregations[u].sortableItem="Excluded")}removeObsoleteAggregations(){let t=this.schema?.properties||{};for(let r in this.aggregations)r in t||delete this.aggregations[r]}parseBuildingBlocks(t,r,n,i,a){let{parser:o,page:s,pageType:c}=t,u=i[n],{fragmentName:l}=u,p=o?.definitions[`CustomExtensionFragment<${l}>`];if(p&&r.aggregations.controls){let f=new Av(void 0,p);r.addAggregation("controls",f,a.concat(r.path[r.path.length-1],"controls"),0,!0),o.parse(f,p,void 0,void 0,f.path,{filePath:p.metadata?.filePath});let d=BO(r.value||{},["controls"]);d&&typeof d=="object"&&f.updatePropertiesValues(d,s,c,a,o?.annotations)}}isSectionsMerged(){return!1}};var HX=class extends BE{allowedAnnotationCreationForms=["NativeSection","DataPointSection","ProgressSection","RatingSection","ChartSection"];constructor(t,r){super(t,r);let n=r?.additionalProperties;typeof n=="object"&&n.$ref&&(this.schemaCreationForms=[{name:"CustomHeaderSection",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_SECTIONS_TITLE",disabled:!1}])}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),this.formSchema=this.additionalProperties?.aggregations?.sections;let o=t||{};for(let s in o){let c=this.aggregations[s];if(c?.schema&&!c.schema.annotationPath){let u=c.properties.templateEdit?.value,l=c.properties.fragmentName?.value,p;typeof l=="string"&&typeof u=="string"&&(p={type:"OpenSource",subActions:[{id:l,text:vt.t("CUSTOM_HEADER_SECTION_TEMPLATE")},{id:u,text:vt.t("CUSTOM_HEADER_SECTION_TEMPLATE_EDIT")}]}),c.markAsCustomSection(void 0,void 0,p)}}}};var GX=class extends BE{constructor(t,r){super(t,r);let n=r?.additionalProperties;typeof n=="object"&&n.$ref&&(this.schemaCreationForms=[{name:"CustomSubSection",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_SECTIONS_TITLE",disabled:!1}])}updatePropertiesValues(t,r,n,i,a,o){super.updatePropertiesValues(t,r,n,i,a,o),this.formSchema=this.additionalProperties?.aggregations?.subsections}isSectionsMerged(){let t=0;for(let r in this.aggregations){let n=this.aggregations[r];if("subsections"in n.aggregations)return!1;n.custom||t++}return t>0}};var KO=class extends Gt{title;actions=[];sortableItem="Enabled";sortableCollection="views";constructor(t,r){super(t,r),r?.key&&!r.annotationPath&&!r.properties?.annotationPath&&(r.annotationPath=`${Hj}${r.key})`)}getRawDisplayName(){return this.title||super.getRawDisplayName()}markAsCustomView(){this.custom=!0,this.actions=["Delete","OpenSource"],this.sortableItem="Enabled",this.additionalText=vt.t("PAGE_EDITOR_OUTLINE_NODE_DESC_CUSTOM_VIEW"),this.i18nKey=this.parent?.i18nKey,this.properties.label?.value&&(this.title=this.properties.label.value)}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),this.isTableView()?this.icon="Table":this.isChartView()?this.icon="Chart":this.icon="Sections",this.isAnnotationView()&&!this.schema?.annotationPath&&this.properties.annotationPath&&(this.properties.annotationPath.messages=[{type:"warning",text:vt.t("PAGE_EDITOR_PROPERTIES_VIEW_NO_ANNOTATION_PATH")}])}isTableView(){return"columns"in this.aggregations}isChartView(){return!("columns"in this.aggregations)&&"toolBar"in this.aggregations}isAnnotationView(){return!this.custom&&"annotationPath"in this.properties||!this.custom&&this.schema?.annotationPath&&!this.schema?.annotationPath.startsWith(Hj)}};var YO=class extends Gt{sortableList=!0;childClass=KO;allowedAnnotationCreationForms=["TableView","AnalyticalChartView","CustomViewV4"];sortableCollection="views";sortableConfigOnly=!0;i18nKey="VIEWS";updateAnnotationData(t){if(super.updateAnnotationData(t),t){this.toggleChartForm(this.annotationCreationForms,t);for(let r in this.aggregations){let n=this.aggregations[r],i=this.getViewDeleteAction(n,t),a=n.actions||[];a.push(i),n.actions=a}}}updatePropertiesValues(t,r,n,i,a){super.updatePropertiesValues(t,r,n,i,a),this.formSchema=this.additionalProperties?.aggregations.views,this.formSchema?.properties?.template&&(this.schemaCreationForms=[{name:"CustomViewV4",kind:go,title:"PAGE_EDITOR_OUTLINE_ADD_CUSTOM_VIEW_TITLE",disabled:!1}]);let o=t||{};if(Object.keys(o).length!==0)for(let s in o){let c=this.aggregations[s];c?.schema&&!c?.schema.properties?.annotationPath&&(!c.schema.annotationPath||c.schema.annotationPath.startsWith(Hj))&&c.markAsCustomView()}}getViewDeleteAction(t,r){let n=t.annotationNodeId,i=!0,a=this.getAnnotationViewCount();return n?i=UO(r.dialogsContext?.suppressTableViewDeletionNodeId||[],n):(a>1||a===1&&t.custom)&&(i=!1),{type:"Delete",disabled:i,title:vt.t(i?"TABLE_VIEW_DELETE_DISABLED_TOOLTIP":"PAGE_EDITOR_OUTLINE_DELETE_TOOLTIP")}}toggleChartForm(t,r){let n=t.find(i=>i.name==="AnalyticalChartView");n&&r.dialogsContext?.analyticalChartSupport&&(r.dialogsContext.analyticalChartSupport.addToMultiViewEnabled?(n.disabled=!1,delete n.disabledTitle):(n.disabled=!0,n.disabledTitle=r.dialogsContext.analyticalChartSupport.addToMultiViewTooltip))}getAnnotationViewCount(){let t=0;for(let r in this.aggregations){let n=this.aggregations[r];n instanceof KO&&n.isAnnotationView()&&t++}return t}};var qRn="array",yMt="object",Twe="sap.fe.macros.Table",vMt=[["table","quickVariantSelection","variants"],["table","quickVariantSelectionX","variants"]],xwe=(e,t,r)=>{let n=r,i=e.split("/").length-1,a=0;for(;a<i;)n=n?.parent,a++;return t.endsWith(`table/${e}`)||n instanceof KO&&t.endsWith(`/${e}`)},URn=(e,t,r)=>!!r?.additionalProperties?.$ref?.includes("CustomSectionActionOP")&&!!t?.name&&e.endsWith(`${t.name}/actions`),Owe=(e,t)=>t?.schema?.metadata?.controlName===e,BRn=(e,t)=>t?.metadata?.controlName===e,bMt=(e,t)=>{let r=t?.additionalProperties;return t?.metadata?.type==="Aggregation"&&typeof r=="object"&&r.$ref===`#/definitions/${e}`},zRn=[{aggregation:BE,fn:(e,t,r)=>{let i=r?.additionalProperties?.$ref?.includes("ObjectPageCustomSectionFragment");return e==="sections"&&!!i}},{aggregation:LD,fn:e=>e==="sections"},{aggregation:VX,fn:(e,t,r)=>xwe("columns",e,t)||bMt("sap.fe.macros.table.Column",r)&&Owe(Twe,t)},{aggregation:UX,fn:(e,t)=>xwe("toolBar",e,t)},{aggregation:$X,fn:e=>e.endsWith("form/fields")},{aggregation:RX,fn:e=>e.endsWith("actions/RelatedApps/additionalSemanticObjects")},{aggregation:MX,fn:(e,t,r)=>r?.dataType==="ConnectedFields"},{aggregation:NX,fn:(e,t,r)=>URn(e,t,r)||["form/actions","header/actions","footer/actions"].some(n=>e.endsWith(n))||xwe("toolBar/actions",e,t)||bMt("sap.fe.macros.table.Action",r)&&Owe(Twe,t)},{aggregation:FX,fn:(e,t)=>e.endsWith("filterBar/selectionFields")||e.endsWith("/filterFields")&&Owe("sap.fe.macros.FilterBar",t)},{aggregation:zX,fn:e=>e.endsWith("filterBar/visualFilters")},{aggregation:qX,fn:(e,t,r)=>e==="table"||e.endsWith("/table")&&t instanceof Jm||BRn(Twe,r)},{aggregation:HX,fn:e=>e.endsWith("header/sections")},{aggregation:qE,fn:e=>e===""},{aggregation:kX,fn:e=>e==="chart"},{aggregation:YO,fn:e=>e.endsWith("table/views")},{aggregation:GX,fn:(e,t)=>e.endsWith("/subsections")&&t instanceof Jm}],HRn=["annotationPath"],KX=class{name;pageType;root=this.prepareAggregation();data;originalData;definitions={};excludeProperties=["$schema"];schema;validator=new LX;pendingNodes=[];constructor(t,r,n,i,a){this.name=t,this.pageType=r,this.data=n,this.originalData={page:structuredClone(this.data),annotations:a,schema:i},this.schema=JSON.parse(i),this.init(a)}init(t){if(this.schema.definitions)for(let i in this.schema.definitions)this.definitions[`#/definitions/${i}`]=this.schema.definitions[i];let r=JSON.parse(this.originalData.schema);this.root=this.prepareAggregation(void 0,{properties:r.properties}),this.parseSchema(this.root,r,{subnodes:t.nodes},void 0,[],{filePath:this.data.$filePath}),this.readAdvancedPropertiesData(this.root,this.data);let n={definitions:this.schema.definitions,parse:this.parseSchema.bind(this),annotations:t};this.root.updatePropertiesValues(this.data,this.data,this.pageType,[],t,n),this.validator.validate(this.root,this.data),this.updateViewNodes(this.root),this.pendingNodes=[],this.afterInit(t)}updatePropertyFromSchema(t,r,n){if(!(t in r.properties))r.properties[t]=r.addProperty(t,n),r.properties[t].freeText=this.isFreeText(n);else if(n.enum){let i=r.properties[t].schema.enum;i=i?i.concat(n.enum):n.enum,r.properties[t].schema.enum=i?i.filter((a,o)=>i&&i.indexOf(a)===o):[]}}getContextForMacrosNode(t,r){for(let n in r){let i=r[n],a="subnodes"in i?i.subnodes:[];for(let o in a)if(a[o].macroNodeId===t)return i}}schemaParsers=[t=>(t.currentNode.const&&!t.currentNode.enum&&(t.currentNode.enum=[t.currentNode.const]),!0),t=>{let{currentNode:r}=t;return!r.hidden},t=>{let{currentNode:r,name:n}=t;if(n===void 0)return!0;if(this.isAggregation(r)){t.path=t.path.concat([t.aggregation.type==="Array"?Number.parseInt(n,10):n]);let i=r.displayName||n,a=r.type===yMt?"Object":"Array";if(t.aggregation=t.aggregation.addAggregation(i,t.aggregation.aggregations[i]||this.prepareAggregation(t.path,r,t.aggregation,a),t.path),t.aggregation.type==="Array")return t.aggregation.schema=r,this.updateFormSchema(t.aggregation),this.copySchemaProperties(t.aggregation,r,n),!1}else this.isProperty(r)&&this.updatePropertyFromSchema(n,t.aggregation,r);return!0},t=>{let{aggregation:r,currentNode:n}=t,i=t.currentAnnotationNode;if(r instanceof Av&&(i=this.originalData.annotations.nodes.find(a=>"nodeType"in a&&a.nodeType==="macros"),r.annotationNodeId=i?.nodeId),n.metadata?.internalId&&!i){let a=this.originalData.annotations.nodes;a=a.filter(o=>"nodeType"in o&&o.nodeType==="macros"),i=t.currentAnnotationNode=this.getContextForMacrosNode(n.metadata.internalId,a)}if(!n.$ref&&n.annotationPath){let a=[];i&&!VE(i)&&(a=i.subnodes);let o=oMt(n.annotationPath,this.originalData.annotations.nodes,a,i?.annotationPath,r.order);o&&(t.currentAnnotationNode=o,r.annotationNodeId=o.nodeId)}return!0},t=>{for(let r of Array.from(this.schemaReferenceParsers))if(r[1](t))break;return!0},t=>{let{aggregation:r,currentNode:n,name:i}=t;return this.copySchemaProperties(r,n,i),!0},t=>{let{aggregation:r,currentNode:n,currentAnnotationNode:i,name:a,path:o,context:s}=t;return typeof n.additionalProperties=="object"&&(r.additionalProperties=this.prepareAggregation(),this.parseSchema(r.additionalProperties,n.additionalProperties,i,a,o,s),this.isSchemaAtomic(n.additionalProperties)&&this.updateFormSchema(r,a)),!0},t=>{let{aggregation:r,currentNode:n,currentAnnotationNode:i,name:a,path:o,context:s}=t;return typeof n.patternProperties=="object"&&(r.pattern=Object.keys(n.patternProperties)[0],n.additionalProperties=n.patternProperties[r.pattern],r.additionalProperties=this.prepareAggregation(),this.parseSchema(r.additionalProperties,n.patternProperties[r.pattern],i,a,o,s),this.updateFormSchema(r,a)),!0},t=>{let{aggregation:r,currentNode:n}=t;if(n.required)for(let i of n.required){let a=r.properties[i];a&&(a.required=!0)}return!0},t=>{let{aggregation:r,currentNode:n,name:i}=t;return n.displayName&&i&&n.type==="object"&&r.addUnionName(n.displayName,i),!0},t=>{let{name:r="",aggregation:n,currentNode:i,context:a}=t,{metadata:o}=i,s=n.properties[r];if(a.filePath&&o){let{position:c}=o,u=[];c&&u.push({fileUri:(0,EMt.join)(kD.DirName.Webapp,a.filePath),range:{start:{line:c.startLine-1,character:c.startColumn-1},end:{line:c.endLine-1,character:c.endColumn}},relative:!0,type:kD.ArtifactType.XMLProperty}),s?s.locations=u:n.name===r&&(n.locations=u)}return!0},t=>{let{path:r,name:n="",aggregation:i}=t;return r&&vMt.some(a=>vwe(r,a))&&this.updateFormSchema(i,n),!0}];schemaReferenceParsers=new Map([["$ref",t=>{let{aggregation:r,currentNode:n,currentAnnotationNode:i,name:a,path:o,context:s}=t;if(!n.$ref)return!1;let c=this.definitions[n.$ref]?{...this.definitions[n.$ref]}:{};for(let u of Object.keys(n)){let l=HRn.includes(u);u!=="$ref"&&!(l&&c[u])&&(c[u]=n[u])}return this.parseSchema(r,c,i,a,o,s),!0}],["anyOf",t=>{let{aggregation:r,currentNode:n,currentAnnotationNode:i,name:a,path:o,context:s}=t;if(!n.anyOf)return!1;for(let c of n.anyOf)this.parseSchema(r,c,i,a,o,s);return(Object.keys(n.anyOf).length>1||Array.isArray(n.anyOf)&&n.anyOf.length>1)&&this.createAnyOfPropertiesVariations(n.anyOf,t),!0}],["properties",t=>{let{aggregation:r,currentNode:n,currentAnnotationNode:i,path:a,context:o}=t;if(!n.properties)return!1;let s=Object.keys(n.properties).filter(l=>!this.excludeProperties.includes(l)),c=n.properties,u=s.some(l=>n.properties&&n.properties[l]?.propertyIndex!==void 0);c&&s.length&&u&&s.sort(this.propertySorter.bind(this,c));for(let l of s)this.parseSchema(r,n.properties[l],i,l,a,o);return!0}],["items",t=>{let{aggregation:r,currentNode:n,currentAnnotationNode:i,path:a,context:o}=t;if(!n.items)return!1;if(Array.isArray(n.items))for(let s=0;s<n.items.length;s++)this.parseSchema(r,n.items[s],i,s.toString(),a,o);else this.parseSchema(r,n.items,i,void 0,a,o);return!0}]]);createAnyOfPropertiesVariations(t,r){let{aggregation:n,currentAnnotationNode:i,name:a,path:o,context:s}=r;for(let c of t){let u=this.prepareAggregation();this.parseSchema(u,c,i,a,o,s);let l=a;if(a&&!u.aggregations[a]){let f=Object.keys(u.aggregations);l=f.length>0?f[0]:a}let p=n;l&&(p=n.aggregations[l],u=u.aggregations[l]),u&&p&&p.variants.push({aggregations:u.aggregations,properties:u.properties})}a&&n.properties[a]&&(n.properties[a].freeText=this.isFreeText(t))}parseSchema(t,r,n,i,a,o){let s={aggregation:t,currentNode:r,currentAnnotationNode:n,name:i,path:a,context:o};for(let c of this.schemaParsers)if(!c.call(this,s))break}copySchemaProperties(t,r,n){if(n)if(t.properties[n])this.storeInnerProperties(t.properties[n],["pattern","description","i18nClassification","artifactType","minimum","displayName","messages"],r);else{let i=t.aggregations[n]||t;this.storeInnerProperties(i,["description","isViewNode","artifactType","messages"],r)}}isProperty(t){return!t.$ref&&t.type!=="object"&&t.type!=="array"&&!t.anyOf}isAggregation(t){return(t.type===yMt||t.type===qRn)&&!t.$ref}handleAdditionalProperties(t,r){let n=[...Object.keys(t.properties),...Object.keys(t.aggregations)];for(let i of Object.keys(r))if(!n.includes(i)&&t.additionalProperties){let a=t.schema?t.schema.additionalProperties||t.schema.additionalItems:void 0;if(typeof a=="object"){this.parseSchema(t,a,void 0,i,t.path,{});let o=t.aggregations[i];o?.isViewNode&&o.description&&delete o.description}}}readAdvancedPropertiesData(t,r){if(this.handleAdditionalProperties(t,r),t&&t.type==="Array"&&t.schema){let n=t.schema,i=this.getSchemaArrayItem(n);if(i&&Array.isArray(r))for(let a=0;a<r.length;a++)this.parseSchema(t,i,void 0,a.toString(),t.path,{})}for(let n in t.aggregations){let i=t.aggregations[n].union?.originalNames||[n];for(let a of i)typeof r=="object"&&a in r&&this.readAdvancedPropertiesData(t.aggregations[n],r[a])}}readPropertiesData(t,r){let n=Object.keys(t.properties);for(let i in r)n.includes(i)&&(t.properties[i].value=r[i]);for(let i in t.aggregations)i in r&&this.readPropertiesData(t.aggregations[i],r[i])}prepareAggregation(t,r,n,i="Object"){let a=(t||[]).join("/");for(let s of zRn)if(s.fn(a,n,r))return new s.aggregation(void 0,r);let o;if(n?.childClass)o=new n.childClass(void 0,r);else{let s=i==="Object"?Gt:Gj;o=new s(void 0,r)}return t&&vMt.some(s=>vwe(t,s))&&(o.isTable=!0),o}isFreeText(t){let r=n=>n.type==="string"&&!n.enum;return Array.isArray(t)?t.some(r):r(t)}storeInnerProperties(t,r,n){for(let i of r)if(n[i]!==void 0||i==="i18nClassification"&&i in n){if(!this.isCorrectSchemaProperty(i,n[i])){Nt.error(vt.t("SCHEMA_PARSING_ERROR_UNEXPECTED_VALUE",{name:i,value:JSON.stringify(n[i])}));return}t[i]=n[i]}}getSchemaArrayItem(t){let r=Array.isArray(t.items)?t.additionalItems:t.items;return typeof r=="object"?r:void 0}updateArrayFormSchema(t){let r=this.getSchemaArrayItem(t.schema||{});if(typeof r=="object"){let n=this.prepareAggregation();t.isAtomic=!!r.type,this.parseSchema(n,r,void 0,t.isAtomic?"":void 0,t.path,{}),Object.keys(n.properties).length&&(t.formSchema=n)}(!t.formSchema||!Object.keys(t.formSchema.properties).length)&&(t.schemaCreationForms=[])}updateFormSchema(t,r){if(t instanceof Gj)this.updateArrayFormSchema(t);else if(r&&t.additionalProperties?.aggregations[r]){let n=this.prepareAggregation();this.parseSchema(n,t.additionalProperties.aggregations[r].schema||{},void 0,void 0,t.path,{}),Object.keys(n.properties).length&&(t.formSchema=n)}else if(typeof t.schema?.additionalProperties=="object"&&this.isSchemaAtomic(t.schema?.additionalProperties)){t.isAtomic=!0,t.isTable=!0;let n=this.prepareAggregation();this.parseSchema(n,t.schema.additionalProperties,void 0,"",t.path,{}),Object.keys(n.properties).length&&(t.formSchema=n)}}updateViewNodes(t){for(let r in t.aggregations){let n=t.aggregations[r];this.updateViewNodes(n)&&!t.isViewNode&&(t.isViewNode=!0)}return t.isViewNode||!1}isCorrectSchemaProperty(t,r){let n=!0;switch(t){case"description":case"pattern":case"i18nClassification":{n=r===void 0||typeof r=="string";break}case"isViewNode":{n=r===void 0||typeof r=="boolean";break}}return n}propertySorter(t,r,n){let i=t[r].propertyIndex!==void 0?t[r].propertyIndex:0,a=t[n].propertyIndex!==void 0?t[n].propertyIndex:0;return i===a?0:i>a?1:-1}afterInit(t){if(this.pageType===kD.PageType.FPMCustomPage){let r=new Av(void 0,void 0);typeof this.data.$filePath=="string"&&(r.setFilePath(this.data.$filePath),r.annotationNodeId=t.nodes[0]?.nodeId),r.aggregations=this.root.aggregations,this.root.aggregations={macros:r}}}isSchemaAtomic(t){let r=["string","number","boolean"];return typeof t=="object"&&typeof t.type=="string"&&r.includes(t.type)}};var TMt=dt(Pc());var GRn="True",KRn="False",YRn=[CX,X$t];function WRn(e){return`outline-node${e.replace(/\//g,"-")}`}function xMt(e,t,r,n){return{schemaPath:n,artifactType:r.artifactType,description:r.description??"",name:e,displayName:t,type:"string",value:r.value,schema:r.schema??{}}}var _Mt=e=>!Number.isNaN(e)&&!Number.isNaN(e-0),OMt=e=>{let t=[];t.push({key:"",text:""});for(let r of e){let n=r;typeof r=="boolean"?(n=r?GRn:KRn,t.push({key:r,text:n})):typeof r=="string"?_Mt(parseFloat(r))?t.push({key:parseFloat(r),text:r?.toString()}):t.push({key:r,text:r}):typeof r=="number"&&_Mt(r)&&t.push({key:r,text:r?.toString()})}return t};function XRn(e,t){if(t.enum||t.oneOf){let r=[];t.enum?r=OMt(t.enum):t.oneOf&&(r=t.oneOf.map(n=>{let i=n.const;return{key:n.const,text:i}}),r.unshift({key:"",text:"",reset:!0})),e.options=r}}function JRn(e,t,r,n){let i=r.schema.type,a=xMt(e,t,r,n);switch(i){case"string":a.type="string",XRn(a,r.schema);break;case"number":{a.type="number";break}case"boolean":{a.type="boolean",a.options=[{key:void 0,text:""},{key:!0,text:"True"},{key:!1,text:"False"}];break}default:{r.schema.enum?OMt(r.schema.enum):Nt.warn(`Unhandled property: ${JSON.stringify(r)}`);break}}return a}function SMt(e,t=[]){let r=[],n=Object.keys(e.properties);n.length&&n.forEach(i=>{let a=e.properties[i],o=e.path.concat(i),s=JRn(i,a.name,a,o);s&&r.push(s)});for(let i in e.aggregations){let a=e.aggregations[i];if(a.isViewNode)continue;let o=xMt(i,a.name??i,a,a.path);o.type="object";let s=SMt(a,[...t,e]);s.length&&(o.properties=s),r.push(o)}return r}function AMt(e,t){let{text:r,level:n,model:i}=t,{path:a}=t,o=[],s=e.getAggregationKeys(!0),c=WRn(e===i.root?"root-node":`${a}-node`);e.virtual&&i.pageType===TMt.PageTypeV4.FPMCustomPage&&(a="");for(let l of s){let p=a+"/"+l,f=e.aggregations[l],d=f.getDisplayName(),h=AMt(f,{...t,level:n+1,path:p,text:d});o.push(h)}let u=e.annotationNodeId;return!u&&(e instanceof qE||e instanceof YO)&&(u=[]),{id:c,path:e.path.map(l=>l),children:o,text:r,additionalText:e.additionalText,moveProps:ZRn(i,e),title:e.getTechnicalName(),properties:SMt(e),annotationNodeId:u,type:eLn(e),value:e.value,schema:e.schema??{}}}function ZRn(e,t){if(e.root!==t){let n={movable:t.sortableItem==="Enabled"&&!0,allowedParents:QRn(e.root,t),allowedChildTypes:t.sortableList&&t.sortableCollection?[t.sortableCollection]:void 0,type:t.sortableCollection};return t.sortableItem==="Excluded"&&(n.dropRestricted=!0),n}}function QRn(e,t){let r;if(t.custom){let n=t.parent?.getAllowedDropRange(t);r=[],t.parent&&n&&r.push({path:t.parent.path,allowedRanges:n})}else if(t.dropUINodes){let n=e.findAllowedDropAggregations(t);YRn.some(i=>t.name?.startsWith(i))&&(n=n.filter(i=>!UO(i.path,["footer","actions"]))),r=n.map(i=>({path:i.path,allowedRanges:i.range}))}return r}function eLn(e){let t;return e.custom?e instanceof zO?t="customAction":e instanceof GO?t="customColumn":e instanceof RD?t="customFilterField":e instanceof Jm&&(t="customSection"):e.path.length===0?t="rootNode":e instanceof YO&&(t="views"),t}function Swe(e,t,r,n){let i=new KX("Root",r,t,e,n??{dynamicNodes:{},nodes:[]}),a=AMt(i.root,{level:0,path:"",text:i.name,model:i});return a.root=!0,a.schema=i.schema,a}function YX(e,t){for(let r of e){if(UO(r.path,t))return{node:r};for(let i of r.properties){if(UO(i.schemaPath,t))return{property:i};let a=CMt(i,t);if(a)return{node:r,property:a}}let n=r.children?YX(r.children,t):void 0;if(n)return n}}function CMt(e,t){if(e.properties)for(let r of e.properties){if(UO(r.schemaPath,t))return r;let n=CMt(r,t);if(n)return n}}var ch=dt(Pc()),zf=require("node:path"),Nwe=dt(Zd());var sh=dt(Zd()),Awe=dt(Pc()),Cwe=require("node:fs"),Wj=require("node:fs/promises"),wwe=require("node:path");function wMt(e){let t=e.getAppId(),r=e.project,n;if(t===void 0){let i=Object.keys(r.apps);n=r.apps[i[0]].mainService}else{let i=r.apps[t];if(!i)throw new Error("ERROR_INVALID_APP_ID");n=i.mainService}return n??"mainService"}async function $D(e){let t=wMt(e);return(e.projectType==="CAPJava"||e.projectType==="CAPNodejs")&&(t=await(0,sh.getCapServiceName)(e.project.root,e.app?.services?.[t].uri??"")),t}async function PMt(e){let t=[],r=wMt(e),n=e.app?.services?.[r];if(!n)return[];if(n.uri&&(e.projectType==="CAPJava"||e.projectType==="CAPNodejs")){let i=n?.uri??"";if(i){let a=await(0,sh.readCapServiceMetadataEdmx)(e.root,i);t.push({fileContent:a,dataSourceUri:i})}}else{if(n.local){let a=await(0,Wj.readFile)(n.local);t.push({dataSourceUri:n.local,fileContent:a.toString()})}let{annotations:i=[]}=n;for(let a of i)if(a.local){let o=await(0,Wj.readFile)(a.local);t.push({dataSourceUri:a.local,fileContent:o.toString()})}}return t}async function Xj(e){let t=await(0,sh.getWebappPath)(e.app.appRoot),r=(0,wwe.join)(t,sh.FileName.Manifest);if(!(0,Cwe.existsSync)(r))return;let n=await(0,Wj.readFile)(r);return JSON.parse(n.toString())}async function Pwe(e){let t=await Xj(e),r=t?(0,sh.getMinimumUI5Version)(t):void 0;return r!==void 0&&Number.isNaN(parseFloat(r))&&(r="latest"),r??"latest"}async function DMt(e){let t,r=(0,wwe.join)(e,sh.FileName.Package);if((0,Cwe.existsSync)(r)){let n=await(0,Wj.readFile)(r);try{t=JSON.parse(n.toString())}catch(i){Nt.error(String(i))}}return t?.sapuxLayer==="VENDOR"?Awe.FlexChangeLayer.Vendor:Awe.FlexChangeLayer.Customer}var WO=require("node:path"),Dwe=require("node:fs"),WX=require("node:fs/promises"),IMt=dt(iK()),RMt=dt(YK());function tLn(e){return e??(0,RMt.create)((0,IMt.create)())}function LMt(e,t,r){let n={},i=oLn(t),a=nLn(r);if(a)for(;a.length>0;){let o=a.pop();sLn(i,o)||o.content.newValue!==null&&(n[(0,WO.join)(e,`${o.fileName}.change`)]=o)}return aLn(e,i,n),n}async function kMt(e,t,r){r=tLn(r),await rLn(e,t,r),Object.keys(t).length>0&&!(0,Dwe.existsSync)((0,WO.join)(e))&&await(0,WX.mkdir)(e);for(let n in t){let i="";(0,Dwe.existsSync)(n)&&(i=await r.read(n));let a=JSON.stringify(t[n],void 0,4);a!==i&&await r.write(n,a)}return r}async function rLn(e,t,r){let n=Object.keys(t);try{let i=await(0,WX.readdir)(e);i=i.map(o=>(0,WO.join)(e,o));let a=i.filter(o=>!n.includes(o));for(let o of a)try{await r.delete(o)}catch(s){Nt.error(`Failed to delete deprecated file "${o}": ${s}`);continue}}catch(i){Nt.error(`Error while removing deprecated flex change files: ${i}`);return}}function nLn(e=[]){let t=[];for(let r of e){let n=$Mt(r);n&&t.push(n)}return t}function $Mt(e){try{return JSON.parse(e)}catch(t){Nt.error(`Error while prsing flex change file: ${t}`)}}function NMt(e,t){return(e.changeType==="propertyChange"||e.changeType==="propertyBindingChange")&&e.changeType===t.changeType&&e.content?.property===t.content?.property&&e.selector?.id===t.selector?.id}function iLn(e,t){for(let r=e.length-1;r>=0;r--){let n=e[r].change;t.selector.id===n.selector.id&&t.content.property===n.content.property&&e.splice(r,1)}}function aLn(e,t,r){if(t)for(let n of t)r[(0,WO.join)(e,`${n.filename}`)]=n.change}function oLn(e){let t=[];for(let r in e){let n=$Mt(e[r]);n&&t.push({filename:r,change:n})}return t}function sLn(e,t){let r=e?.filter(n=>NMt(t,n.change));if(r&&r.length>0)if(r.length===1){let n=r[0].change;if(n.content.newValue!==void 0&&t.content.newValue!==void 0&&n.content.newValue===t.content.newValue||n.content.newBinding!==void 0&&t.content.newBinding!==void 0&&n.content.newBinding===t.content.newBinding)return!0;t.fileName=(0,WO.parse)(r[0]?.filename).name;let i=e.findIndex(a=>NMt(t,a.change));e.splice(i,1)}else iLn(e,t);return!1}var jo=class{appAccess;constructor(t){this.appAccess=t}async getSpecification(){return this.appAccess.getSpecification()}getAppId(t){return t["sap.app"]?.id??""}async getVirtualFiles(){let t=await Xj(this.appAccess);if(!t)return[];let r=await this.getSpecification(),n=await PMt(this.appAccess),i=await(0,Nwe.readFlexChanges)(this.appAccess.app.changes);return r.importProject({manifest:t,annotations:n,flex:Object.values(i)})}async readApp(t){t??=await this.getVirtualFiles();let r=t.find(o=>o.dataSourceUri===ch.FileName.App),n=JSON.parse(r?.fileContent??"{}"),i=(0,zf.join)(".schemas",(0,zf.basename)((0,zf.join)(n?.$schema??""))),a=t.find(o=>(0,zf.join)(o.dataSourceUri)===i);if(a){let o=JSON.parse(a.fileContent);o.properties?.settings&&(o.properties.settings.isViewNode=!0),a.fileContent=JSON.stringify(o)}return{config:n,schema:a?.fileContent??"{}"}}async readPageData(t){try{let r=await this.getVirtualFiles(),n=(0,zf.join)(ch.DirName.Pages,`${t}.json`),i=r.find(c=>(0,zf.join)(c.dataSourceUri)===n),a=i?.fileContent?JSON.parse(i.fileContent):void 0,o=(0,zf.join)(".schemas",(0,zf.basename)((0,zf.join)(a?.$schema??""))),s=r.find(c=>(0,zf.join)(c.dataSourceUri)===o);if(a&&s){let u=(await this.readApp(r)).config.pages?.[t];if(u){let l=u.pageType;return{pageId:t,pageType:l??ch.PageTypeV4.ListReport,config:a,page:u,schema:s.fileContent,entitySet:u.entitySet,entityType:"entityType"in u&&typeof u.entityType=="string"?u.entityType:void 0,contextPath:u.contextPath}}}}catch(r){Nt.error(String(r))}}async writePage(t){let r=await Xj(this.appAccess);if(!r)return;let n=await this.getSpecification(),a={[t.pageType===ch.PageTypeV4.ObjectPage?ch.SchemaType.ObjectPage:ch.SchemaType.ListReport]:{appId:this.getAppId(r),jsonSchema:JSON.parse(t.schema),manifest:r,page:{...t.page,name:t.pageId,config:t.config}}},o=await this.getExportConfigParameters(r,a),s=n.exportConfig(o);s.manifestChangeIndicator==="Updated"&&await this.appAccess.updateManifestJSON(s.manifest);let c=this.appAccess.app.changes,u=await(0,Nwe.readFlexChanges)(this.appAccess.app.changes),l=LMt(c,u,s.flexChanges),p=await kMt(c,l);return await p.commit(()=>{}),s.flexChanges=Object.keys(p.dump()),s}async writeApp(t){let{config:r,schema:n}=t,i=await Xj(this.appAccess);if(!i)return;let a=await this.getSpecification(),o={[ch.SchemaType.Application]:{application:r,manifest:i,jsonSchema:JSON.parse(n)}},s=await this.getExportConfigParameters(i,o),c=a.exportConfig(s);return await this.appAccess.updateManifestJSON(c.manifest),c}async writeFPM(t){t.data&&(t.data.minUI5Version=await Pwe(this.appAccess));let n=await(await this.getSpecification()).generateCustomExtension(t);return await n?.commit(()=>{}),n?Object.keys(n.dump()):[]}async getExportConfigParameters(t,r){let i=t["sap.app"]?.dataSources?.mainService?.settings?.odataVersion==="2.0"?{v2:r}:{v4:r};return i.ui5Version=await Pwe(this.appAccess),i.layer=await DMt(this.appAccess.root),i}};function Iwe(e,t,r,n=!1){cLn(e,t,r!==void 0,(i,a)=>{if(typeof i!="object"||i===null)return;let o=i;r!==void 0?n&&Array.isArray(o[a])?o[a].push(r):o[a]=n?[r]:r:Array.isArray(o)?o.splice(typeof a=="string"?Number.parseInt(a,10):a,1):delete o[a]})}function cLn(e,t,r,n){let i=e;for(let a=0;a<t.length;a++)if(t[a]!==void 0){if(a===t.length-1&&n(i,t[a]),i[t[a]]===void 0&&r){let o=t[a+1]!==void 0&&typeof t[a+1]=="number";i[t[a]]=o?[]:{}}if(i=i[t[a]],!i)break}}var Cv=class{constructor(t,r){this.appAccess=t;this.pageId=r;this.ftfsIO=new jo(t)}ftfsIO;async getPageTree(t){let r={children:[],path:[],properties:[],text:"",schema:{}};if(this.pageId){let n=await this.ftfsIO.readPageData(this.pageId);n&&(r=Swe(n.schema,n.config,n.pageType,t))}else{let n=await this.ftfsIO.readApp();n&&(r=Swe(n.schema,n.config,MMt.PageTypeV4.ListReport))}return r}async changeProperty(t,r){if(this.pageId){let n=await this.ftfsIO.readPageData(this.pageId);if(n)return Iwe(n.config,t,r),this.ftfsIO.writePage(n)}else{let n=await this.ftfsIO.readApp();return Iwe(n.config,t,r),this.ftfsIO.writeApp(n)}}async getApplication(){return this.ftfsIO.readApp()}async updateApplication(t){await this.ftfsIO.writeApp(t)}};var xl=dt(Pc());var r5t=require("node:path");var Q6t=dt(A6t()),e5t=dt(Zd()),t5t=dt(Z6t()),See=class{constructor(t){this.options=t}metadataService;annotationService;nodes=[];nodesMap=new Map;namespace="";async loadMetadata(t=!1){if(!t&&this.metadataService)return;let{project:r,serviceName:n,appName:i}=this.options,a=await(0,e5t.getProject)(r.root);this.annotationService=await Q6t.FioriAnnotationService.createService(a,n,i),await this.annotationService.sync(),this.metadataService=this.annotationService.getMetadataService(),this.namespace=[...this.metadataService.getNamespaces()][0],this.metadataService.visitMetadataElements(this.visitMdElement.bind(this))}visitMdElement(t){let{path:r,name:n}=t,i=this.metadataService?.getEdmTargetKinds(r)[0]||"",a={path:r,name:n,mdElement:t,kind:i};this.nodes?.push(a),this.nodesMap.set(r,a)}async getNamespace(){return await this.loadMetadata(),this.namespace}async getAllowedEntities(t=!1){if(await this.loadMetadata(t),!this.annotationService)return[];let r=[],n=this.annotationService.getSchema(),i=(0,t5t.convert)(n);for(let a of i.entitySets)r.push({entitySet:a.name,entityType:a.entityType.name,navigations:a.entityType.navigationProperties.filter(o=>o.isCollection).map(o=>{let s=o.targetType,c=i.entitySets.find(u=>u.entityTypeName===s.name);return{name:o.name,fullyQualifiedName:o.fullyQualifiedName,entitySet:c?.name??s.name}})});return r}async getAllowedNavigations(t,r,n=!1){return(await this.getAllowedEntities(n)).find(a=>a.entitySet===t||a.entityType===r)?.navigations??[]}};var YRe=new Map;function Y9n(e){return(0,r5t.join)(e.project.root,e.appName,e.serviceName)}async function WRe(e){let t=Y9n(e);YRe.has(t)||YRe.set(t,new See(e));let r=YRe.get(t);if(!r)throw new Error(`No service: '${t}'`);return r}var id=dt(Pc()),W9n=new Map([[id.PageTypeV4.ListReport,"List"],[id.PageTypeV4.ObjectPage,id.PageTypeV4.ObjectPage],[id.PageTypeV4.CustomPage,"Page"],[id.PageTypeV4.FPMCustomPage,"Page"],[id.PageTypeV4.AnalyticalListPage,"ALP"]]);function X9n(e,t,r){let n="",i=[];if(e.pageType===id.PageTypeV4.CustomPage||e.pageType===id.PageTypeV4.FPMCustomPage){let o=(e.viewName??"").split(".");n=o[o.length-1]}else n=e.contextPath?e.contextPath.slice(1).replace(/\//g,"_"):e.entitySet;return i=[n],t&&r&&(!e.contextPath||e.contextPath.indexOf(r)===-1)&&i.push(r),i[i.length-1]+=W9n.get(e.pageType),i}function J9n(e){let t=[];return t.push(e.pageType),e.entitySet&&t.push(e.entitySet),t}function XRe(e,t,r,n,i){let a=[];n===id.FioriElementsVersion.v2?a=J9n(e):a=X9n(e,t,i);let o=a.join("_"),s=r.map(u=>u.pageId),c=0;for(;s.indexOf(o)>-1;)o+=c.toString(),c++;return o}function Tq(e){return e.config.target?.fioriElements??id.FioriElementsVersion.v4}var i5t=dt(Zd()),a5t=require("node:path");var n5t="1.136.7",L1="generate-fiori-ui-application-cap",m_="add-page",tb="delete-page",Aee="create-controller-extension",Cee=/^[A-Za-z][A-Za-z0-9_-]*$/;var g_=class{serviceName;appData;appId;applicationAccess;params;version;constructor({params:t,applicationAccess:r,appId:n,serviceName:i,appData:a}){this.params=t,this.serviceName=i,this.appData=a,this.appId=n,this.applicationAccess=r,this.version=Tq(a)}getAllowedNavigationsOutput(t){return t.map(r=>r.name).join(", ")}getMissingNavigationMessage(t,r,n){let i="";switch(t){case 1:{i="page does not have valid navigation for add";break}case 2:{i=`provided 'navigation' was not found. ${n} has following navigations available: ${this.getAllowedNavigationsOutput(r)}`;break}case 3:{i="provide 'entitySet' for very first page";break}case 4:{i=`provided 'entitySet' was not found. Following entitySets available: ${this.getAllowedNavigationsOutput(r)}`;break}}return i}calculateContextPath(t,r,n){let i;return!t||t.pageType===xl.PageTypeV4.ListReport?i=`/${n}`:t.contextPath?i=r&&t.routePattern!==":?query:"?`${t.contextPath}/${r}`:`/${n}`:t.entitySet&&(i=this.calculateContextPathBasedOnEntitySet(t,r)),i}calculateContextPathBasedOnEntitySet(t,r){let n,a=t.routePattern?.replace(":?query:","").replace(/\({[^}]*}\)/g,"");return a?n=r&&r!==""?`/${a}/${r}`:`/${a}`:n=r&&r!==""?`/${t.entitySet}/${r}`:`/${t.entitySet}`,n}createErrorResponse(t){return{functionalityId:m_,status:"Failed",message:t,parameters:[],appPath:this.params.appPath,changes:[],timestamp:new Date().toISOString()}}async validatePageCreationInput(t,r,n){if(r.length&&!t.parent)return this.createErrorResponse('Provide "parentPage" for page creation');if(t.pageType===xl.PageTypeV4.CustomPage){let i=this.validateCustomPageViewName(n);if(i)return i}return null}validateCustomPageViewName(t){let r=".view.xml",n=t?.endsWith(r)?t.slice(0,-r.length):t;return n?/^[a-z][a-z0-9_-]*$/i.exec(n)?null:this.createErrorResponse("'viewName' must not contain spaces, must start with an upper-case letter, and may contain letters, digits, and underscores."):this.createErrorResponse('Provide "viewName" for CustomPage')}async validateNavigationInput(t,r,n,i=[]){if(i.length&&!t)return this.createErrorResponse('provided "parentPage" was not found');let a=await this.getAllowedNavigations(t);if(t&&!a.length){let s=this.getMissingNavigationMessage(1,a);return this.createErrorResponse(s)}let o=this.findTargetNavigation(a,r,n);if(t&&!o){let s=this.getMissingNavigationMessage(2,a,t.pageId);return this.createErrorResponse(s)}if(!t&&!n){let s=this.getMissingNavigationMessage(3,a);return this.createErrorResponse(s)}if(!t&&!o){let s=this.getMissingNavigationMessage(4,a);return this.createErrorResponse(s)}return null}findTargetNavigation(t,r,n){return t.find(i=>{let a=i.name.toLocaleLowerCase();return a===r?.toLocaleLowerCase()||a===n?.toLocaleLowerCase()})}async generatePageV4(t,r,n,i,a,o){let s=r?{sourceEntity:r.entitySet,sourcePage:r.pageId,navEntity:n?.name,navKey:!0}:void 0,c=this.calculateContextPath(r,n?.name,n?.entitySet??o),u=XRe({entitySet:n?.entitySet??o??"",pageId:"",pageType:t.pageType,contextPath:c,viewName:a},r?.pageId,i,this.version,n?.name),l={id:u,entity:n?.entitySet??o??"",navigation:s,contextPath:c,name:t.pageType===xl.PageTypeV4.CustomPage?a:void 0},p=await this.writeFPM(t.pageType,l,a);return{pageID:u,changes:p}}async generatePageV2(t,r,n,i,a,o){let s=this.appData.config;s.pages||(s.pages={});let c=XRe({entitySet:n?.entitySet??o??"",pageId:"",pageType:t.pageType,contextPath:"",viewName:a},r?.pageId,i,this.version,n?.name);s.pages[c]={pageType:t.pageType,entitySet:n?.entitySet??o,navigationProperty:n?.name,navigation:{}};let u=r?s.pages[r.pageId]:void 0;if(u){u.navigation||(u.navigation={});let p=u.entitySet??"";u.navigation[c]=n?.name?`${p}.${n.name}`:p}return await new jo(this.applicationAccess).writeApp(this.appData),{pageID:c,changes:[this.applicationAccess.app.manifest]}}async writeFPM(t,r,n){let i=new jo(this.applicationAccess),a=xl.CustomExtensionType.ListReport;t===xl.PageTypeV4.ObjectPage&&(a=xl.CustomExtensionType.ObjectPage),t===xl.PageTypeV4.CustomPage&&n&&(a=xl.CustomExtensionType.CustomPage);let o=XY(i5t.DirName.View);return i.writeFPM({customExtension:a,basePath:(0,a5t.join)(this.applicationAccess.project.root,this.appId),data:{...r,folder:o}})}deleteNavigationLinks(t,r){if(t){for(let n in t)if(this.findPageByNavigation(t,n)===r){delete t[n];break}}}findPageByNavigation(t,r){let n=t?.[r];return typeof n=="string"?r:n?.route}deletePageRecursively(t,r){if(!r)return;let{pages:n}=t,i=t.settings??{};if(n?.[r]){let a=n?.[r];delete n[r];let o=`${a.pageType}#${r}`;if(i.controllerExtensions?.[o]&&delete i.controllerExtensions[o],a.navigation)for(let s in a.navigation){let c=this.findPageByNavigation(a.navigation,s);this.deletePageRecursively(t,c)}}}getPages(){let{config:t}=this.appData,{pages:r={}}=t,n=[];for(let i in r){let a=r[i];n.push({pageId:i,pageType:a.pageType??xl.PageTypeV4.ListReport,entitySet:a.entitySet??"",contextPath:a.contextPath,routePattern:"routePattern"in a&&typeof a.routePattern=="string"?a.routePattern:void 0})}return n}async getAllowedNavigations(t,r=!1){return!t||t?.pageType==="ListReport"?this.getRootPageNavigationOptions(r):(await(await WRe({appName:this.appId,project:this.applicationAccess.project,serviceName:this.serviceName})).getAllowedNavigations(t?.entitySet,t?.entitySet,r)).map(i=>({...i,isNavigation:!0}))}async getRootPageNavigationOptions(t=!1){return(await(await WRe({appName:this.appId,project:this.applicationAccess.project,serviceName:this.serviceName})).getAllowedEntities(t)).map(i=>({entitySet:i.entitySet,name:i.entitySet}))}async getCreationNavigationOptions(){let t={navigations:{}},r=this.getPages();if(r.length){let n=!0;for(let i of r)t.navigations[i.pageId]=await this.getAllowedNavigations(i,n),n=!1}else t.entities=await this.getAllowedNavigations();return t}async createPage(t){let{parent:r,navigation:n,pageType:i,entitySet:a}=t,o=t.pageType===xl.PageTypeV4.CustomPage?t.viewName:void 0,s=this.getPages(),c=await this.validatePageCreationInput(t,s,o);if(c)return c;let u=s.find(v=>v.pageId===r),l=await this.validateNavigationInput(u,n,a,s);if(l)return l;let p=await this.getAllowedNavigations(u),f=this.findTargetNavigation(p,n,a),d=this.version===xl.FioriElementsVersion.v2?this.generatePageV2:this.generatePageV4,{pageID:h,changes:m}=await d.call(this,t,u,f,s,o,a);return{functionalityId:m_,status:m.length?"success":"skipped",message:m.length?`Page with id '${h}' of type '${i}' was created successfully in application '${this.appId}'`:`No changes were made for '${i}'`,parameters:[],appPath:this.params.appPath,changes:m,timestamp:new Date().toISOString()}}async deletePage(t){let{pageId:r}=t,n=structuredClone(this.appData),{config:i}=n,a=!1,{pages:o={}}=i;if(o?.[r]){for(let s in o)o[s].navigation&&this.deleteNavigationLinks(o[s].navigation,r);this.deletePageRecursively(i,r),a=!0}return Object.keys(o).length===0&&delete i.home,a?(await new jo(this.applicationAccess).writeApp(n),{functionalityId:tb,status:"success",message:`Page with id '${r}' was deleted successfully in application '${this.appId}'`,parameters:[],appPath:this.params.appPath,changes:[],timestamp:new Date().toISOString()}):{functionalityId:tb,status:"unchanged",message:`Page with id '${r}' was not found in application '${this.appId}'`,parameters:[],appPath:this.params.appPath,changes:[],timestamp:new Date().toISOString()}}};var ad=dt(Pc());var o5t=Fn([ad.PageTypeV4.ListReport,ad.PageTypeV4.ObjectPage,ad.PageTypeV4.CustomPage]),s5t=Fn([ad.PageTypeV4.ObjectPage]),Z9n=(e,t)=>{let r=t===ad.FioriElementsVersion.v2?s5t:o5t;return Ae({pageType:r.describe("Type of page to be created. First try to extract page type from user input, if not possible suggest content defined in options."),entitySet:Fn(e.map(n=>n.name)).describe("Entity set for the new page. First try to extract entity from user input, if not possible suggest content defined in options.")})},Q9n=(e,t,r)=>{let n=r===ad.FioriElementsVersion.v2?s5t:o5t,i={parentPage:ht(e).describe("Parent page is id/name of parent page. First try to extract parent page from user input, if not possible suggest content defined in options"),pageNavigation:Fn(t.map(o=>o.name)),pageType:n.describe("Type of page to be created. First try to extract page type from user input, if not possible suggest content defined in options.")};r===ad.FioriElementsVersion.v4&&(i.pageViewName=re().regex(Cee).optional().describe('Required if pageType is "CustomPage". Name of custom view file. First try to extract view name from user input that satisfies the pattern, if not possible ask user to provide view name'));let a=Ae(i);return r===ad.FioriElementsVersion.v4&&(a=a.refine(o=>!(o.pageType===ad.PageTypeV4.CustomPage&&!o.pageViewName),{path:["pageViewName"],message:"A pageViewName must be provided when using PageTypeV4.CustomPage"})),a};function wee(e,t=[],r=ad.FioriElementsVersion.v4){let n=Object.keys(e);return n.length?hn(n.map(i=>Q9n(i,e[i],r))):Z9n(t,r)}function Pee(e=[]){let t=e.map(r=>r.pageId);return Ae({pageId:Fn(t).describe("Page id to be deleted. First try to extract page id from user input, if not possible suggest content defined in options")})}var c5t=dt(Pc());var xq={functionalityId:m_,name:"Add new page to application by updating manifest.json",description:"Create new fiori elements page like ListReport, ObjectPage, CustomPage",parameters:Oa(wee({}))};async function eHn(e){let{appPath:t}=e,r=await fu(t);if(!r?.applicationAccess)return{...xq,parameters:{},name:"Invalid Project Root or Application Path",description:`To add a new page, provide a valid project root or application path. "${t}" is not valid`};let{appId:n,applicationAccess:i}=r,o=await new jo(i).readApp(),s=await $D(i),u=await new g_({params:e,applicationAccess:i,serviceName:s,appId:n,appData:o}).getCreationNavigationOptions();return{...xq,parameters:Oa(wee(u.navigations,u.entities,Tq(o)))}}async function tHn(e){let{appPath:t,parameters:r}=e,n=await fu(t);if(!n?.applicationAccess)return{functionalityId:m_,status:"Failed",message:`Project root not found for app path: ${t}`,parameters:[],appPath:t,changes:[],timestamp:new Date().toISOString()};let{appId:i,applicationAccess:a}=n,s=await new jo(a).readApp(),c=await $D(a),u=new g_({params:e,applicationAccess:a,serviceName:c,appId:i,appData:s}),l=await u.getCreationNavigationOptions(),p=wee(l.navigations,l.entities,Tq(s)),f=wm(p,r),d=f.pageType??c5t.PageTypeV4.ObjectPage,h="parentPage"in f?f.parentPage:void 0,m="entitySet"in f?f.entitySet?.toString():void 0,v="pageNavigation"in f?f.pageNavigation.toString():void 0,_="pageViewName"in f&&f.pageViewName&&typeof f.pageViewName=="string"?f.pageViewName:"";return u.createPage({pageType:d,parent:h,navigation:v,entitySet:m,viewName:_})}var JRe={getFunctionalityDetails:eHn,executeFunctionality:tHn};var Dee={functionalityId:tb,name:"Delete page from application by updating manifest.json",description:"Remove existing fiori elements page from the application",parameters:Oa(Pee())};async function rHn(e){let{appPath:t}=e,r=await fu(t);if(!r?.applicationAccess)return{functionalityId:tb,name:"Invalid Project Root or Application Path",description:`To delete a page, provide a valid project root or application path. "${t}" is not valid`,parameters:{}};let{appId:n,applicationAccess:i}=r,o=await new jo(i).readApp(),s=await $D(i),c=new g_({params:e,applicationAccess:i,serviceName:s,appId:n,appData:o});return{...Dee,parameters:Oa(Pee(c.getPages()))}}async function nHn(e){let{appPath:t,parameters:r}=e,n=await fu(t);if(!n?.applicationAccess)return{functionalityId:tb,status:"Failed",message:`Project root not found for app path: ${t}`,parameters:[],appPath:t,changes:[],timestamp:new Date().toISOString()};let{appId:i,applicationAccess:a}=n,s=await new jo(a).readApp(),c=await $D(a),u=new g_({params:e,applicationAccess:a,serviceName:c,appId:i,appData:s}),l=Pee(u.getPages()),p=wm(l,r);return u.deletePage({pageId:p.pageId})}var ZRe={getFunctionalityDetails:rHn,executeFunctionality:nHn};var Iee=dt(Pc());var u5t=require("node:path");var Nee=Ae({pageType:Fn(["ListReport","ObjectPage"]).describe("Type of page").default("ListReport"),controllerName:re().regex(Cee).describe("Name of new controller extension file")});async function QRe(e){let t=[];if(e){let r=await e.readApp();t=Object.keys(r.config.pages??{})}return t.length>0?Nee.extend({pageId:Fn(t).optional().describe("If controller extension should be assigned for specific page, then pageId should be provided")}):Nee}var eLe={functionalityId:Aee,name:"Add new controller extension by creating javascript or typescript file and updates manifest.json with entry",description:"Add new controller extension by creating javascript or typescript file and updates manifest.json with entry. Controller extensions allow users to extensiate default behaviour with custom controllers code.",parameters:Oa(Nee)};async function iHn(e){let t=await fu(e.appPath);if(!t?.applicationAccess)throw new Error("Invalid Project Root or Application Path");let r=new jo(t.applicationAccess);return{...eLe,parameters:Oa(await QRe(r))}}async function aHn(e){let{parameters:t,appPath:r}=e,n=await fu(r),i=[];if(n?.applicationAccess){let{appId:a,root:o}=n,s=new jo(n.applicationAccess),c=await QRe(s),u=wm(c,t),{pageId:l,controllerName:p,pageType:f}=u,d=await oHn(s,f,l);if(d&&typeof d=="string"){let h={pageId:typeof l=="string"?l:void 0,pageType:d};i=await s.writeFPM({customExtension:Iee.CustomExtensionType.ControllerExtension,basePath:(0,u5t.join)(o,a),data:{extension:h,folder:XY(Iee.DirName.Controller),name:p}})}}return{functionalityId:e.functionalityId,status:i.length?"success":"skipped",message:i.length?"Controller extension is created":"Controller extension is not created",parameters:t,appPath:r,changes:i,timestamp:new Date().toISOString()}}async function oHn(e,t,r){if(r&&typeof r=="string"&&(t=(await e.readApp()).config.pages?.[r]?.pageType),t&&typeof t=="string")return t}var l5t={getFunctionalityDetails:iHn,executeFunctionality:aHn};var UN=require("node:fs"),Oq=require("node:path");var k1={version:"0.2",telemetryData:{generationSourceName:$2.name,generationSourceVersion:$2.version},project:{sapux:!0}},Ree=ht(["FE_FPM","FE_LROP","FE_OVP","FE_ALP","FE_FEOP","FE_WORKLIST","FF_SIMPLE"]).describe("SAP Fiori Elements floor plan type."),Lee=Ae({name:re().describe("Must be lowercase with dashes, e.g., 'sales-order-management'.").regex(/^[a-z0-9-]+$/),title:pt(re()),description:re(),targetFolder:re().describe("Absolute path to the project folder (projectPath)."),ui5Version:re().default(n5t)}),p5t=Ae({servicePath:re().describe("The odata endpoint. If the parameter is not provided, the agent should ask the user for it.").meta({examples:["/sap/opu/odata/sap/<servicename>/","/<servicename>/"]}),host:Ppe().describe("The host of the OData service. Must be an HTTPS endpoint. If the parameter is not provided, the agent should ask the user for it."),client:pt(re().describe("The client to be used for the OData service.")),metadataFilePath:pt(re().describe("Path to a local metadata.xml file."))}),f5t=Ae({servicePath:re().describe("The odata endpoint as provided by the cds mcp or as fallback in case that tool is not available from the service cds file.").meta({examples:["/odata/v4/<servicename>/","/odata/v4/MyRiskService/","/odata/v2/MyOdataV2Service/","/odata/v4/MyOdataV4Service/","/odata/v4/<relative '@path' annotation from service cds file>/","<absolute '@path' annotation from service cds file>/","/myAbsolutePathFromServiceCdsFile/"]}),capService:Ae({projectPath:re(),serviceName:re(),serviceCdsPath:re().describe("The path to the service cds file").meta({examples:["srv/service.cds","srv/my-service.cds","path/to/srv/service.cds","path/to/srv/my-service.cds"]}),capType:pt(ht(["Node.js","Java"]))})}),kee=Ae({mainEntity:Ae({entityName:re().describe("The name of the main entity. EntitySet Name attribute in OData Metadata.").meta({examples:["'SalesOrder'","'PurchaseOrderHeader'","'MyEntity'"]})}),generateFormAnnotations:Qi().describe("Whether to generate form annotations for the main entity if none exist.").default(!0),generateLROPAnnotations:Qi().describe("Whether to generate LROP annotations for the main entity if none exist.").default(!0)});var tLe=KT.object({entityConfig:kee,floorplan:Ree,project:Lee,service:p5t}).describe(`The configuration that will be used for the Application UI generation.
1659
1659
  The configuration **MUST** be a valid JSON object corresponding to the inputSchema of the functionality.`),d5t=Oa(tLe);var rLe=KT.object({entityConfig:kee,floorplan:Ree,project:Lee,service:f5t}).describe(`The configuration that will be used for the Application UI generation.
1660
1660
  The configuration **MUST** be a valid JSON object corresponding to the inputSchema of the functionality.`),h5t=Oa(rLe);async function m5t(e){let t=wm(rLe,e?.parameters),r={...k1,...t,project:{...k1.project,...t.project}};r.project.sapux=r.floorplan!=="FF_SIMPLE";let n=r?.project?.targetFolder??e.appPath;if(!n||typeof n!="string")throw new Error("Please provide a valid path to the CAP project folder.");r?.service.capService.serviceCdsPath&&(r.service.capService.serviceCdsPath=r?.service.capService.serviceCdsPath?.startsWith("/")?r?.service.capService.serviceCdsPath:`/${r?.service.capService.serviceCdsPath}`);let i=r?.project.name??"default",a=(0,Oq.join)(n,"app",i),o=n,s=`${i}-generator-config.json`,c=(0,Oq.join)(o,s);await nX();try{let u=JSON.stringify(r,null,4);await UN.promises.mkdir((0,Oq.dirname)(c),{recursive:!0}),await UN.promises.writeFile(c,u,{encoding:"utf8"});let l=`npx -y yo@4 @sap/fiori:headless ${s} --force --skipInstall`.trim(),{stdout:p,stderr:f}=await iX(l,{cwd:o});Nt.info(p),f&&Nt.error(f)}catch(u){return Nt.error(`Error generating application: ${u}`),{functionalityId:L1,status:"Error",message:"Error generating application: "+u.message,parameters:e.parameters,appPath:a,changes:[],timestamp:new Date().toISOString()}}finally{(0,UN.existsSync)(c)&&await UN.promises.unlink(c)}return{functionalityId:L1,status:"Success",message:`Generation completed successfully: ${a}. You must run \`npm install\` in ${o} before trying to run the application.`,parameters:e.parameters,appPath:a,changes:[],timestamp:new Date().toISOString()}}var $ee={functionalityId:L1,name:"Generate SAP Fiori UI Application",description:`Creates (generates) a new SAP Fiori UI application within an existing CAP project.
1661
1661
  To populate parameters, you **MUST** use the ***CDS MCP*** to search the model for service definitions, entities, associations, and UI annotations.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sap-ux/fiori-mcp-server",
3
3
  "description": "SAP Fiori - Model Context Protocol (MCP) server",
4
- "version": "0.4.10",
4
+ "version": "0.4.11",
5
5
  "keywords": [
6
6
  "SAP Fiori tools",
7
7
  "SAP Fiori elements",