@mongodb-js/compass-web 0.34.0 → 0.34.1

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.
@@ -1,8 +1,8 @@
1
- /*! For license information please see 400.ee421ec0c79f2e659fa8.mjs.LICENSE.txt */
1
+ /*! For license information please see 400.0a2392755f7467db862b.mjs.LICENSE.txt */
2
2
  export const __webpack_esm_id__=400;export const __webpack_esm_ids__=[400];export const __webpack_esm_modules__={86:(e,t)=>{function n(e,t){return{validate:e,compare:t}}Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0,t.fullFormats={date:n(o,a),time:n(c(!0),u),"date-time":n(f(!0),d),"iso-time":n(c(),l),"iso-date-time":n(f(),g),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(e){return p.test(e)&&b.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:function(e){if(S.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}},uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:function(e){return m.lastIndex=0,m.test(e)},int32:{type:"number",validate:function(e){return Number.isInteger(e)&&e<=v&&e>=w}},int64:{type:"number",validate:function(e){return Number.isInteger(e)}},float:{type:"number",validate:y},double:{type:"number",validate:y},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:n(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:n(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,u),"date-time":n(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,d),"iso-time":n(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,l),"iso-date-time":n(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,g),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);const r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function o(e){const t=r.exec(e);if(!t)return!1;const n=+t[1],o=+t[2],a=+t[3];return o>=1&&o<=12&&a>=1&&a<=(2===o&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(n)?29:i[o])}function a(e,t){if(e&&t)return e>t?1:e<t?-1:0}const s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){const n=s.exec(t);if(!n)return!1;const r=+n[1],i=+n[2],o=+n[3],a=n[4],c="-"===n[5]?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||e&&!a)return!1;if(r<=23&&i<=59&&o<60)return!0;const h=i-l*c,f=r-u*c-(h<0?1:0);return(23===f||-1===f)&&(59===h||-1===h)&&o<61}}function u(e,t){if(!e||!t)return;const n=new Date("2020-01-01T"+e).valueOf(),r=new Date("2020-01-01T"+t).valueOf();return n&&r?n-r:void 0}function l(e,t){if(!e||!t)return;const n=s.exec(e),r=s.exec(t);return n&&r?(e=n[1]+n[2]+n[3])>(t=r[1]+r[2]+r[3])?1:e<t?-1:0:void 0}const h=/t|\s/i;function f(e){const t=c(e);return function(e){const n=e.split(h);return 2===n.length&&o(n[0])&&t(n[1])}}function d(e,t){if(!e||!t)return;const n=new Date(e).valueOf(),r=new Date(t).valueOf();return n&&r?n-r:void 0}function g(e,t){if(!e||!t)return;const[n,r]=e.split(h),[i,o]=t.split(h),s=a(n,i);return void 0!==s?s||u(r,o):void 0}const p=/\/|:/,b=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,m=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm,w=-(2**31),v=2**31-1;function y(){return!0}const S=/[^\\]\\Z/},2337:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;const r=n(98947),i=n(89689),o=n(78249),a=n(63843),s=n(91447),c=n(87351),u={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:n,it:i}=e,{baseId:a,schemaEnv:c,validateName:u,opts:f,self:d}=i,{root:g}=c;if(("#"===n||"#/"===n)&&a===g.baseId)return function(){if(c===g)return h(e,u,c,c.$async);const n=t.scopeValue("root",{ref:g});return h(e,o._`${n}.validate`,g,g.$async)}();const p=s.resolveRef.call(d,g,a,n);if(void 0===p)throw new r.default(i.opts.uriResolver,a,n);return p instanceof s.SchemaEnv?function(t){const n=l(e,t);h(e,n,t,t.$async)}(p):function(r){const i=t.scopeValue("schema",!0===f.code.source?{ref:r,code:(0,o.stringify)(r)}:{ref:r}),a=t.name("valid"),s=e.subschema({schema:r,dataTypes:[],schemaPath:o.nil,topSchemaRef:i,errSchemaPath:n},a);e.mergeEvaluated(s),e.ok(a)}(p)}};function l(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):o._`${n.scopeValue("wrapper",{ref:t})}.validate`}function h(e,t,n,r){const{gen:s,it:u}=e,{allErrors:l,schemaEnv:h,opts:f}=u,d=f.passContext?a.default.this:o.nil;function g(e){const t=o._`${e}.errors`;s.assign(a.default.vErrors,o._`${a.default.vErrors} === null ? ${t} : ${a.default.vErrors}.concat(${t})`),s.assign(a.default.errors,o._`${a.default.vErrors}.length`)}function p(e){var t;if(!u.opts.unevaluated)return;const r=null===(t=null==n?void 0:n.validate)||void 0===t?void 0:t.evaluated;if(!0!==u.props)if(r&&!r.dynamicProps)void 0!==r.props&&(u.props=c.mergeEvaluated.props(s,r.props,u.props));else{const t=s.var("props",o._`${e}.evaluated.props`);u.props=c.mergeEvaluated.props(s,t,u.props,o.Name)}if(!0!==u.items)if(r&&!r.dynamicItems)void 0!==r.items&&(u.items=c.mergeEvaluated.items(s,r.items,u.items));else{const t=s.var("items",o._`${e}.evaluated.items`);u.items=c.mergeEvaluated.items(s,t,u.items,o.Name)}}r?function(){if(!h.$async)throw new Error("async schema referenced by sync schema");const n=s.let("valid");s.try((()=>{s.code(o._`await ${(0,i.callValidateCode)(e,t,d)}`),p(t),l||s.assign(n,!0)}),(e=>{s.if(o._`!(${e} instanceof ${u.ValidationError})`,(()=>s.throw(e))),g(e),l||s.assign(n,!1)})),e.ok(n)}():e.result((0,i.callValidateCode)(e,t,d),(()=>p(t)),(()=>g(t)))}t.getValidate=l,t.callRef=h,t.default=u},2622:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DropCollectionTool=void 0;const r=n(58203);class i extends r.MongoDBToolBase{constructor(){super(...arguments),this.name="drop-collection",this.description="Removes a collection or view from the database. The method also removes any indexes associated with the dropped collection.",this.argsShape={...r.DbOperationArgs}}async execute({database:e,collection:t}){const n=await this.ensureConnected();return{content:[{text:`${await n.dropCollection(e,t)?"Successfully dropped":"Failed to drop"} collection "${t}" from database "${e}"`,type:"text"}]}}getConfirmationMessage({database:e,collection:t}){return`You are about to drop the \`${t}\` collection from the \`${e}\` database:\n\nThis operation will permanently remove the collection and all its data, including indexes.\n\n**Do you confirm the execution of the action?**`}}t.DropCollectionTool=i,i.operationType="delete"},2993:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.assertToolsCallTaskCapability=function(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${t})`)},t.assertClientRequestTaskCapability=function(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}},3079:(e,t,n)=>{n.d(t,{_:()=>k});var r=n(66596);function i(e){const t=[];let n=-1,i=0,o=0;for(;++n<e.length;){const a=e.charCodeAt(n);let s="";if(37===a&&(0,r.lV)(e.charCodeAt(n+1))&&(0,r.lV)(e.charCodeAt(n+2)))o=2;else if(a<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(a))||(s=String.fromCharCode(a));else if(a>55295&&a<57344){const t=e.charCodeAt(n+1);a<56320&&t>56319&&t<57344?(s=String.fromCharCode(a,t),o=1):s="�"}else s=String.fromCharCode(a);s&&(t.push(e.slice(i,n),encodeURIComponent(s)),i=n+o+1,s=""),o&&(n+=o,o=0)}return t.join("")+e.slice(i)}var o=n(38411),a=n(2563),s=n(73429);const c={}.hasOwnProperty;function u(e){return String(e||"").toUpperCase()}function l(e,t){const n=String(t.identifier).toUpperCase(),r=i(n.toLowerCase()),o=e.footnoteOrder.indexOf(n);let a;-1===o?(e.footnoteOrder.push(n),e.footnoteCounts[n]=1,a=e.footnoteOrder.length):(e.footnoteCounts[n]++,a=o+1);const s=e.footnoteCounts[n],c={type:"element",tagName:"a",properties:{href:"#"+e.clobberPrefix+"fn-"+r,id:e.clobberPrefix+"fnref-"+r+(s>1?"-"+s:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,c);const u={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,u),e.applyData(t,u)}function h(e,t){const n=t.referenceType;let r="]";if("collapsed"===n?r+="[]":"full"===n&&(r+="["+(t.label||t.identifier)+"]"),"imageReference"===t.type)return{type:"text",value:"!["+t.alt+r};const i=e.all(t),o=i[0];o&&"text"===o.type?o.value="["+o.value:i.unshift({type:"text",value:"["});const a=i[i.length-1];return a&&"text"===a.type?a.value+=r:i.push({type:"text",value:r}),i}function f(e){const t=e.spread;return null==t?e.children.length>1:t}var d=n(10743);const g={blockquote:function(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)},break:function(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:"\n"}]},code:function(e,t){const n=t.value?t.value+"\n":"",r=t.lang?t.lang.match(/^[^ \t]+(?=[ \t]|$)/):null,i={};r&&(i.className=["language-"+r]);let o={type:"element",tagName:"code",properties:i,children:[{type:"text",value:n}]};return t.meta&&(o.data={meta:t.meta}),e.patch(t,o),o=e.applyData(t,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(t,o),o},delete:function(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},emphasis:function(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},footnoteReference:l,footnote:function(e,t){const n=e.footnoteById;let r=1;for(;r in n;)r++;const i=String(r);return n[i]={type:"footnoteDefinition",identifier:i,children:[{type:"paragraph",children:t.children}],position:t.position},l(e,{type:"footnoteReference",identifier:i,position:t.position})},heading:function(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},html:function(e,t){if(e.dangerous){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}return null},imageReference:function(e,t){const n=e.definition(t.identifier);if(!n)return h(e,t);const r={src:i(n.url||""),alt:t.alt};null!==n.title&&void 0!==n.title&&(r.title=n.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,o),e.applyData(t,o)},image:function(e,t){const n={src:i(t.url)};null!==t.alt&&void 0!==t.alt&&(n.alt=t.alt),null!==t.title&&void 0!==t.title&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)},inlineCode:function(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)},linkReference:function(e,t){const n=e.definition(t.identifier);if(!n)return h(e,t);const r={href:i(n.url||"")};null!==n.title&&void 0!==n.title&&(r.title=n.title);const o={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)},link:function(e,t){const n={href:i(t.url)};null!==t.title&&void 0!==t.title&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)},listItem:function(e,t,n){const r=e.all(t),i=n?function(e){let t=!1;if("list"===e.type){t=e.spread||!1;const n=e.children;let r=-1;for(;!t&&++r<n.length;)t=f(n[r])}return t}(n):f(t),o={},a=[];if("boolean"==typeof t.checked){const e=r[0];let n;e&&"element"===e.type&&"p"===e.tagName?n=e:(n={type:"element",tagName:"p",properties:{},children:[]},r.unshift(n)),n.children.length>0&&n.children.unshift({type:"text",value:" "}),n.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let s=-1;for(;++s<r.length;){const e=r[s];(i||0!==s||"element"!==e.type||"p"!==e.tagName)&&a.push({type:"text",value:"\n"}),"element"!==e.type||"p"!==e.tagName||i?a.push(e):a.push(...e.children)}const c=r[r.length-1];c&&(i||"element"!==c.type||"p"!==c.tagName)&&a.push({type:"text",value:"\n"});const u={type:"element",tagName:"li",properties:o,children:a};return e.patch(t,u),e.applyData(t,u)},list:function(e,t){const n={},r=e.all(t);let i=-1;for("number"==typeof t.start&&1!==t.start&&(n.start=t.start);++i<r.length;){const e=r[i];if("element"===e.type&&"li"===e.tagName&&e.properties&&Array.isArray(e.properties.className)&&e.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const o={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(r,!0)};return e.patch(t,o),e.applyData(t,o)},paragraph:function(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},root:function(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)},strong:function(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},table:function(e,t){const n=e.all(t),r=n.shift(),i=[];if(r){const n={type:"element",tagName:"thead",properties:{},children:e.wrap([r],!0)};e.patch(t.children[0],n),i.push(n)}if(n.length>0){const r={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},o=(0,a.PW)(t.children[1]),s=(0,a.Y)(t.children[t.children.length-1]);o.line&&s.line&&(r.position={start:o,end:s}),i.push(r)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(i,!0)};return e.patch(t,o),e.applyData(t,o)},tableCell:function(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},tableRow:function(e,t,n){const r=n?n.children:void 0,i=0===(r?r.indexOf(t):1)?"th":"td",o=n&&"table"===n.type?n.align:void 0,a=o?o.length:t.children.length;let s=-1;const c=[];for(;++s<a;){const n=t.children[s],r={},a=o?o[s]:void 0;a&&(r.align=a);let u={type:"element",tagName:i,properties:r,children:[]};n&&(u.children=e.all(n),e.patch(n,u),u=e.applyData(t,u)),c.push(u)}const u={type:"element",tagName:"tr",properties:{},children:e.wrap(c,!0)};return e.patch(t,u),e.applyData(t,u)},text:function(e,t){const n={type:"text",value:(0,d.E)(String(t.value))};return e.patch(t,n),e.applyData(t,n)},thematicBreak:function(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)},toml:p,yaml:p,definition:p,footnoteDefinition:p};function p(){return null}const b={}.hasOwnProperty;function m(e,t){e.position&&(t.position=(0,a.G1)(e))}function w(e,t){let n=t;if(e&&e.data){const t=e.data.hName,r=e.data.hChildren,i=e.data.hProperties;"string"==typeof t&&("element"===n.type?n.tagName=t:n={type:"element",tagName:t,properties:{},children:[]}),"element"===n.type&&i&&(n.properties={...n.properties,...i}),"children"in n&&n.children&&null!=r&&(n.children=r)}return n}function v(e,t,n){const r=t&&t.type;if(!r)throw new Error("Expected node, got `"+t+"`");return b.call(e.handlers,r)?e.handlers[r](e,t,n):e.passThrough&&e.passThrough.includes(r)?"children"in t?{...t,children:y(e,t)}:t:e.unknownHandler?e.unknownHandler(e,t,n):function(e,t){const n=t.data||{},r=!("value"in t)||b.call(n,"hProperties")||b.call(n,"hChildren")?{type:"element",tagName:"div",properties:{},children:y(e,t)}:{type:"text",value:t.value};return e.patch(t,r),e.applyData(t,r)}(e,t)}function y(e,t){const n=[];if("children"in t){const r=t.children;let i=-1;for(;++i<r.length;){const o=v(e,r[i],t);if(o){if(i&&"break"===r[i-1].type&&(Array.isArray(o)||"text"!==o.type||(o.value=o.value.replace(/^\s+/,"")),!Array.isArray(o)&&"element"===o.type)){const e=o.children[0];e&&"text"===e.type&&(e.value=e.value.replace(/^\s+/,""))}Array.isArray(o)?n.push(...o):n.push(o)}}}return n}function S(e,t){const n=[];let r=-1;for(t&&n.push({type:"text",value:"\n"});++r<e.length;)r&&n.push({type:"text",value:"\n"}),n.push(e[r]);return t&&e.length>0&&n.push({type:"text",value:"\n"}),n}function k(e,t){const n=function(e,t){const n=t||{},r=n.allowDangerousHtml||!1,i={};return h.dangerous=r,h.clobberPrefix=void 0===n.clobberPrefix||null===n.clobberPrefix?"user-content-":n.clobberPrefix,h.footnoteLabel=n.footnoteLabel||"Footnotes",h.footnoteLabelTagName=n.footnoteLabelTagName||"h2",h.footnoteLabelProperties=n.footnoteLabelProperties||{className:["sr-only"]},h.footnoteBackLabel=n.footnoteBackLabel||"Back to content",h.unknownHandler=n.unknownHandler,h.passThrough=n.passThrough,h.handlers={...g,...n.handlers},h.definition=function(e){const t=Object.create(null);if(!e||!e.type)throw new Error("mdast-util-definitions expected node");return(0,o.YR)(e,"definition",(e=>{const n=u(e.identifier);n&&!c.call(t,n)&&(t[n]=e)})),function(e){const n=u(e);return n&&c.call(t,n)?t[n]:null}}(e),h.footnoteById=i,h.footnoteOrder=[],h.footnoteCounts={},h.patch=m,h.applyData=w,h.one=function(e,t){return v(h,e,t)},h.all=function(e){return y(h,e)},h.wrap=S,h.augment=l,(0,o.YR)(e,"footnoteDefinition",(e=>{const t=String(e.identifier).toUpperCase();b.call(i,t)||(i[t]=e)})),h;function l(e,t){if(e&&"data"in e&&e.data){const n=e.data;n.hName&&("element"!==t.type&&(t={type:"element",tagName:"",properties:{},children:[]}),t.tagName=n.hName),"element"===t.type&&n.hProperties&&(t.properties={...t.properties,...n.hProperties}),"children"in t&&t.children&&n.hChildren&&(t.children=n.hChildren)}if(e){const n="type"in e?e:{position:e};(0,s.g)(n)||(t.position={start:(0,a.PW)(n),end:(0,a.Y)(n)})}return t}function h(e,t,n,r){return Array.isArray(n)&&(r=n,n={}),l(e,{type:"element",tagName:t,properties:n||{},children:r||[]})}}(e,t),r=n.one(e,null),l=function(e){const t=[];let n=-1;for(;++n<e.footnoteOrder.length;){const r=e.footnoteById[e.footnoteOrder[n]];if(!r)continue;const o=e.all(r),a=String(r.identifier).toUpperCase(),s=i(a.toLowerCase());let c=0;const u=[];for(;++c<=e.footnoteCounts[a];){const t={type:"element",tagName:"a",properties:{href:"#"+e.clobberPrefix+"fnref-"+s+(c>1?"-"+c:""),dataFootnoteBackref:!0,className:["data-footnote-backref"],ariaLabel:e.footnoteBackLabel},children:[{type:"text",value:"↩"}]};c>1&&t.children.push({type:"element",tagName:"sup",children:[{type:"text",value:String(c)}]}),u.length>0&&u.push({type:"text",value:" "}),u.push(t)}const l=o[o.length-1];if(l&&"element"===l.type&&"p"===l.tagName){const e=l.children[l.children.length-1];e&&"text"===e.type?e.value+=" ":l.children.push({type:"text",value:" "}),l.children.push(...u)}else o.push(...u);const h={type:"element",tagName:"li",properties:{id:e.clobberPrefix+"fn-"+s},children:e.wrap(o,!0)};e.patch(r,h),t.push(h)}if(0!==t.length)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:e.footnoteLabelTagName,properties:{...JSON.parse(JSON.stringify(e.footnoteLabelProperties)),id:"footnote-label"},children:[{type:"text",value:e.footnoteLabel}]},{type:"text",value:"\n"},{type:"element",tagName:"ol",properties:{},children:e.wrap(t,!0)},{type:"text",value:"\n"}]}}(n);return l&&r.children.push({type:"text",value:"\n"},l),Array.isArray(r)?{type:"root",children:r}:r}},3131:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DropDatabaseTool=void 0;const r=n(58203);class i extends r.MongoDBToolBase{constructor(){super(...arguments),this.name="drop-database",this.description="Removes the specified database, deleting the associated data files",this.argsShape={database:r.DbOperationArgs.database}}async execute({database:e}){const t=await this.ensureConnected();return{content:[{text:`${(await t.dropDatabase(e)).ok?"Successfully dropped":"Failed to drop"} database "${e}"`,type:"text"}]}}getConfirmationMessage({database:e}){return`You are about to drop the \`${e}\` database:\n\nThis operation will permanently remove the database and ALL its collections, documents, and indexes.\n\n**Do you confirm the execution of the action?**`}}t.DropDatabaseTool=i,i.operationType="delete"},3357:(e,t,n)=>{var r=n(33433),i=n(372);function o(e){this.rand=e||new i.Rand}e.exports=o,o.create=function(e){return new o(e)},o.prototype._randbelow=function(e){var t=e.bitLength(),n=Math.ceil(t/8);do{var i=new r(this.rand.generate(n))}while(i.cmp(e)>=0);return i},o.prototype._randrange=function(e,t){var n=t.sub(e);return e.add(this._randbelow(n))},o.prototype.test=function(e,t,n){var i=e.bitLength(),o=r.mont(e),a=new r(1).toRed(o);t||(t=Math.max(1,i/48|0));for(var s=e.subn(1),c=0;!s.testn(c);c++);for(var u=e.shrn(c),l=s.toRed(o);t>0;t--){var h=this._randrange(new r(2),s);n&&n(h);var f=h.toRed(o).redPow(u);if(0!==f.cmp(a)&&0!==f.cmp(l)){for(var d=1;d<c;d++){if(0===(f=f.redSqr()).cmp(a))return!1;if(0===f.cmp(l))break}if(d===c)return!1}}return!0},o.prototype.getDivisor=function(e,t){var n=e.bitLength(),i=r.mont(e),o=new r(1).toRed(i);t||(t=Math.max(1,n/48|0));for(var a=e.subn(1),s=0;!a.testn(s);s++);for(var c=e.shrn(s),u=a.toRed(i);t>0;t--){var l=this._randrange(new r(2),a),h=e.gcd(l);if(0!==h.cmpn(1))return h;var f=l.toRed(i).redPow(c);if(0!==f.cmp(o)&&0!==f.cmp(u)){for(var d=1;d<s;d++){if(0===(f=f.redSqr()).cmp(o))return f.fromRed().subn(1).gcd(e);if(0===f.cmp(u))break}if(d===s)return(f=f.redSqr()).fromRed().subn(1).gcd(e)}}return!1}},3476:(e,t,n)=>{var r=n(9606).URL;Object.defineProperty(t,"__esModule",{value:!0}),t.ResourceTemplate=t.McpServer=void 0;const i=n(16444),o=n(16132),a=n(81461),s=n(17227),c=n(89512),u=n(22010),l=n(96606),h=n(84802),f=n(69761);t.McpServer=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new i.Server(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new h.ExperimentalMcpServerTasks(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(w(s.ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(w(s.CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(s.ListToolsRequestSchema,(()=>({tools:Object.entries(this._registeredTools).filter((([,e])=>e.enabled)).map((([e,t])=>{const n={name:e,title:t.title,description:t.description,inputSchema:(()=>{const e=(0,o.normalizeObjectSchema)(t.inputSchema);return e?(0,a.toJsonSchemaCompat)(e,{strictUnions:!0,pipeStrategy:"input"}):d})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){const e=(0,o.normalizeObjectSchema)(t.outputSchema);e&&(n.outputSchema=(0,a.toJsonSchemaCompat)(e,{strictUnions:!0,pipeStrategy:"output"}))}return n}))}))),this.server.setRequestHandler(s.CallToolRequestSchema,(async(e,t)=>{try{const n=this._registeredTools[e.params.name];if(!n)throw new s.McpError(s.ErrorCode.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new s.McpError(s.ErrorCode.InvalidParams,`Tool ${e.params.name} disabled`);const r=!!e.params.task,i=n.execution?.taskSupport,o="createTask"in n.handler;if(("required"===i||"optional"===i)&&!o)throw new s.McpError(s.ErrorCode.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if("required"===i&&!r)throw new s.McpError(s.ErrorCode.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if("optional"===i&&!r&&o)return await this.handleAutomaticTaskPolling(n,e,t);const a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,t);return r||await this.validateToolOutput(n,c,e.params.name),c}catch(e){if(e instanceof s.McpError&&e.code===s.ErrorCode.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}})),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;const r=(0,o.normalizeObjectSchema)(e.inputSchema)??e.inputSchema,i=await(0,o.safeParseAsync)(r,t);if(!i.success){const e="error"in i?i.error:"Unknown error",t=(0,o.getParseErrorMessage)(e);throw new s.McpError(s.ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${t}`)}return i.data}async validateToolOutput(e,t,n){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new s.McpError(s.ErrorCode.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const r=(0,o.normalizeObjectSchema)(e.outputSchema),i=await(0,o.safeParseAsync)(r,t.structuredContent);if(!i.success){const e="error"in i?i.error:"Unknown error",t=(0,o.getParseErrorMessage)(e);throw new s.McpError(s.ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${t}`)}}async executeToolHandler(e,t,n){const r=e.handler;if("createTask"in r){if(!n.taskStore)throw new Error("No task store provided.");const i={...n,taskStore:n.taskStore};if(e.inputSchema){const e=r;return await Promise.resolve(e.createTask(t,i))}{const e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){const e=r;return await Promise.resolve(e(t,n))}{const e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,o={...n,taskStore:n.taskStore},a=r?await Promise.resolve(i.createTask(r,o)):await Promise.resolve(i.createTask(o)),c=a.task.taskId;let u=a.task;const l=u.pollInterval??5e3;for(;"completed"!==u.status&&"failed"!==u.status&&"cancelled"!==u.status;){await new Promise((e=>setTimeout(e,l)));const e=await n.taskStore.getTask(c);if(!e)throw new s.McpError(s.ErrorCode.InternalError,`Task ${c} not found during polling`);u=e}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(w(s.CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(s.CompleteRequestSchema,(async e=>{switch(e.params.ref.type){case"ref/prompt":return(0,s.assertCompleteRequestPrompt)(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return(0,s.assertCompleteRequestResourceTemplate)(e),this.handleResourceCompletion(e,e.params.ref);default:throw new s.McpError(s.ErrorCode.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}})),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){const n=this._registeredPrompts[t.name];if(!n)throw new s.McpError(s.ErrorCode.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new s.McpError(s.ErrorCode.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return y;const r=(0,o.getObjectShape)(n.argsSchema),i=r?.[e.params.argument.name];if(!(0,c.isCompletable)(i))return y;const a=(0,c.getCompleter)(i);return a?v(await a(e.params.argument.value,e.params.context)):y}async handleResourceCompletion(e,t){const n=Object.values(this._registeredResourceTemplates).find((e=>e.resourceTemplate.uriTemplate.toString()===t.uri));if(!n){if(this._registeredResources[t.uri])return y;throw new s.McpError(s.ErrorCode.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?v(await r(e.params.argument.value,e.params.context)):y}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(w(s.ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(w(s.ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(w(s.ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(s.ListResourcesRequestSchema,(async(e,t)=>{const n=Object.entries(this._registeredResources).filter((([e,t])=>t.enabled)).map((([e,t])=>({uri:e,name:t.name,...t.metadata}))),r=[];for(const e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;const n=await e.resourceTemplate.listCallback(t);for(const t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}})),this.server.setRequestHandler(s.ListResourceTemplatesRequestSchema,(async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map((([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata})))}))),this.server.setRequestHandler(s.ReadResourceRequestSchema,(async(e,t)=>{const n=new r(e.params.uri),i=this._registeredResources[n.toString()];if(i){if(!i.enabled)throw new s.McpError(s.ErrorCode.InvalidParams,`Resource ${n} disabled`);return i.readCallback(n,t)}for(const e of Object.values(this._registeredResourceTemplates)){const r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new s.McpError(s.ErrorCode.InvalidParams,`Resource ${n} not found`)})),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(w(s.ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(w(s.GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(s.ListPromptsRequestSchema,(()=>({prompts:Object.entries(this._registeredPrompts).filter((([,e])=>e.enabled)).map((([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?m(t.argsSchema):void 0})))}))),this.server.setRequestHandler(s.GetPromptRequestSchema,(async(e,t)=>{const n=this._registeredPrompts[e.params.name];if(!n)throw new s.McpError(s.ErrorCode.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new s.McpError(s.ErrorCode.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){const r=(0,o.normalizeObjectSchema)(n.argsSchema),i=await(0,o.safeParseAsync)(r,e.params.arguments);if(!i.success){const t="error"in i?i.error:"Unknown error",n=(0,o.getParseErrorMessage)(t);throw new s.McpError(s.ErrorCode.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${n}`)}const a=i.data,c=n.callback;return await Promise.resolve(c(a,t))}{const e=n.callback;return await Promise.resolve(e(t))}})),this._promptHandlersInitialized=!0)}resource(e,t,...n){let r;"object"==typeof n[0]&&(r=n.shift());const i=n[0];if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){const o={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=o)),void 0!==e.name&&(o.name=e.name),void 0!==e.title&&(o.title=e.title),void 0!==e.metadata&&(o.metadata=e.metadata),void 0!==e.callback&&(o.readCallback=e.callback),void 0!==e.enabled&&(o.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=o,o}_createRegisteredResourceTemplate(e,t,n,r,i){const o={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=o)),void 0!==t.title&&(o.title=t.title),void 0!==t.template&&(o.resourceTemplate=t.template),void 0!==t.metadata&&(o.metadata=t.metadata),void 0!==t.callback&&(o.readCallback=t.callback),void 0!==t.enabled&&(o.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=o;const a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some((e=>!!n.completeCallback(e)))&&this.setCompletionRequestHandler(),o}_createRegisteredPrompt(e,t,n,r,i){const a={title:t,description:n,argsSchema:void 0===r?void 0:(0,o.objectFromShape)(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),void 0!==t.title&&(a.title=t.title),void 0!==t.description&&(a.description=t.description),void 0!==t.argsSchema&&(a.argsSchema=(0,o.objectFromShape)(t.argsSchema)),void 0!==t.callback&&(a.callback=t.callback),void 0!==t.enabled&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some((e=>{const t=e instanceof f.ZodOptional?e._def?.innerType:e;return(0,c.isCompletable)(t)}))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,s,c,u){(0,l.validateAndWarnToolName)(e);const h={title:t,description:n,inputSchema:b(r),outputSchema:b(i),annotations:a,execution:s,_meta:c,handler:u,enabled:!0,disable:()=>h.update({enabled:!1}),enable:()=>h.update({enabled:!0}),remove:()=>h.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&("string"==typeof t.name&&(0,l.validateAndWarnToolName)(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=h)),void 0!==t.title&&(h.title=t.title),void 0!==t.description&&(h.description=t.description),void 0!==t.paramsSchema&&(h.inputSchema=(0,o.objectFromShape)(t.paramsSchema)),void 0!==t.outputSchema&&(h.outputSchema=(0,o.objectFromShape)(t.outputSchema)),void 0!==t.callback&&(h.handler=t.callback),void 0!==t.annotations&&(h.annotations=t.annotations),void 0!==t._meta&&(h._meta=t._meta),void 0!==t.enabled&&(h.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=h,this.setToolRequestHandlers(),this.sendToolListChanged(),h}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,r,i;if("string"==typeof t[0]&&(n=t.shift()),t.length>1){const e=t[0];p(e)?(r=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!p(t[0])&&(i=t.shift())):"object"==typeof e&&null!==e&&(i=t.shift())}const o=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,i,{taskSupport:"forbidden"},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:r,description:i,inputSchema:o,outputSchema:a,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,o,a,s,{taskSupport:"forbidden"},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n,r;"string"==typeof t[0]&&(n=t.shift()),t.length>1&&(r=t.shift());const i=t[0],o=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:r,description:i,argsSchema:o}=t,a=this._createRegisteredPrompt(e,r,i,o,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},t.ResourceTemplate=class{constructor(e,t){this._callbacks=t,this._uriTemplate="string"==typeof e?new u.UriTemplate(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}};const d={type:"object",properties:{}};function g(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function p(e){return"object"==typeof e&&null!==e&&!function(e){return"_def"in e||"_zod"in e||g(e)}(e)&&(0===Object.keys(e).length||Object.values(e).some(g))}function b(e){if(e)return p(e)?(0,o.objectFromShape)(e):e}function m(e){const t=(0,o.getObjectShape)(e);return t?Object.entries(t).map((([e,t])=>({name:e,description:(0,o.getSchemaDescription)(t),required:!(0,o.isSchemaOptional)(t)}))):[]}function w(e){const t=(0,o.getObjectShape)(e),n=t?.method;if(!n)throw new Error("Schema is missing a method literal");const r=(0,o.getLiteralValue)(n);if("string"==typeof r)return r;throw new Error("Schema method literal must be a string")}function v(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const y={completion:{values:[],hasMore:!1}}},3668:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectTool=void 0;const r=n(69761),i=n(58203);class o extends i.MongoDBToolBase{constructor(e){super(e),this.name="connect",this.description="Connect to a MongoDB instance. The config resource captures if the server is already connected to a MongoDB cluster. If the user has configured a connection string or has previously called the connect tool, a connection is already established and there's no need to call this tool unless the user has explicitly requested to switch to a new MongoDB cluster.",this.argsShape={connectionString:r.z.string().describe("MongoDB connection string (in the mongodb:// or mongodb+srv:// format)")},e.session.on("connect",(()=>{this.disable()})),e.session.on("disconnect",(()=>{this.enable()}))}register(e){const t=super.register(e);return t&&this.session.isConnectedToMongoDB&&this.disable(),t}async execute({connectionString:e}){return await this.session.connectToMongoDB({connectionString:e}),{content:[{type:"text",text:"Successfully connected to MongoDB."}]}}}t.ConnectTool=o,o.operationType="connect"},4060:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Keychain=void 0,t.registerGlobalSecretToRedact=function(e,t){n.root.register(e,t)};class n{constructor(){this.secrets=[]}static get root(){return n.rootKeychain}register(e,t){this.secrets.push({value:e,kind:t})}clearAllSecrets(){this.secrets=[]}get allSecrets(){return[...this.secrets]}}t.Keychain=n,n.rootKeychain=new n},4341:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;const r=n(78249),i=n(63843),o=n(89689),a=n(7280);function s(e){const{gen:t,data:n,it:i}=e;t.if(i.parentData,(()=>t.assign(n,r._`${i.parentData}[${i.parentDataProperty}]`)))}function c(e,t,n){if(void 0===n)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword","function"==typeof n?{ref:n}:{ref:n,code:(0,r.stringify)(n)})}t.macroKeywordCode=function(e,t){const{gen:n,keyword:i,schema:o,parentSchema:a,it:s}=e,u=t.macro.call(s.self,o,a,s),l=c(n,i,u);!1!==s.opts.validateSchema&&s.self.validateSchema(u,!0);const h=n.name("valid");e.subschema({schema:u,schemaPath:r.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},h),e.pass(h,(()=>e.error(!0)))},t.funcKeywordCode=function(e,t){var n;const{gen:u,keyword:l,schema:h,parentSchema:f,$data:d,it:g}=e;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(g,t);const p=!d&&t.compile?t.compile.call(g.self,h,f,g):t.validate,b=c(u,l,p),m=u.let("valid");function w(n=(t.async?r._`await `:r.nil)){const a=g.opts.passContext?i.default.this:i.default.self,s=!("compile"in t&&!d||!1===t.schema);u.assign(m,r._`${n}${(0,o.callValidateCode)(e,b,a,s)}`,t.modifying)}function v(e){var n;u.if((0,r.not)(null!==(n=t.valid)&&void 0!==n?n:m),e)}e.block$data(m,(function(){if(!1===t.errors)w(),t.modifying&&s(e),v((()=>e.error()));else{const n=t.async?function(){const e=u.let("ruleErrs",null);return u.try((()=>w(r._`await `)),(t=>u.assign(m,!1).if(r._`${t} instanceof ${g.ValidationError}`,(()=>u.assign(e,r._`${t}.errors`)),(()=>u.throw(t))))),e}():function(){const e=r._`${b}.errors`;return u.assign(e,null),w(r.nil),e}();t.modifying&&s(e),v((()=>function(e,t){const{gen:n}=e;n.if(r._`Array.isArray(${t})`,(()=>{n.assign(i.default.vErrors,r._`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`).assign(i.default.errors,r._`${i.default.vErrors}.length`),(0,a.extendErrors)(e)}),(()=>e.error()))}(e,n)))}})),e.ok(null!==(n=t.valid)&&void 0!==n?n:m)},t.validSchemaType=function(e,t,n=!1){return!t.length||t.some((t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||n&&void 0===e))},t.validateKeywordUsage=function({schema:e,opts:t,self:n,errSchemaPath:r},i,o){if(Array.isArray(i.keyword)?!i.keyword.includes(o):i.keyword!==o)throw new Error("ajv implementation error");const a=i.dependencies;if(null==a?void 0:a.some((t=>!Object.prototype.hasOwnProperty.call(e,t))))throw new Error(`parent schema must have dependencies of ${o}: ${a.join(",")}`);if(i.validateSchema&&!i.validateSchema(e[o])){const e=`keyword "${o}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);n.logger.error(e)}}},4429:(e,t,n)=>{n.d(t,{$Z:()=>a,AO:()=>p,Ay:()=>i,GH:()=>s,Kz:()=>d,Yr:()=>h,aN:()=>g,e1:()=>o,eH:()=>c,mj:()=>u,ol:()=>l,r4:()=>f,tf:()=>b});var r=n(25364);const i=r.default,o=r.DEFAULT_COLLATION,a=r.DEFAULT_FILTER,s=r.DEFAULT_HINT,c=r.DEFAULT_LIMIT,u=r.DEFAULT_MAX_TIME_MS,l=r.DEFAULT_PROJECT,h=r.DEFAULT_SKIP,f=r.DEFAULT_SORT,d=r.isCollationValid,g=(r.isFilterValid,r.isHintValid,r.isLimitValid,r.isMaxTimeMSValid,r.isProjectValid,r.isSkipValid,r.isSortValid,r.parseCollation,r.parseFilter),p=(r.parseProject,r.parseSort,r.stringify,r.toJSString),b=r.validate},4743:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WebStandardStreamableHTTPServerTransport=void 0;const r=n(17227);t.WebStandardStreamableHTTPServerTransport=class{constructor(e={}){this._started=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(e,t,n,r){const i={code:t,message:n};return void 0!==r?.data&&(i.data=r.data),new Response(JSON.stringify({jsonrpc:"2.0",error:i,id:null}),{status:e,headers:{"Content-Type":"application/json",...r?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){const t=e.headers.get("host");if(!t||!this._allowedHosts.includes(t)){const e=`Invalid Host header: ${t}`;return this.onerror?.(new Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){const t=e.headers.get("origin");if(t&&!this._allowedOrigins.includes(t)){const e=`Invalid Origin header: ${t}`;return this.onerror?.(new Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){const n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case"POST":return this.handlePostRequest(e,t);case"GET":return this.handleGetRequest(e);case"DELETE":return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,n,r){if(!this._eventStore)return;if(r<"2025-11-25")return;const i=await this._eventStore.storeEvent(n,{});let o=`id: ${i}\ndata: \n\n`;void 0!==this._retryInterval&&(o=`id: ${i}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(o))}async handleGetRequest(e){const t=e.headers.get("accept");if(!t?.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept text/event-stream");const n=this.validateSession(e);if(n)return n;const r=this.validateProtocolVersion(e);if(r)return r;if(this._eventStore){const t=e.headers.get("last-event-id");if(t)return this.replayEvents(t)}if(void 0!==this._streamMapping.get(this._standaloneSseStreamId))return this.createJsonErrorResponse(409,-32e3,"Conflict: Only one SSE stream is allowed per session");const i=new TextEncoder;let o;const a=new ReadableStream({start:e=>{o=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),s={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};return void 0!==this.sessionId&&(s["mcp-session-id"]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:o,encoder:i,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{o.close()}catch{}}}),new Response(a,{headers:s})}async replayEvents(e){if(!this._eventStore)return this.createJsonErrorResponse(400,-32e3,"Event store not configured");try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.createJsonErrorResponse(400,-32e3,"Invalid event ID format");if(void 0!==this._streamMapping.get(t))return this.createJsonErrorResponse(409,-32e3,"Conflict: Stream already has an active connection")}const n={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};void 0!==this.sessionId&&(n["mcp-session-id"]=this.sessionId);const r=new TextEncoder;let i;const o=new ReadableStream({start:e=>{i=e},cancel:()=>{}}),a=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(i,r,t,e)){this.onerror?.(new Error("Failed replay events"));try{i.close()}catch{}}}});return this._streamMapping.set(a,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(a);try{i.close()}catch{}}}),new Response(o,{headers:n})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,"Error replaying events")}}writeSSEEvent(e,t,n,r){try{let i="event: message\n";return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,t){try{const n=e.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");const i=e.headers.get("content-type");if(!i||!i.includes("application/json"))return this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");const o={headers:Object.fromEntries(e.headers.entries())};let a,s;if(void 0!==t?.parsedBody)a=t.parsedBody;else try{a=await e.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}try{s=Array.isArray(a)?a.map((e=>r.JSONRPCMessageSchema.parse(e))):[r.JSONRPCMessageSchema.parse(a)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}const c=s.some(r.isInitializeRequest);if(c){if(this._initialized&&void 0!==this.sessionId)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(s.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!c){const t=this.validateSession(e);if(t)return t;const n=this.validateProtocolVersion(e);if(n)return n}if(!s.some(r.isJSONRPCRequest)){for(const e of s)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:o});return new Response(null,{status:202})}const u=crypto.randomUUID(),l=s.find((e=>(0,r.isInitializeRequest)(e))),h=l?l.params.protocolVersion:e.headers.get("mcp-protocol-version")??r.DEFAULT_NEGOTIATED_PROTOCOL_VERSION;if(this._enableJsonResponse)return new Promise((e=>{this._streamMapping.set(u,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(u)}});for(const e of s)(0,r.isJSONRPCRequest)(e)&&this._requestToStreamMapping.set(e.id,u);for(const e of s)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:o})}));const f=new TextEncoder;let d;const g=new ReadableStream({start:e=>{d=e},cancel:()=>{this._streamMapping.delete(u)}}),p={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};void 0!==this.sessionId&&(p["mcp-session-id"]=this.sessionId);for(const e of s)(0,r.isJSONRPCRequest)(e)&&(this._streamMapping.set(u,{controller:d,encoder:f,cleanup:()=>{this._streamMapping.delete(u);try{d.close()}catch{}}}),this._requestToStreamMapping.set(e.id,u));await this.writePrimingEvent(d,f,u,h);for(const e of s){let n,i;(0,r.isJSONRPCRequest)(e)&&this._eventStore&&h>="2025-11-25"&&(n=()=>{this.closeSSEStream(e.id)},i=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:o,closeSSEStream:n,closeStandaloneSSEStream:i})}return new Response(g,{status:200,headers:p})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(e)})}}async handleDeleteRequest(e){const t=this.validateSession(e);if(t)return t;return this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(void 0===this.sessionIdGenerator)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");const t=e.headers.get("mcp-session-id");return t?t!==this.sessionId?this.createJsonErrorResponse(404,-32001,"Session not found"):void 0:this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required")}validateProtocolVersion(e){const t=e.headers.get("mcp-protocol-version");if(null!==t&&!r.SUPPORTED_PROTOCOL_VERSIONS.includes(t))return this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${r.SUPPORTED_PROTOCOL_VERSIONS.join(", ")})`)}async close(){this._streamMapping.forEach((({cleanup:e})=>{e()})),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){const t=this._requestToStreamMapping.get(e);if(!t)return;const n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){const e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if(((0,r.isJSONRPCResultResponse)(e)||(0,r.isJSONRPCErrorResponse)(e))&&(n=e.id),void 0===n){if((0,r.isJSONRPCResultResponse)(e)||(0,r.isJSONRPCErrorResponse)(e))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));const n=this._streamMapping.get(this._standaloneSseStreamId);if(void 0===n)return;return void(n.controller&&n.encoder&&this.writeSSEEvent(n.controller,n.encoder,e,t))}const i=this._requestToStreamMapping.get(n);if(!i)throw new Error(`No connection established for request ID: ${String(n)}`);const o=this._streamMapping.get(i);if(!this._enableJsonResponse&&o?.controller&&o?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(i,e)),this.writeSSEEvent(o.controller,o.encoder,e,t)}if((0,r.isJSONRPCResultResponse)(e)||(0,r.isJSONRPCErrorResponse)(e)){this._requestResponseMap.set(n,e);const t=Array.from(this._requestToStreamMapping.entries()).filter((([e,t])=>t===i)).map((([e])=>e));if(t.every((e=>this._requestResponseMap.has(e)))){if(!o)throw new Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&o.resolveJson){const e={"Content-Type":"application/json"};void 0!==this.sessionId&&(e["mcp-session-id"]=this.sessionId);const n=t.map((e=>this._requestResponseMap.get(e)));1===n.length?o.resolveJson(new Response(JSON.stringify(n[0]),{status:200,headers:e})):o.resolveJson(new Response(JSON.stringify(n),{status:200,headers:e}))}else o.cleanup();for(const e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}}},5805:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Resources=void 0;const r=n(55648),i=n(72227),o=n(68097);t.Resources=[r.ConfigResource,i.DebugResource,o.ExportedData]},5853:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_ACCESS_LIST_COMMENT=void 0,t.makeCurrentIpAccessListEntry=o,t.ensureCurrentIpInAccessList=async function(e,n){const a=await o(e,n,t.DEFAULT_ACCESS_LIST_COMMENT);try{return await e.createAccessListEntry({params:{path:{groupId:n}},body:[a]}),e.logger.debug({id:r.LogId.atlasIpAccessListAdded,context:"accessListUtils",message:`IP access list created: ${JSON.stringify(a)}`}),!0}catch(t){if(t instanceof i.ApiClientError&&409===t.response?.status)return e.logger.debug({id:r.LogId.atlasIpAccessListAdded,context:"accessListUtils",message:`IP address ${a.ipAddress} is already present in the access list for project ${n}.`}),!1;e.logger.warning({id:r.LogId.atlasIpAccessListAddFailure,context:"accessListUtils",message:`Error adding IP access list: ${t instanceof Error?t.message:String(t)}`})}return!1};const r=n(45584),i=n(7303);async function o(e,n,r=t.DEFAULT_ACCESS_LIST_COMMENT){const{currentIpv4Address:i}=await e.getIpInfo();return{groupId:n,ipAddress:i,comment:r}}t.DEFAULT_ACCESS_LIST_COMMENT="Added by MongoDB MCP Server to enable tool access"},6416:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListAlertsTool=t.ListAlertsArgs=void 0;const r=n(77710),i=n(55415),o=n(14233);t.ListAlertsArgs={projectId:o.AtlasArgs.projectId().describe("Atlas project ID to list alerts for")};class a extends i.AtlasToolBase{constructor(){super(...arguments),this.name="atlas-list-alerts",this.description="List MongoDB Atlas alerts",this.argsShape={...t.ListAlertsArgs}}async execute({projectId:e}){const t=await this.apiClient.listAlerts({params:{path:{groupId:e}}});if(!t?.results?.length)return{content:[{type:"text",text:"No alerts found in your MongoDB Atlas project."}]};const n=t.results.map((e=>({id:e.id,status:e.status,created:e.created?new Date(e.created).toISOString():"N/A",updated:e.updated?new Date(e.updated).toISOString():"N/A",eventTypeName:e.eventTypeName,acknowledgementComment:e.acknowledgementComment??"N/A"})));return{content:(0,r.formatUntrustedData)(`Found ${t.results.length} alerts in project ${e}`,JSON.stringify(n))}}}t.ListAlertsTool=a,a.operationType="read"},6467:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Elicitation=void 0;class n{constructor({server:e}){this.server=e}supportsElicitation(){const e=this.server.getClientCapabilities();return void 0!==e?.elicitation}async requestConfirmation(e){if(!this.supportsElicitation())return!0;const t=await this.server.elicitInput({mode:"form",message:e,requestedSchema:n.CONFIRMATION_SCHEMA});return"accept"===t.action&&"Yes"===t.content?.confirmation}}t.Elicitation=n,n.CONFIRMATION_SCHEMA={type:"object",properties:{confirmation:{type:"string",title:"Would you like to confirm?",description:"Would you like to confirm?",enum:["Yes","No"],enumNames:["Yes, I confirm","No, I do not confirm"]}},required:["confirmation"]}},6578:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CreateProjectTool=void 0;const r=n(55415),i=n(14233);class o extends r.AtlasToolBase{constructor(){super(...arguments),this.name="atlas-create-project",this.description="Create a MongoDB Atlas project",this.argsShape={projectName:i.AtlasArgs.projectName().optional().describe("Name for the new project"),organizationId:i.AtlasArgs.organizationId().optional().describe("Organization ID for the new project")}}async execute({projectName:e,organizationId:t}){let n=!1;if(e||(e="Atlas Project"),!t)try{const e=await this.apiClient.listOrgs();if(!e?.results?.length)throw new Error("No organizations were found in your MongoDB Atlas account. Please create an organization first.");const r=e.results[0];if(!r?.id)throw new Error("The first organization found does not have an ID. Please check your Atlas account.");t=r.id,n=!0}catch{throw new Error("Could not search for organizations in your MongoDB Atlas account, please provide an organization ID or create one first.")}const r={name:e,orgId:t},i=await this.apiClient.createGroup({body:r});if(!i?.id)throw new Error("Failed to create project");return{content:[{type:"text",text:`Project "${e}" created successfully${n?` (using organizationId ${t}).`:""}.`}]}}}t.CreateProjectTool=o,o.operationType="create"},6976:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(87351),i={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:n,it:i}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");const o=t.name("valid");n.forEach(((t,n)=>{if((0,r.alwaysValidSchema)(i,t))return;const a=e.subschema({keyword:"allOf",schemaProp:n},o);e.ok(o),e.mergeEvaluated(a)}))}};t.default=i},7280:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const r=n(78249),i=n(87351),o=n(63843);function a(e,t){const n=e.const("err",t);e.if(r._`${o.default.vErrors} === null`,(()=>e.assign(o.default.vErrors,r._`[${n}]`)),r._`${o.default.vErrors}.push(${n})`),e.code(r._`${o.default.errors}++`)}function s(e,t){const{gen:n,validateName:i,schemaEnv:o}=e;o.$async?n.throw(r._`new ${e.ValidationError}(${t})`):(n.assign(r._`${i}.errors`,t),n.return(!1))}t.keywordError={message:({keyword:e})=>r.str`must pass "${e}" keyword validation`},t.keyword$DataError={message:({keyword:e,schemaType:t})=>t?r.str`"${e}" keyword must be ${t} ($data)`:r.str`"${e}" keyword is invalid ($data)`},t.reportError=function(e,n=t.keywordError,i,o){const{it:c}=e,{gen:l,compositeRule:h,allErrors:f}=c,d=u(e,n,i);(null!=o?o:h||f)?a(l,d):s(c,r._`[${d}]`)},t.reportExtraError=function(e,n=t.keywordError,r){const{it:i}=e,{gen:c,compositeRule:l,allErrors:h}=i;a(c,u(e,n,r)),l||h||s(i,o.default.vErrors)},t.resetErrorsCount=function(e,t){e.assign(o.default.errors,t),e.if(r._`${o.default.vErrors} !== null`,(()=>e.if(t,(()=>e.assign(r._`${o.default.vErrors}.length`,t)),(()=>e.assign(o.default.vErrors,null)))))},t.extendErrors=function({gen:e,keyword:t,schemaValue:n,data:i,errsCount:a,it:s}){if(void 0===a)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",a,o.default.errors,(a=>{e.const(c,r._`${o.default.vErrors}[${a}]`),e.if(r._`${c}.instancePath === undefined`,(()=>e.assign(r._`${c}.instancePath`,(0,r.strConcat)(o.default.instancePath,s.errorPath)))),e.assign(r._`${c}.schemaPath`,r.str`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign(r._`${c}.schema`,n),e.assign(r._`${c}.data`,i))}))};const c={keyword:new r.Name("keyword"),schemaPath:new r.Name("schemaPath"),params:new r.Name("params"),propertyName:new r.Name("propertyName"),message:new r.Name("message"),schema:new r.Name("schema"),parentSchema:new r.Name("parentSchema")};function u(e,t,n){const{createErrors:i}=e.it;return!1===i?r._`{}`:function(e,t,n={}){const{gen:i,it:a}=e,s=[l(a,n),h(e,n)];return function(e,{params:t,message:n},i){const{keyword:a,data:s,schemaValue:u,it:l}=e,{opts:h,propertyName:f,topSchemaRef:d,schemaPath:g}=l;i.push([c.keyword,a],[c.params,"function"==typeof t?t(e):t||r._`{}`]),h.messages&&i.push([c.message,"function"==typeof n?n(e):n]),h.verbose&&i.push([c.schema,u],[c.parentSchema,r._`${d}${g}`],[o.default.data,s]),f&&i.push([c.propertyName,f])}(e,t,s),i.object(...s)}(e,t,n)}function l({errorPath:e},{instancePath:t}){const n=t?r.str`${e}${(0,i.getErrorPath)(t,i.Type.Str)}`:e;return[o.default.instancePath,(0,r.strConcat)(o.default.instancePath,n)]}function h({keyword:e,it:{errSchemaPath:t}},{schemaPath:n,parentSchema:o}){let a=o?t:r.str`${t}/${e}`;return n&&(a=r.str`${a}${(0,i.getErrorPath)(n,i.Type.Str)}`),[c.schemaPath,a]}},7303:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ApiClientError=void 0;class n extends Error{constructor(e,t,n){super(e),this.response=t,this.apiError=n,this.name="ApiClientError"}static async fromResponse(e,t="error calling Atlas API"){const n=await this.extractError(e);return this.fromError(e,n,t)}static fromError(e,t,r="error calling Atlas API"){const i=this.buildErrorMessage(t),o="object"!=typeof t||t instanceof Error?void 0:t;return new n(`[${e.status} ${e.statusText}] ${r}: ${i}`,e,o)}static async extractError(e){try{return await e.json()}catch{try{return await e.text()}catch{return}}}static buildErrorMessage(e){let t="unknown error";if(e instanceof Error)return e.message;switch(typeof e){case"object":t=e.reason||"unknown error",e.detail&&e.detail.length>0&&(t=`${t}; ${e.detail}`);break;case"string":t=e}return t.trim()}}t.ApiClientError=n},9015:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountTool=t.CountArgs=void 0;const r=n(58203),i=n(49446),o=n(14233);t.CountArgs={query:(0,o.zEJSON)().optional().describe("A filter/query parameter. Allows users to filter the documents to count. Matches the syntax of the filter argument of db.collection.count().")};class a extends r.MongoDBToolBase{constructor(){super(...arguments),this.name="count",this.description="Gets the number of documents in a MongoDB collection using db.collection.count() and query as an optional filter parameter",this.argsShape={...r.DbOperationArgs,...t.CountArgs}}async execute({database:e,collection:t,query:n},{signal:r}){const o=await this.ensureConnected();return this.config.indexCheck&&await(0,i.checkIndexUsage)({database:e,collection:t,operation:"count",explainCallback:async()=>o.runCommandWithCheck(e,{explain:{count:t,query:n},verbosity:"queryPlanner"},{signal:r}),logger:this.session.logger}),{content:[{text:`Found ${await o.countDocuments(e,t,n,{signal:r})} documents in the collection "${t}"${n?" that matched the query":""}.`,type:"text"}]}}}t.CountTool=a,a.operationType="read"},9351:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.generateUri=function(e){if(e.nodb)return"";const t=function(e){const t=e.connectionSpecifier,{replSetName:n,hosts:r}=function(e){if(!e)return{};const[t,n,...r]=e.split("/").reverse();if(r.length)return{};const i=t.split(",").filter(Boolean);return i.every((e=>/^([A-Za-z0-9._-]+|\[[0-9a-fA-F:]+\])(:\d+)?$/.test(e)))?{replSetName:n,hosts:i}:{}}(e.host);if(n||(null!=r?r:[]).length>1){const s=new a.ConnectionString(`mongodb://replacemeHost/${encodeURIComponent(t||"")}`);return s.hosts=function(e,t){var n,r;const a=[];for(const s of e){const{host:e,port:c}=null!==(r=null===(n=/^(?<host>.+?)(:(?<port>\d+))?$/.exec(s))||void 0===n?void 0:n.groups)&&void 0!==r?r:{};if(t&&void 0!==c&&c!==t)throw new i.MongoshInvalidInputError(o.default.__(h),i.CommonErrors.InvalidArgument);a.push(`${e}${c||t?`:${c||t}`:""}`)}return a}(null!=r?r:[],e.port),n&&s.searchParams.set("replicaSet",n),w(s)}if(!t)return new a.ConnectionString(`mongodb://${b(e)}:${m(e)}/?directConnection=true`);if(t.startsWith("mongodb+srv://")){const n=new a.ConnectionString(t);return g(e,n),n}if(t.startsWith("mongodb://")){const n=new a.ConnectionString(t);return g(e,n),w(n)}let s=/^([A-Za-z0-9][A-Za-z0-9._-]+)(?::(\d+))?(?:\/(\S*))?$/gi.exec(t);if(null===s){if(/[/\\. "$]/.test(t))throw new i.MongoshInvalidInputError(`Invalid URI: ${t}`,i.CommonErrors.InvalidArgument);s=[t,t]}let c=null==s?void 0:s[1];const u=null==s?void 0:s[2];let l=null==s?void 0:s[3];return!u&&!l&&c.indexOf(".")<0&&(l=c,c=void 0),(c||u)&&g(e),w(new a.ConnectionString(`mongodb://${c||b(e)}:${u||m(e)}/${encodeURIComponent(l||"")}`))}(e);if(t.hosts.every((e=>["localhost","127.0.0.1"].includes(e.split(":")[0])))){const e=t.searchParams;e.has("serverSelectionTimeoutMS")||e.set("serverSelectionTimeoutMS","2000")}return t.toString()};const i=n(47454),o=r(n(97770)),a=n(14052),s="127.0.0.1",c="27017",u="cli-repl.uri-generator.no-host-port",l="cli-repl.uri-generator.invalid-host",h="cli-repl.uri-generator.host-list-port-mismatch",f="cli-repl.uri-generator.diverging-service-name",d="cli-repl.uri-generator.gssapi-service-name-unsupported";function g(e,t){if(e.host||e.port)throw new i.MongoshInvalidInputError(o.default.__(u),i.CommonErrors.InvalidArgument);if(e.gssapiServiceName&&(null==t?void 0:t.searchParams.has("authMechanismProperties"))){const n=new a.CommaAndColonSeparatedRecord(t.searchParams.get("authMechanismProperties")).get("SERVICE_NAME");if(void 0!==n&&e.gssapiServiceName!==n)throw new i.MongoshInvalidInputError(o.default.__(f),i.CommonErrors.InvalidArgument)}if(null==t?void 0:t.searchParams.has("gssapiServiceName"))throw new i.MongoshInvalidInputError(o.default.__(d),i.CommonErrors.InvalidArgument)}function p(e){const t=/[^a-zA-Z0-9.:[\]_-]/.exec(e);if(t)throw new i.MongoshInvalidInputError(`${o.default.__(l)}: ${t[0]}`,i.CommonErrors.InvalidArgument)}function b(e){return e.host?(p(e.host),e.host.includes(":")?e.host.split(":")[0]:e.host):s}function m(e){if(e.host&&e.host.includes(":")){p(e.host);const t=e.host.split(":")[1];if(!e.port||e.port===t)return t;throw new i.MongoshInvalidInputError(o.default.__(u),i.CommonErrors.InvalidArgument)}return e.port?e.port:c}function w(e){const t=(e=e.clone()).searchParams;return t.has("replicaSet")||t.has("directConnection")||t.has("loadBalanced")||1!==e.hosts.length||t.set("directConnection","true"),e}},9517:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(78249),i=n(87351),o={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:e})=>r._`{propertyName: ${e.propertyName}}`},code(e){const{gen:t,schema:n,data:o,it:a}=e;if((0,i.alwaysValidSchema)(a,n))return;const s=t.name("valid");t.forIn("key",o,(n=>{e.setParams({propertyName:n}),e.subschema({keyword:"propertyNames",data:n,dataTypes:["string"],propertyName:n,compositeRule:!0},s),t.if((0,r.not)(s),(()=>{e.error(!0),a.allErrors||t.break()}))})),e.ok(s)}};t.default=o},9527:(e,t,n)=>{var r=n(25003),i=n(33820),o=n(79696).Buffer,a=new Array(16);function s(){i.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}function c(e,t){return e<<t|e>>>32-t}function u(e,t,n,r,i,o,a){return c(e+(t&n|~t&r)+i+o|0,a)+t|0}function l(e,t,n,r,i,o,a){return c(e+(t&r|n&~r)+i+o|0,a)+t|0}function h(e,t,n,r,i,o,a){return c(e+(t^n^r)+i+o|0,a)+t|0}function f(e,t,n,r,i,o,a){return c(e+(n^(t|~r))+i+o|0,a)+t|0}r(s,i),s.prototype._update=function(){for(var e=a,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var n=this._a,r=this._b,i=this._c,o=this._d;n=u(n,r,i,o,e[0],3614090360,7),o=u(o,n,r,i,e[1],3905402710,12),i=u(i,o,n,r,e[2],606105819,17),r=u(r,i,o,n,e[3],3250441966,22),n=u(n,r,i,o,e[4],4118548399,7),o=u(o,n,r,i,e[5],1200080426,12),i=u(i,o,n,r,e[6],2821735955,17),r=u(r,i,o,n,e[7],4249261313,22),n=u(n,r,i,o,e[8],1770035416,7),o=u(o,n,r,i,e[9],2336552879,12),i=u(i,o,n,r,e[10],4294925233,17),r=u(r,i,o,n,e[11],2304563134,22),n=u(n,r,i,o,e[12],1804603682,7),o=u(o,n,r,i,e[13],4254626195,12),i=u(i,o,n,r,e[14],2792965006,17),n=l(n,r=u(r,i,o,n,e[15],1236535329,22),i,o,e[1],4129170786,5),o=l(o,n,r,i,e[6],3225465664,9),i=l(i,o,n,r,e[11],643717713,14),r=l(r,i,o,n,e[0],3921069994,20),n=l(n,r,i,o,e[5],3593408605,5),o=l(o,n,r,i,e[10],38016083,9),i=l(i,o,n,r,e[15],3634488961,14),r=l(r,i,o,n,e[4],3889429448,20),n=l(n,r,i,o,e[9],568446438,5),o=l(o,n,r,i,e[14],3275163606,9),i=l(i,o,n,r,e[3],4107603335,14),r=l(r,i,o,n,e[8],1163531501,20),n=l(n,r,i,o,e[13],2850285829,5),o=l(o,n,r,i,e[2],4243563512,9),i=l(i,o,n,r,e[7],1735328473,14),n=h(n,r=l(r,i,o,n,e[12],2368359562,20),i,o,e[5],4294588738,4),o=h(o,n,r,i,e[8],2272392833,11),i=h(i,o,n,r,e[11],1839030562,16),r=h(r,i,o,n,e[14],4259657740,23),n=h(n,r,i,o,e[1],2763975236,4),o=h(o,n,r,i,e[4],1272893353,11),i=h(i,o,n,r,e[7],4139469664,16),r=h(r,i,o,n,e[10],3200236656,23),n=h(n,r,i,o,e[13],681279174,4),o=h(o,n,r,i,e[0],3936430074,11),i=h(i,o,n,r,e[3],3572445317,16),r=h(r,i,o,n,e[6],76029189,23),n=h(n,r,i,o,e[9],3654602809,4),o=h(o,n,r,i,e[12],3873151461,11),i=h(i,o,n,r,e[15],530742520,16),n=f(n,r=h(r,i,o,n,e[2],3299628645,23),i,o,e[0],4096336452,6),o=f(o,n,r,i,e[7],1126891415,10),i=f(i,o,n,r,e[14],2878612391,15),r=f(r,i,o,n,e[5],4237533241,21),n=f(n,r,i,o,e[12],1700485571,6),o=f(o,n,r,i,e[3],2399980690,10),i=f(i,o,n,r,e[10],4293915773,15),r=f(r,i,o,n,e[1],2240044497,21),n=f(n,r,i,o,e[8],1873313359,6),o=f(o,n,r,i,e[15],4264355552,10),i=f(i,o,n,r,e[6],2734768916,15),r=f(r,i,o,n,e[13],1309151649,21),n=f(n,r,i,o,e[4],4149444226,6),o=f(o,n,r,i,e[11],3174756917,10),i=f(i,o,n,r,e[2],718787259,15),r=f(r,i,o,n,e[9],3951481745,21),this._a=this._a+n|0,this._b=this._b+r|0,this._c=this._c+i|0,this._d=this._d+o|0},s.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=o.allocUnsafe(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e},e.exports=s},9651:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ParseMode=void 0,t.parse=s;const r=n(84537),i=n(40967),o=n(54553),a=n(86577);function s(e,t){const n=(0,a.buildOptions)(t),{hasComments:s,ast:c}=function(e){let t=!1;return{ast:(0,r.parse)(e,{ecmaVersion:6,onComment:()=>t=!0,locations:!0,ranges:!0,sourceFile:e}),hasComments:t}}(`(\n${e}\n)`);return s&&!n.allowComments||!(0,i.checkTree)(c,n)?"":(0,o.executeAST)(c)}Object.defineProperty(t,"ParseMode",{enumerable:!0,get:function(){return a.ParseMode}}),t.default=s},10083:(e,t,n)=>{var r=n(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.ReadBuffer=void 0,t.deserializeMessage=o,t.serializeMessage=function(e){return JSON.stringify(e)+"\n"};const i=n(17227);function o(e){return i.JSONRPCMessageSchema.parse(JSON.parse(e))}t.ReadBuffer=class{append(e){this._buffer=this._buffer?r.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),o(t)}clear(){this._buffer=void 0}}},11062:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CreateCollectionTool=void 0;const r=n(58203);class i extends r.MongoDBToolBase{constructor(){super(...arguments),this.name="create-collection",this.description="Creates a new collection in a database. If the database doesn't exist, it will be created automatically.",this.argsShape=r.DbOperationArgs}async execute({collection:e,database:t}){const n=await this.ensureConnected();return await n.createCollection(t,e),{content:[{type:"text",text:`Collection "${e}" created in database "${t}".`}]}}}t.CreateCollectionTool=i,i.operationType="create"},12281:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListDBUsersTool=t.ListDBUsersArgs=void 0;const r=n(55415),i=n(77710),o=n(14233);t.ListDBUsersArgs={projectId:o.AtlasArgs.projectId().describe("Atlas project ID to filter DB users")};class a extends r.AtlasToolBase{constructor(){super(...arguments),this.name="atlas-list-db-users",this.description="List MongoDB Atlas database users",this.argsShape={...t.ListDBUsersArgs}}async execute({projectId:e}){const t=await this.apiClient.listDatabaseUsers({params:{path:{groupId:e}}});if(!t?.results?.length)return{content:[{type:"text",text:" No database users found"}]};const n=t.results.map((e=>({username:e.username,roles:e.roles?.map((e=>({roleName:e.roleName,databaseName:e.databaseName,collectionName:e.collectionName})))??[],scopes:e.scopes?.map((e=>({type:e.type,name:e.name})))??[]})));return{content:(0,i.formatUntrustedData)(`Found ${t.results.length} database users in project ${e}`,JSON.stringify(n))}}}t.ListDBUsersTool=a,a.operationType="read"},12374:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AuthProviderFactory=void 0;const r=n(25182);t.AuthProviderFactory=class{static create(e,t){if(e.credentials.clientId&&e.credentials.clientSecret)return new r.ClientCredentialsAuthProvider({baseUrl:e.apiBaseUrl,userAgent:e.userAgent,clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret},t)}}},12453:e=>{const t=function(e){return e=e.toString(),this instanceof t?(this.ns=e,this.dotIndex=e.indexOf("."),-1===this.dotIndex?(this.database=e,this.collection=""):(this.database=e.slice(0,this.dotIndex),this.collection=e.slice(this.dotIndex+1)),this.system=/^(?:system(?!\.profile$).*|enxcol_)\./.test(this.collection),this.oplog=/local\.oplog\.(\$main|rs)/.test(e),this.command="$cmd"===this.collection||0===this.collection.indexOf("$cmd.sys"),this.special=this.oplog||this.command||this.system||"config"===this.database||/^__mdb_internal_\w/.test(this.database),this.specialish=this.special||["local","admin"].indexOf(this.database)>-1,this.normal=this.oplog||-1===this.ns.indexOf("$"),this.validDatabaseName=new RegExp('^[^\\\\/". ]*$').test(this.database)&&this.database.length<=t.MAX_DATABASE_NAME_LENGTH,this.validCollectionName=this.collection.length>0&&(this.oplog||/^[^\0$]*$/.test(this.collection)),this.databaseHash=7,this.ns.split("").every(((e,t)=>"."!==e&&(this.databaseHash+=11*this.ns.charCodeAt(t),this.databaseHash*=3,!0))),this):new t(e)};t.prototype.database="",t.prototype.databaseHash=0,t.prototype.collection="",t.prototype.command=!1,t.prototype.special=!1,t.prototype.system=!1,t.prototype.oplog=!1,t.prototype.normal=!1,t.prototype.specialish=!1,t.prototype.isCommand=function(){return this.command},t.prototype.isSpecial=function(){return this.special},t.prototype.isSystem=function(){return this.system},t.prototype.isNormal=function(){return this.normal},t.prototype.isOplog=function(){return this.oplog},t.prototype.isConf=function(){},t.prototype.toString=function(){return this.ns},t.MAX_DATABASE_NAME_LENGTH=128,t.sort=function(e){return e.sort((function(e,n){return new t(e).specialish&&new t(n).specialish?0:new t(e).specialish&&!new t(n).specialish?1:!new t(e).specialish&&new t(n).specialish?-1:e>n?1:-1})),e},e.exports=t},12664:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getDeviceId=function({getMachineId:e,onError:t,timeout:n=3e3,abortSignal:r,fallbackValue:o="unknown"}){let a;return Promise.race([i({getMachineId:e,onError:t}),new Promise((e=>{r?.addEventListener("abort",(()=>{t?.("abort",new Error("Aborted by abort signal")),e(o)})),a=setTimeout((()=>{t?.("timeout",new Error(`Timeout reached after ${n} ms`)),e(o)}),n).unref?.()}))]).finally((()=>clearTimeout(a)))};const r=n(27348);async function i({getMachineId:e,onError:t}){try{const n=(await e())?.toUpperCase();if(!n)return t?.("resolutionError",new Error("Failed to resolve machine ID")),"unknown";const i=(0,r.createHmac)("sha256",n),o="atlascli";return i.update(o),i.digest("hex")}catch(e){return t?.("resolutionError",e),"unknown"}}},12798:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(16428);r.code='require("ajv/dist/runtime/equal").default',t.default=r},12856:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getEmbeddingsProvider=function(e){if(s.isConfiguredIn(e))return new s(e)};const r=n(25982),i=n(6577),o=n(79587),a=n(70685);class s{constructor({voyageApiKey:e},t){if(!e)throw new Error("The VoyageAI API Key does not exist. This is likely a bug.");const n=t??(0,o.createFetch)({useEnvironmentVariableProxies:!0});this.voyage=(0,r.createVoyage)({apiKey:e,fetch:n})}static isConfiguredIn({voyageApiKey:e,previewFeatures:t}){return t.includes("search")&&!!e}async embed(e,t,n){const r=a.zVoyageAPIParameters.parse(n),o=this.voyage.textEmbeddingModel(e),{embeddings:s}=await(0,i.embedMany)({model:o,values:t,providerOptions:{voyage:r}});return s}}},13511:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RenameCollectionTool=void 0;const r=n(69761),i=n(58203);class o extends i.MongoDBToolBase{constructor(){super(...arguments),this.name="rename-collection",this.description="Renames a collection in a MongoDB database",this.argsShape={...i.DbOperationArgs,newName:r.z.string().describe("The new name for the collection"),dropTarget:r.z.boolean().optional().default(!1).describe("If true, drops the target collection if it exists")}}async execute({database:e,collection:t,newName:n,dropTarget:r}){const i=await this.ensureConnected();return{content:[{text:`Collection "${t}" renamed to "${(await i.renameCollection(e,t,n,{dropTarget:r})).collectionName}" in database "${e}".`,type:"text"}]}}handleError(e,t){if(e instanceof Error&&"codeName"in e)switch(e.codeName){case"NamespaceNotFound":return{content:[{text:`Cannot rename "${t.database}.${t.collection}" because it doesn't exist.`,type:"text"}],isError:!0};case"NamespaceExists":return{content:[{text:`Cannot rename "${t.database}.${t.collection}" to "${t.newName}" because the target collection already exists. If you want to overwrite it, set the "dropTarget" argument to true.`,type:"text"}],isError:!0}}return super.handleError(e,t)}}t.RenameCollectionTool=o,o.operationType="update"},14012:e=>{function t(e,t){if(!e)throw new Error(t||"Assertion failed")}e.exports=t,t.equal=function(e,t,n){if(e!=t)throw new Error(n||"Assertion failed: "+e+" != "+t)}},14052:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CommaAndColonSeparatedRecord=t.ConnectionString=t.redactConnectionString=void 0;const r=n(9606),i=n(14811);Object.defineProperty(t,"redactConnectionString",{enumerable:!0,get:function(){return i.redactConnectionString}});const o="__this_is_a_placeholder__",a=/^(?<protocol>[^/]+):\/\/(?:(?<username>[^:@]*)(?::(?<password>[^@]*))?@)?(?<hosts>(?!:)[^/?@]*)(?<rest>.*)/;class s extends Map{delete(e){return super.delete(this._normalizeKey(e))}get(e){return super.get(this._normalizeKey(e))}has(e){return super.has(this._normalizeKey(e))}set(e,t){return super.set(this._normalizeKey(e),t)}_normalizeKey(e){e=`${e}`;for(const t of this.keys())if(t.toLowerCase()===e.toLowerCase()){e=t;break}return e}}class c extends r.URL{}class u extends Error{get name(){return"MongoParseError"}}class l extends c{constructor(e,t={}){var n;const{looseValidation:r}=t;if(!r&&!(i=e).startsWith("mongodb://")&&!i.startsWith("mongodb+srv://"))throw new u('Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"');var i;const c=e.match(a);if(!c)throw new u(`Invalid connection string "${e}"`);const{protocol:h,username:f,password:d,hosts:g,rest:p}=null!==(n=c.groups)&&void 0!==n?n:{};if(!r){if(!h||!g)throw new u(`Protocol and host list are required in "${e}"`);try{decodeURIComponent(null!=f?f:""),decodeURIComponent(null!=d?d:"")}catch(e){throw new u(e.message)}const t=/[:/?#[\]@]/gi;if(null==f?void 0:f.match(t))throw new u(`Username contains unescaped characters ${f}`);if(!f||!d){const t=e.replace(`${h}://`,"");if(t.startsWith("@")||t.startsWith(":"))throw new u("URI contained empty userinfo section")}if(null==d?void 0:d.match(t))throw new u("Password contains unescaped characters")}let b="";"string"==typeof f&&(b+=f),"string"==typeof d&&(b+=`:${d}`),b&&(b+="@");try{super(`${h.toLowerCase()}://${b}${o}${p}`)}catch(n){throw r&&new l(e,{...t,looseValidation:!1}),"string"==typeof n.message&&(n.message=n.message.replace(o,g)),n}if(this._hosts=g.split(","),!r){if(this.isSRV&&1!==this.hosts.length)throw new u("mongodb+srv URI cannot have multiple service names");if(this.isSRV&&this.hosts.some((e=>e.includes(":"))))throw new u("mongodb+srv URI cannot have port number")}var m;this.pathname||(this.pathname="/"),Object.setPrototypeOf(this.searchParams,(m=this.searchParams.constructor,class extends m{append(e,t){return super.append(this._normalizeKey(e),t)}delete(e){return super.delete(this._normalizeKey(e))}get(e){return super.get(this._normalizeKey(e))}getAll(e){return super.getAll(this._normalizeKey(e))}has(e){return super.has(this._normalizeKey(e))}set(e,t){return super.set(this._normalizeKey(e),t)}keys(){return super.keys()}values(){return super.values()}entries(){return super.entries()}[Symbol.iterator](){return super[Symbol.iterator]()}_normalizeKey(e){return s.prototype._normalizeKey.call(this,e)}}).prototype)}get host(){return o}set host(e){throw new Error("No single host for connection string")}get hostname(){return o}set hostname(e){throw new Error("No single host for connection string")}get port(){return""}set port(e){throw new Error("No single host for connection string")}get href(){return this.toString()}set href(e){throw new Error("Cannot set href for connection strings")}get isSRV(){return this.protocol.includes("srv")}get hosts(){return this._hosts}set hosts(e){this._hosts=e}toString(){return super.toString().replace(o,this.hosts.join(","))}clone(){return new l(this.toString(),{looseValidation:!0})}redact(e){return(0,i.redactValidConnectionString)(this,e)}typedSearchParams(){return this.searchParams}[Symbol.for("nodejs.util.inspect.custom")](){const{href:e,origin:t,protocol:n,username:r,password:i,hosts:o,pathname:a,search:s,searchParams:c,hash:u}=this;return{href:e,origin:t,protocol:n,username:r,password:i,hosts:o,pathname:a,search:s,searchParams:c,hash:u}}}t.ConnectionString=l,t.CommaAndColonSeparatedRecord=class extends s{constructor(e){super();for(const t of(null!=e?e:"").split(",")){if(!t)continue;const e=t.indexOf(":");-1===e?this.set(t,""):this.set(t.slice(0,e),t.slice(e+1))}}toString(){return[...this].map((e=>e.join(":"))).join(",")}},t.default=l},14233:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AtlasArgs=t.CommonArgs=t.ALLOWED_PROJECT_NAME_CHARACTERS_ERROR=t.ALLOWED_CLUSTER_NAME_CHARACTERS_ERROR=t.ALLOWED_REGION_CHARACTERS_ERROR=t.ALLOWED_USERNAME_CHARACTERS_ERROR=t.NO_UNICODE_ERROR=void 0,t.zEJSON=function(){return r.z.object({}).passthrough().transform(l)};const r=n(69761),i=n(62444),o=/^[\x20-\x7E]*$/;t.NO_UNICODE_ERROR="String cannot contain special characters or Unicode symbols";const a=/^[a-zA-Z0-9._-]+$/;t.ALLOWED_USERNAME_CHARACTERS_ERROR="Username can only contain letters, numbers, dots, hyphens, and underscores";const s=/^[a-zA-Z0-9_-]+$/;t.ALLOWED_REGION_CHARACTERS_ERROR="Region can only contain letters, numbers, hyphens, and underscores";const c=/^[a-zA-Z0-9_-]+$/;t.ALLOWED_CLUSTER_NAME_CHARACTERS_ERROR="Cluster names can only contain ASCII letters, numbers, and hyphens.";const u=/^[a-zA-Z0-9\s()@&+:._',-]+$/;function l(e){return e?i.EJSON.deserialize(e,{relaxed:!1}):e}t.ALLOWED_PROJECT_NAME_CHARACTERS_ERROR="Project names can't be longer than 64 characters and can only contain letters, numbers, spaces, and the following symbols: ( ) @ & + : . _ - ' ,",t.CommonArgs={string:()=>r.z.string().regex(o,t.NO_UNICODE_ERROR),objectId:e=>r.z.string().min(1,`${e} is required`).length(24,`${e} must be exactly 24 characters`).regex(/^[0-9a-fA-F]+$/,`${e} must contain only hexadecimal characters`)},t.AtlasArgs={projectId:()=>t.CommonArgs.objectId("projectId"),organizationId:()=>t.CommonArgs.objectId("organizationId"),clusterName:()=>r.z.string().min(1,"Cluster name is required").max(64,"Cluster name must be 64 characters or less").regex(c,t.ALLOWED_CLUSTER_NAME_CHARACTERS_ERROR),connectionType:()=>r.z.enum(["standard","private","privateEndpoint"]).default("standard"),projectName:()=>r.z.string().min(1,"Project name is required").max(64,"Project name must be 64 characters or less").regex(u,t.ALLOWED_PROJECT_NAME_CHARACTERS_ERROR),username:()=>r.z.string().min(1,"Username is required").max(100,"Username must be 100 characters or less").regex(a,t.ALLOWED_USERNAME_CHARACTERS_ERROR),ipAddress:()=>r.z.string().ip({version:"v4"}),cidrBlock:()=>r.z.string().cidr(),region:()=>r.z.string().min(1,"Region is required").max(50,"Region must be 50 characters or less").regex(s,t.ALLOWED_REGION_CHARACTERS_ERROR),password:()=>r.z.string().min(1,"Password is required").max(100,"Password must be 100 characters or less")}},14811:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.redactConnectionString=t.redactValidConnectionString=void 0;const a=o(n(14052));t.redactValidConnectionString=function(e,t){var n,r;const i=e.clone(),o=null!==(n=null==t?void 0:t.replacementString)&&void 0!==n?n:"_credentials_",s=null===(r=null==t?void 0:t.redactUsernames)||void 0===r||r;if((i.username||i.password)&&s?(i.username=o,i.password=""):i.password&&(i.password=o),i.searchParams.has("authMechanismProperties")){const e=new a.CommaAndColonSeparatedRecord(i.searchParams.get("authMechanismProperties"));e.get("AWS_SESSION_TOKEN")&&(e.set("AWS_SESSION_TOKEN",o),i.searchParams.set("authMechanismProperties",e.toString()))}return i.searchParams.has("tlsCertificateKeyFilePassword")&&i.searchParams.set("tlsCertificateKeyFilePassword",o),i.searchParams.has("proxyUsername")&&s&&i.searchParams.set("proxyUsername",o),i.searchParams.has("proxyPassword")&&i.searchParams.set("proxyPassword",o),i},t.redactConnectionString=function(e,t){var n,r;const i=null!==(n=null==t?void 0:t.replacementString)&&void 0!==n?n:"<credentials>",o=null===(r=null==t?void 0:t.redactUsernames)||void 0===r||r;let s;try{s=new a.default(e)}catch(e){}if(s)return t={...t,replacementString:"___credentials___"},s.redact(t).toString().replace(/___credentials___/g,i);const c=i,u=[e=>e.replace(o?/(\/\/)(.*)(@)/g:/(\/\/[^@]*:)(.*)(@)/g,`$1${c}$3`),e=>e.replace(/(AWS_SESSION_TOKEN(:|%3A))([^,&]+)/gi,`$1${c}`),e=>e.replace(/(tlsCertificateKeyFilePassword=)([^&]+)/gi,`$1${c}`),e=>o?e.replace(/(proxyUsername=)([^&]+)/gi,`$1${c}`):e,e=>e.replace(/(proxyPassword=)([^&]+)/gi,`$1${c}`)];for(const t of u)e=t(e);return e}},16132:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.isZ4Schema=c,t.objectFromShape=u,t.safeParse=function(e,t){return c(e)?s.safeParse(e,t):e.safeParse(t)},t.safeParseAsync=async function(e,t){if(c(e))return await s.safeParseAsync(e,t);const n=e;return await n.safeParseAsync(t)},t.getObjectShape=function(e){if(!e)return;let t;if(c(e)){const n=e;t=n._zod?.def?.shape}else t=e.shape;if(t){if("function"==typeof t)try{return t()}catch{return}return t}},t.normalizeObjectSchema=function(e){if(e){if("object"==typeof e){const t=e;if(!e._def&&!t._zod){const t=Object.values(e);if(t.length>0&&t.every((e=>"object"==typeof e&&null!==e&&(void 0!==e._def||void 0!==e._zod||"function"==typeof e.parse))))return u(e)}}if(c(e)){const t=e,n=t._zod?.def;if(n&&("object"===n.type||void 0!==n.shape))return e}else if(void 0!==e.shape)return e}},t.getParseErrorMessage=function(e){if(e&&"object"==typeof e){if("message"in e&&"string"==typeof e.message)return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){const t=e.issues[0];if(t&&"object"==typeof t&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)},t.getSchemaDescription=function(e){return e.description},t.isSchemaOptional=function(e){if(c(e)){const t=e;return"optional"===t._zod?.def?.type}const t=e;return"function"==typeof e.isOptional?e.isOptional():"ZodOptional"===t._def?.typeName},t.getLiteralValue=function(e){if(c(e)){const t=e,n=t._zod?.def;if(n){if(void 0!==n.value)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}}const t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}const n=e.value;return void 0!==n?n:void 0};const a=o(n(79203)),s=o(n(83890));function c(e){return!!e._zod}function u(e){const t=Object.values(e);if(0===t.length)return s.object({});const n=t.every(c),r=t.every((e=>!c(e)));if(n)return s.object(e);if(r)return a.object(e);throw new Error("Mixed Zod versions detected in object shape.")}},16444:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Server=void 0;const r=n(99764),i=n(17227),o=n(68781),a=n(16132),s=n(99481),c=n(2993);class u extends r.Protocol{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(i.LoggingLevelSchema.options.map(((e,t)=>[e,t]))),this.isMessageIgnored=(e,t)=>{const n=this._loggingLevels.get(t);return!!n&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n)},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new o.AjvJsonSchemaValidator,this.setRequestHandler(i.InitializeRequestSchema,(e=>this._oninitialize(e))),this.setNotificationHandler(i.InitializedNotificationSchema,(()=>this.oninitialized?.())),this._capabilities.logging&&this.setRequestHandler(i.SetLevelRequestSchema,(async(e,t)=>{const n=t.sessionId||t.requestInfo?.headers["mcp-session-id"]||void 0,{level:r}=e.params,o=i.LoggingLevelSchema.safeParse(r);return o.success&&this._loggingLevels.set(n,o.data),{}}))}get experimental(){return this._experimental||(this._experimental={tasks:new s.ExperimentalServerTasks(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=(0,r.mergeCapabilities)(this._capabilities,e)}setRequestHandler(e,t){const n=(0,a.getObjectShape)(e),r=n?.method;if(!r)throw new Error("Schema is missing a method literal");let o;if((0,a.isZ4Schema)(r)){const e=r,t=e._zod?.def;o=t?.value??e.value}else{const e=r,t=e._def;o=t?.value??e.value}if("string"!=typeof o)throw new Error("Schema method literal must be a string");if("tools/call"===o){const n=async(e,n)=>{const r=(0,a.safeParse)(i.CallToolRequestSchema,e);if(!r.success){const e=r.error instanceof Error?r.error.message:String(r.error);throw new i.McpError(i.ErrorCode.InvalidParams,`Invalid tools/call request: ${e}`)}const{params:o}=r.data,s=await Promise.resolve(t(e,n));if(o.task){const e=(0,a.safeParse)(i.CreateTaskResultSchema,s);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new i.McpError(i.ErrorCode.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const c=(0,a.safeParse)(i.CallToolResultSchema,s);if(!c.success){const e=c.error instanceof Error?c.error.message:String(c.error);throw new i.McpError(i.ErrorCode.InvalidParams,`Invalid tools/call result: ${e}`)}return c.data};return super.setRequestHandler(e,n)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);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 ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);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 ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);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 ${e})`)}}assertTaskCapability(e){(0,c.assertClientRequestTaskCapability)(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&(0,c.assertToolsCallTaskCapability)(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:i.SUPPORTED_PROTOCOL_VERSIONS.includes(t)?t:i.LATEST_PROTOCOL_VERSION,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"},i.EmptyResultSchema)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some((e=>"tool_result"===e.type)),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,o=i?Array.isArray(i.content)?i.content:[i.content]:[],a=o.some((e=>"tool_use"===e.type));if(r){if(n.some((e=>"tool_result"!==e.type)))throw new Error("The last message must contain only tool_result content if any is present");if(!a)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){const e=new Set(o.filter((e=>"tool_use"===e.type)).map((e=>e.id))),t=new Set(n.filter((e=>"tool_result"===e.type)).map((e=>e.toolUseId)));if(e.size!==t.size||![...e].every((e=>t.has(e))))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},i.CreateMessageResultWithToolsSchema,t):this.request({method:"sampling/createMessage",params:e},i.CreateMessageResultSchema,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const n=e;return this.request({method:"elicitation/create",params:n},i.ElicitResultSchema,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const n="form"===e.mode?e:{...e,mode:"form"},r=await this.request({method:"elicitation/create",params:n},i.ElicitResultSchema,t);if("accept"===r.action&&r.content&&n.requestedSchema)try{const e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new i.McpError(i.ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof i.McpError)throw e;throw new i.McpError(i.ErrorCode.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},i.ListRootsResultSchema,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}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"})}}t.Server=u},17179:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UpdateManyTool=void 0;const r=n(69761),i=n(58203),o=n(49446),a=n(14233);class s extends i.MongoDBToolBase{constructor(){super(...arguments),this.name="update-many",this.description="Updates all documents that match the specified filter for a collection. If the list of documents is above com.mongodb/maxRequestPayloadBytes, consider updating them in batches.",this.argsShape={...i.DbOperationArgs,filter:(0,a.zEJSON)().optional().describe("The selection criteria for the update, matching the syntax of the filter argument of db.collection.updateOne()"),update:(0,a.zEJSON)().describe("An update document describing the modifications to apply using update operator expressions"),upsert:r.z.boolean().optional().describe("Controls whether to insert a new document if no documents match the filter")}}async execute({database:e,collection:t,filter:n,update:r,upsert:i}){const a=await this.ensureConnected();this.config.indexCheck&&await(0,o.checkIndexUsage)({database:e,collection:t,operation:"updateMany",explainCallback:async()=>a.runCommandWithCheck(e,{explain:{update:t,updates:[{q:n||{},u:r,upsert:i||!1,multi:!0}]},verbosity:"queryPlanner"}),logger:this.session.logger});const s=await a.updateMany(e,t,n,r,{upsert:i});let c="";return 0===s.matchedCount&&0===s.modifiedCount&&0===s.upsertedCount?c="No documents matched the filter.":(c=`Matched ${s.matchedCount} document(s).`,s.modifiedCount>0&&(c+=` Modified ${s.modifiedCount} document(s).`),s.upsertedCount>0&&(c+=` Upserted ${s.upsertedCount} document with id: ${s.upsertedId?.toString()}.`)),{content:[{text:c,type:"text"}]}}}t.UpdateManyTool=s,s.operationType="update"},17227:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressNotificationParamsSchema=t.ProgressSchema=t.PingRequestSchema=t.isInitializedNotification=t.InitializedNotificationSchema=t.InitializeResultSchema=t.ServerCapabilitiesSchema=t.isInitializeRequest=t.InitializeRequestSchema=t.InitializeRequestParamsSchema=t.ClientCapabilitiesSchema=t.ServerTasksCapabilitySchema=t.ClientTasksCapabilitySchema=t.ImplementationSchema=t.BaseMetadataSchema=t.IconsSchema=t.IconSchema=t.CancelledNotificationSchema=t.CancelledNotificationParamsSchema=t.EmptyResultSchema=t.JSONRPCResponseSchema=t.JSONRPCMessageSchema=t.isJSONRPCError=t.isJSONRPCErrorResponse=t.JSONRPCErrorSchema=t.JSONRPCErrorResponseSchema=t.ErrorCode=t.isJSONRPCResponse=t.isJSONRPCResultResponse=t.JSONRPCResultResponseSchema=t.isJSONRPCNotification=t.JSONRPCNotificationSchema=t.isJSONRPCRequest=t.JSONRPCRequestSchema=t.RequestIdSchema=t.ResultSchema=t.NotificationSchema=t.RequestSchema=t.isTaskAugmentedRequestParams=t.TaskAugmentedRequestParamsSchema=t.RelatedTaskMetadataSchema=t.TaskMetadataSchema=t.TaskCreationParamsSchema=t.CursorSchema=t.ProgressTokenSchema=t.JSONRPC_VERSION=t.RELATED_TASK_META_KEY=t.SUPPORTED_PROTOCOL_VERSIONS=t.DEFAULT_NEGOTIATED_PROTOCOL_VERSION=t.LATEST_PROTOCOL_VERSION=void 0,t.EmbeddedResourceSchema=t.ToolUseContentSchema=t.AudioContentSchema=t.ImageContentSchema=t.TextContentSchema=t.GetPromptRequestSchema=t.GetPromptRequestParamsSchema=t.ListPromptsResultSchema=t.ListPromptsRequestSchema=t.PromptSchema=t.PromptArgumentSchema=t.ResourceUpdatedNotificationSchema=t.ResourceUpdatedNotificationParamsSchema=t.UnsubscribeRequestSchema=t.UnsubscribeRequestParamsSchema=t.SubscribeRequestSchema=t.SubscribeRequestParamsSchema=t.ResourceListChangedNotificationSchema=t.ReadResourceResultSchema=t.ReadResourceRequestSchema=t.ReadResourceRequestParamsSchema=t.ResourceRequestParamsSchema=t.ListResourceTemplatesResultSchema=t.ListResourceTemplatesRequestSchema=t.ListResourcesResultSchema=t.ListResourcesRequestSchema=t.ResourceTemplateSchema=t.ResourceSchema=t.AnnotationsSchema=t.RoleSchema=t.BlobResourceContentsSchema=t.TextResourceContentsSchema=t.ResourceContentsSchema=t.CancelTaskResultSchema=t.CancelTaskRequestSchema=t.ListTasksResultSchema=t.ListTasksRequestSchema=t.GetTaskPayloadResultSchema=t.GetTaskPayloadRequestSchema=t.GetTaskResultSchema=t.GetTaskRequestSchema=t.TaskStatusNotificationSchema=t.TaskStatusNotificationParamsSchema=t.CreateTaskResultSchema=t.TaskSchema=t.TaskStatusSchema=t.PaginatedResultSchema=t.PaginatedRequestSchema=t.PaginatedRequestParamsSchema=t.ProgressNotificationSchema=void 0,t.ElicitationCompleteNotificationSchema=t.ElicitationCompleteNotificationParamsSchema=t.ElicitRequestSchema=t.ElicitRequestParamsSchema=t.ElicitRequestURLParamsSchema=t.ElicitRequestFormParamsSchema=t.PrimitiveSchemaDefinitionSchema=t.EnumSchemaSchema=t.MultiSelectEnumSchemaSchema=t.TitledMultiSelectEnumSchemaSchema=t.UntitledMultiSelectEnumSchemaSchema=t.SingleSelectEnumSchemaSchema=t.LegacyTitledEnumSchemaSchema=t.TitledSingleSelectEnumSchemaSchema=t.UntitledSingleSelectEnumSchemaSchema=t.NumberSchemaSchema=t.StringSchemaSchema=t.BooleanSchemaSchema=t.CreateMessageResultWithToolsSchema=t.CreateMessageResultSchema=t.CreateMessageRequestSchema=t.CreateMessageRequestParamsSchema=t.SamplingMessageSchema=t.SamplingMessageContentBlockSchema=t.SamplingContentSchema=t.ToolResultContentSchema=t.ToolChoiceSchema=t.ModelPreferencesSchema=t.ModelHintSchema=t.LoggingMessageNotificationSchema=t.LoggingMessageNotificationParamsSchema=t.SetLevelRequestSchema=t.SetLevelRequestParamsSchema=t.LoggingLevelSchema=t.ListChangedOptionsBaseSchema=t.ToolListChangedNotificationSchema=t.CallToolRequestSchema=t.CallToolRequestParamsSchema=t.CompatibilityCallToolResultSchema=t.CallToolResultSchema=t.ListToolsResultSchema=t.ListToolsRequestSchema=t.ToolSchema=t.ToolExecutionSchema=t.ToolAnnotationsSchema=t.PromptListChangedNotificationSchema=t.GetPromptResultSchema=t.PromptMessageSchema=t.ContentBlockSchema=t.ResourceLinkSchema=void 0,t.UrlElicitationRequiredError=t.McpError=t.ServerResultSchema=t.ServerNotificationSchema=t.ServerRequestSchema=t.ClientResultSchema=t.ClientNotificationSchema=t.ClientRequestSchema=t.RootsListChangedNotificationSchema=t.ListRootsResultSchema=t.ListRootsRequestSchema=t.RootSchema=t.CompleteResultSchema=t.CompleteRequestSchema=t.CompleteRequestParamsSchema=t.PromptReferenceSchema=t.ResourceReferenceSchema=t.ResourceTemplateReferenceSchema=t.ElicitResultSchema=void 0,t.assertCompleteRequestPrompt=function(e){if("ref/prompt"!==e.params.ref.type)throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)},t.assertCompleteRequestResourceTemplate=function(e){if("ref/resource"!==e.params.ref.type)throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)};const a=o(n(19844));t.LATEST_PROTOCOL_VERSION="2025-11-25",t.DEFAULT_NEGOTIATED_PROTOCOL_VERSION="2025-03-26",t.SUPPORTED_PROTOCOL_VERSIONS=[t.LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],t.RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",t.JSONRPC_VERSION="2.0";const s=a.custom((e=>null!==e&&("object"==typeof e||"function"==typeof e)));t.ProgressTokenSchema=a.union([a.string(),a.number().int()]),t.CursorSchema=a.string(),t.TaskCreationParamsSchema=a.looseObject({ttl:a.union([a.number(),a.null()]).optional(),pollInterval:a.number().optional()}),t.TaskMetadataSchema=a.object({ttl:a.number().optional()}),t.RelatedTaskMetadataSchema=a.object({taskId:a.string()});const c=a.looseObject({progressToken:t.ProgressTokenSchema.optional(),[t.RELATED_TASK_META_KEY]:t.RelatedTaskMetadataSchema.optional()}),u=a.object({_meta:c.optional()});t.TaskAugmentedRequestParamsSchema=u.extend({task:t.TaskMetadataSchema.optional()}),t.isTaskAugmentedRequestParams=e=>t.TaskAugmentedRequestParamsSchema.safeParse(e).success,t.RequestSchema=a.object({method:a.string(),params:u.loose().optional()});const l=a.object({_meta:c.optional()});var h;t.NotificationSchema=a.object({method:a.string(),params:l.loose().optional()}),t.ResultSchema=a.looseObject({_meta:c.optional()}),t.RequestIdSchema=a.union([a.string(),a.number().int()]),t.JSONRPCRequestSchema=a.object({jsonrpc:a.literal(t.JSONRPC_VERSION),id:t.RequestIdSchema,...t.RequestSchema.shape}).strict(),t.isJSONRPCRequest=e=>t.JSONRPCRequestSchema.safeParse(e).success,t.JSONRPCNotificationSchema=a.object({jsonrpc:a.literal(t.JSONRPC_VERSION),...t.NotificationSchema.shape}).strict(),t.isJSONRPCNotification=e=>t.JSONRPCNotificationSchema.safeParse(e).success,t.JSONRPCResultResponseSchema=a.object({jsonrpc:a.literal(t.JSONRPC_VERSION),id:t.RequestIdSchema,result:t.ResultSchema}).strict(),t.isJSONRPCResultResponse=e=>t.JSONRPCResultResponseSchema.safeParse(e).success,t.isJSONRPCResponse=t.isJSONRPCResultResponse,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"}(h||(t.ErrorCode=h={})),t.JSONRPCErrorResponseSchema=a.object({jsonrpc:a.literal(t.JSONRPC_VERSION),id:t.RequestIdSchema.optional(),error:a.object({code:a.number().int(),message:a.string(),data:a.unknown().optional()})}).strict(),t.JSONRPCErrorSchema=t.JSONRPCErrorResponseSchema,t.isJSONRPCErrorResponse=e=>t.JSONRPCErrorResponseSchema.safeParse(e).success,t.isJSONRPCError=t.isJSONRPCErrorResponse,t.JSONRPCMessageSchema=a.union([t.JSONRPCRequestSchema,t.JSONRPCNotificationSchema,t.JSONRPCResultResponseSchema,t.JSONRPCErrorResponseSchema]),t.JSONRPCResponseSchema=a.union([t.JSONRPCResultResponseSchema,t.JSONRPCErrorResponseSchema]),t.EmptyResultSchema=t.ResultSchema.strict(),t.CancelledNotificationParamsSchema=l.extend({requestId:t.RequestIdSchema.optional(),reason:a.string().optional()}),t.CancelledNotificationSchema=t.NotificationSchema.extend({method:a.literal("notifications/cancelled"),params:t.CancelledNotificationParamsSchema}),t.IconSchema=a.object({src:a.string(),mimeType:a.string().optional(),sizes:a.array(a.string()).optional(),theme:a.enum(["light","dark"]).optional()}),t.IconsSchema=a.object({icons:a.array(t.IconSchema).optional()}),t.BaseMetadataSchema=a.object({name:a.string(),title:a.string().optional()}),t.ImplementationSchema=t.BaseMetadataSchema.extend({...t.BaseMetadataSchema.shape,...t.IconsSchema.shape,version:a.string(),websiteUrl:a.string().optional(),description:a.string().optional()});const f=a.intersection(a.object({applyDefaults:a.boolean().optional()}),a.record(a.string(),a.unknown())),d=a.preprocess((e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e),a.intersection(a.object({form:f.optional(),url:s.optional()}),a.record(a.string(),a.unknown()).optional()));t.ClientTasksCapabilitySchema=a.looseObject({list:s.optional(),cancel:s.optional(),requests:a.looseObject({sampling:a.looseObject({createMessage:s.optional()}).optional(),elicitation:a.looseObject({create:s.optional()}).optional()}).optional()}),t.ServerTasksCapabilitySchema=a.looseObject({list:s.optional(),cancel:s.optional(),requests:a.looseObject({tools:a.looseObject({call:s.optional()}).optional()}).optional()}),t.ClientCapabilitiesSchema=a.object({experimental:a.record(a.string(),s).optional(),sampling:a.object({context:s.optional(),tools:s.optional()}).optional(),elicitation:d.optional(),roots:a.object({listChanged:a.boolean().optional()}).optional(),tasks:t.ClientTasksCapabilitySchema.optional()}),t.InitializeRequestParamsSchema=u.extend({protocolVersion:a.string(),capabilities:t.ClientCapabilitiesSchema,clientInfo:t.ImplementationSchema}),t.InitializeRequestSchema=t.RequestSchema.extend({method:a.literal("initialize"),params:t.InitializeRequestParamsSchema}),t.isInitializeRequest=e=>t.InitializeRequestSchema.safeParse(e).success,t.ServerCapabilitiesSchema=a.object({experimental:a.record(a.string(),s).optional(),logging:s.optional(),completions:s.optional(),prompts:a.object({listChanged:a.boolean().optional()}).optional(),resources:a.object({subscribe:a.boolean().optional(),listChanged:a.boolean().optional()}).optional(),tools:a.object({listChanged:a.boolean().optional()}).optional(),tasks:t.ServerTasksCapabilitySchema.optional()}),t.InitializeResultSchema=t.ResultSchema.extend({protocolVersion:a.string(),capabilities:t.ServerCapabilitiesSchema,serverInfo:t.ImplementationSchema,instructions:a.string().optional()}),t.InitializedNotificationSchema=t.NotificationSchema.extend({method:a.literal("notifications/initialized"),params:l.optional()}),t.isInitializedNotification=e=>t.InitializedNotificationSchema.safeParse(e).success,t.PingRequestSchema=t.RequestSchema.extend({method:a.literal("ping"),params:u.optional()}),t.ProgressSchema=a.object({progress:a.number(),total:a.optional(a.number()),message:a.optional(a.string())}),t.ProgressNotificationParamsSchema=a.object({...l.shape,...t.ProgressSchema.shape,progressToken:t.ProgressTokenSchema}),t.ProgressNotificationSchema=t.NotificationSchema.extend({method:a.literal("notifications/progress"),params:t.ProgressNotificationParamsSchema}),t.PaginatedRequestParamsSchema=u.extend({cursor:t.CursorSchema.optional()}),t.PaginatedRequestSchema=t.RequestSchema.extend({params:t.PaginatedRequestParamsSchema.optional()}),t.PaginatedResultSchema=t.ResultSchema.extend({nextCursor:t.CursorSchema.optional()}),t.TaskStatusSchema=a.enum(["working","input_required","completed","failed","cancelled"]),t.TaskSchema=a.object({taskId:a.string(),status:t.TaskStatusSchema,ttl:a.union([a.number(),a.null()]),createdAt:a.string(),lastUpdatedAt:a.string(),pollInterval:a.optional(a.number()),statusMessage:a.optional(a.string())}),t.CreateTaskResultSchema=t.ResultSchema.extend({task:t.TaskSchema}),t.TaskStatusNotificationParamsSchema=l.merge(t.TaskSchema),t.TaskStatusNotificationSchema=t.NotificationSchema.extend({method:a.literal("notifications/tasks/status"),params:t.TaskStatusNotificationParamsSchema}),t.GetTaskRequestSchema=t.RequestSchema.extend({method:a.literal("tasks/get"),params:u.extend({taskId:a.string()})}),t.GetTaskResultSchema=t.ResultSchema.merge(t.TaskSchema),t.GetTaskPayloadRequestSchema=t.RequestSchema.extend({method:a.literal("tasks/result"),params:u.extend({taskId:a.string()})}),t.GetTaskPayloadResultSchema=t.ResultSchema.loose(),t.ListTasksRequestSchema=t.PaginatedRequestSchema.extend({method:a.literal("tasks/list")}),t.ListTasksResultSchema=t.PaginatedResultSchema.extend({tasks:a.array(t.TaskSchema)}),t.CancelTaskRequestSchema=t.RequestSchema.extend({method:a.literal("tasks/cancel"),params:u.extend({taskId:a.string()})}),t.CancelTaskResultSchema=t.ResultSchema.merge(t.TaskSchema),t.ResourceContentsSchema=a.object({uri:a.string(),mimeType:a.optional(a.string()),_meta:a.record(a.string(),a.unknown()).optional()}),t.TextResourceContentsSchema=t.ResourceContentsSchema.extend({text:a.string()});const g=a.string().refine((e=>{try{return atob(e),!0}catch{return!1}}),{message:"Invalid Base64 string"});t.BlobResourceContentsSchema=t.ResourceContentsSchema.extend({blob:g}),t.RoleSchema=a.enum(["user","assistant"]),t.AnnotationsSchema=a.object({audience:a.array(t.RoleSchema).optional(),priority:a.number().min(0).max(1).optional(),lastModified:a.iso.datetime({offset:!0}).optional()}),t.ResourceSchema=a.object({...t.BaseMetadataSchema.shape,...t.IconsSchema.shape,uri:a.string(),description:a.optional(a.string()),mimeType:a.optional(a.string()),annotations:t.AnnotationsSchema.optional(),_meta:a.optional(a.looseObject({}))}),t.ResourceTemplateSchema=a.object({...t.BaseMetadataSchema.shape,...t.IconsSchema.shape,uriTemplate:a.string(),description:a.optional(a.string()),mimeType:a.optional(a.string()),annotations:t.AnnotationsSchema.optional(),_meta:a.optional(a.looseObject({}))}),t.ListResourcesRequestSchema=t.PaginatedRequestSchema.extend({method:a.literal("resources/list")}),t.ListResourcesResultSchema=t.PaginatedResultSchema.extend({resources:a.array(t.ResourceSchema)}),t.ListResourceTemplatesRequestSchema=t.PaginatedRequestSchema.extend({method:a.literal("resources/templates/list")}),t.ListResourceTemplatesResultSchema=t.PaginatedResultSchema.extend({resourceTemplates:a.array(t.ResourceTemplateSchema)}),t.ResourceRequestParamsSchema=u.extend({uri:a.string()}),t.ReadResourceRequestParamsSchema=t.ResourceRequestParamsSchema,t.ReadResourceRequestSchema=t.RequestSchema.extend({method:a.literal("resources/read"),params:t.ReadResourceRequestParamsSchema}),t.ReadResourceResultSchema=t.ResultSchema.extend({contents:a.array(a.union([t.TextResourceContentsSchema,t.BlobResourceContentsSchema]))}),t.ResourceListChangedNotificationSchema=t.NotificationSchema.extend({method:a.literal("notifications/resources/list_changed"),params:l.optional()}),t.SubscribeRequestParamsSchema=t.ResourceRequestParamsSchema,t.SubscribeRequestSchema=t.RequestSchema.extend({method:a.literal("resources/subscribe"),params:t.SubscribeRequestParamsSchema}),t.UnsubscribeRequestParamsSchema=t.ResourceRequestParamsSchema,t.UnsubscribeRequestSchema=t.RequestSchema.extend({method:a.literal("resources/unsubscribe"),params:t.UnsubscribeRequestParamsSchema}),t.ResourceUpdatedNotificationParamsSchema=l.extend({uri:a.string()}),t.ResourceUpdatedNotificationSchema=t.NotificationSchema.extend({method:a.literal("notifications/resources/updated"),params:t.ResourceUpdatedNotificationParamsSchema}),t.PromptArgumentSchema=a.object({name:a.string(),description:a.optional(a.string()),required:a.optional(a.boolean())}),t.PromptSchema=a.object({...t.BaseMetadataSchema.shape,...t.IconsSchema.shape,description:a.optional(a.string()),arguments:a.optional(a.array(t.PromptArgumentSchema)),_meta:a.optional(a.looseObject({}))}),t.ListPromptsRequestSchema=t.PaginatedRequestSchema.extend({method:a.literal("prompts/list")}),t.ListPromptsResultSchema=t.PaginatedResultSchema.extend({prompts:a.array(t.PromptSchema)}),t.GetPromptRequestParamsSchema=u.extend({name:a.string(),arguments:a.record(a.string(),a.string()).optional()}),t.GetPromptRequestSchema=t.RequestSchema.extend({method:a.literal("prompts/get"),params:t.GetPromptRequestParamsSchema}),t.TextContentSchema=a.object({type:a.literal("text"),text:a.string(),annotations:t.AnnotationsSchema.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),t.ImageContentSchema=a.object({type:a.literal("image"),data:g,mimeType:a.string(),annotations:t.AnnotationsSchema.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),t.AudioContentSchema=a.object({type:a.literal("audio"),data:g,mimeType:a.string(),annotations:t.AnnotationsSchema.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),t.ToolUseContentSchema=a.object({type:a.literal("tool_use"),name:a.string(),id:a.string(),input:a.record(a.string(),a.unknown()),_meta:a.record(a.string(),a.unknown()).optional()}),t.EmbeddedResourceSchema=a.object({type:a.literal("resource"),resource:a.union([t.TextResourceContentsSchema,t.BlobResourceContentsSchema]),annotations:t.AnnotationsSchema.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),t.ResourceLinkSchema=t.ResourceSchema.extend({type:a.literal("resource_link")}),t.ContentBlockSchema=a.union([t.TextContentSchema,t.ImageContentSchema,t.AudioContentSchema,t.ResourceLinkSchema,t.EmbeddedResourceSchema]),t.PromptMessageSchema=a.object({role:t.RoleSchema,content:t.ContentBlockSchema}),t.GetPromptResultSchema=t.ResultSchema.extend({description:a.string().optional(),messages:a.array(t.PromptMessageSchema)}),t.PromptListChangedNotificationSchema=t.NotificationSchema.extend({method:a.literal("notifications/prompts/list_changed"),params:l.optional()}),t.ToolAnnotationsSchema=a.object({title:a.string().optional(),readOnlyHint:a.boolean().optional(),destructiveHint:a.boolean().optional(),idempotentHint:a.boolean().optional(),openWorldHint:a.boolean().optional()}),t.ToolExecutionSchema=a.object({taskSupport:a.enum(["required","optional","forbidden"]).optional()}),t.ToolSchema=a.object({...t.BaseMetadataSchema.shape,...t.IconsSchema.shape,description:a.string().optional(),inputSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),s).optional(),required:a.array(a.string()).optional()}).catchall(a.unknown()),outputSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),s).optional(),required:a.array(a.string()).optional()}).catchall(a.unknown()).optional(),annotations:t.ToolAnnotationsSchema.optional(),execution:t.ToolExecutionSchema.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),t.ListToolsRequestSchema=t.PaginatedRequestSchema.extend({method:a.literal("tools/list")}),t.ListToolsResultSchema=t.PaginatedResultSchema.extend({tools:a.array(t.ToolSchema)}),t.CallToolResultSchema=t.ResultSchema.extend({content:a.array(t.ContentBlockSchema).default([]),structuredContent:a.record(a.string(),a.unknown()).optional(),isError:a.boolean().optional()}),t.CompatibilityCallToolResultSchema=t.CallToolResultSchema.or(t.ResultSchema.extend({toolResult:a.unknown()})),t.CallToolRequestParamsSchema=t.TaskAugmentedRequestParamsSchema.extend({name:a.string(),arguments:a.record(a.string(),a.unknown()).optional()}),t.CallToolRequestSchema=t.RequestSchema.extend({method:a.literal("tools/call"),params:t.CallToolRequestParamsSchema}),t.ToolListChangedNotificationSchema=t.NotificationSchema.extend({method:a.literal("notifications/tools/list_changed"),params:l.optional()}),t.ListChangedOptionsBaseSchema=a.object({autoRefresh:a.boolean().default(!0),debounceMs:a.number().int().nonnegative().default(300)}),t.LoggingLevelSchema=a.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),t.SetLevelRequestParamsSchema=u.extend({level:t.LoggingLevelSchema}),t.SetLevelRequestSchema=t.RequestSchema.extend({method:a.literal("logging/setLevel"),params:t.SetLevelRequestParamsSchema}),t.LoggingMessageNotificationParamsSchema=l.extend({level:t.LoggingLevelSchema,logger:a.string().optional(),data:a.unknown()}),t.LoggingMessageNotificationSchema=t.NotificationSchema.extend({method:a.literal("notifications/message"),params:t.LoggingMessageNotificationParamsSchema}),t.ModelHintSchema=a.object({name:a.string().optional()}),t.ModelPreferencesSchema=a.object({hints:a.array(t.ModelHintSchema).optional(),costPriority:a.number().min(0).max(1).optional(),speedPriority:a.number().min(0).max(1).optional(),intelligencePriority:a.number().min(0).max(1).optional()}),t.ToolChoiceSchema=a.object({mode:a.enum(["auto","required","none"]).optional()}),t.ToolResultContentSchema=a.object({type:a.literal("tool_result"),toolUseId:a.string().describe("The unique identifier for the corresponding tool call."),content:a.array(t.ContentBlockSchema).default([]),structuredContent:a.object({}).loose().optional(),isError:a.boolean().optional(),_meta:a.record(a.string(),a.unknown()).optional()}),t.SamplingContentSchema=a.discriminatedUnion("type",[t.TextContentSchema,t.ImageContentSchema,t.AudioContentSchema]),t.SamplingMessageContentBlockSchema=a.discriminatedUnion("type",[t.TextContentSchema,t.ImageContentSchema,t.AudioContentSchema,t.ToolUseContentSchema,t.ToolResultContentSchema]),t.SamplingMessageSchema=a.object({role:t.RoleSchema,content:a.union([t.SamplingMessageContentBlockSchema,a.array(t.SamplingMessageContentBlockSchema)]),_meta:a.record(a.string(),a.unknown()).optional()}),t.CreateMessageRequestParamsSchema=t.TaskAugmentedRequestParamsSchema.extend({messages:a.array(t.SamplingMessageSchema),modelPreferences:t.ModelPreferencesSchema.optional(),systemPrompt:a.string().optional(),includeContext:a.enum(["none","thisServer","allServers"]).optional(),temperature:a.number().optional(),maxTokens:a.number().int(),stopSequences:a.array(a.string()).optional(),metadata:s.optional(),tools:a.array(t.ToolSchema).optional(),toolChoice:t.ToolChoiceSchema.optional()}),t.CreateMessageRequestSchema=t.RequestSchema.extend({method:a.literal("sampling/createMessage"),params:t.CreateMessageRequestParamsSchema}),t.CreateMessageResultSchema=t.ResultSchema.extend({model:a.string(),stopReason:a.optional(a.enum(["endTurn","stopSequence","maxTokens"]).or(a.string())),role:t.RoleSchema,content:t.SamplingContentSchema}),t.CreateMessageResultWithToolsSchema=t.ResultSchema.extend({model:a.string(),stopReason:a.optional(a.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(a.string())),role:t.RoleSchema,content:a.union([t.SamplingMessageContentBlockSchema,a.array(t.SamplingMessageContentBlockSchema)])}),t.BooleanSchemaSchema=a.object({type:a.literal("boolean"),title:a.string().optional(),description:a.string().optional(),default:a.boolean().optional()}),t.StringSchemaSchema=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),minLength:a.number().optional(),maxLength:a.number().optional(),format:a.enum(["email","uri","date","date-time"]).optional(),default:a.string().optional()}),t.NumberSchemaSchema=a.object({type:a.enum(["number","integer"]),title:a.string().optional(),description:a.string().optional(),minimum:a.number().optional(),maximum:a.number().optional(),default:a.number().optional()}),t.UntitledSingleSelectEnumSchemaSchema=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),enum:a.array(a.string()),default:a.string().optional()}),t.TitledSingleSelectEnumSchemaSchema=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),oneOf:a.array(a.object({const:a.string(),title:a.string()})),default:a.string().optional()}),t.LegacyTitledEnumSchemaSchema=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),enum:a.array(a.string()),enumNames:a.array(a.string()).optional(),default:a.string().optional()}),t.SingleSelectEnumSchemaSchema=a.union([t.UntitledSingleSelectEnumSchemaSchema,t.TitledSingleSelectEnumSchemaSchema]),t.UntitledMultiSelectEnumSchemaSchema=a.object({type:a.literal("array"),title:a.string().optional(),description:a.string().optional(),minItems:a.number().optional(),maxItems:a.number().optional(),items:a.object({type:a.literal("string"),enum:a.array(a.string())}),default:a.array(a.string()).optional()}),t.TitledMultiSelectEnumSchemaSchema=a.object({type:a.literal("array"),title:a.string().optional(),description:a.string().optional(),minItems:a.number().optional(),maxItems:a.number().optional(),items:a.object({anyOf:a.array(a.object({const:a.string(),title:a.string()}))}),default:a.array(a.string()).optional()}),t.MultiSelectEnumSchemaSchema=a.union([t.UntitledMultiSelectEnumSchemaSchema,t.TitledMultiSelectEnumSchemaSchema]),t.EnumSchemaSchema=a.union([t.LegacyTitledEnumSchemaSchema,t.SingleSelectEnumSchemaSchema,t.MultiSelectEnumSchemaSchema]),t.PrimitiveSchemaDefinitionSchema=a.union([t.EnumSchemaSchema,t.BooleanSchemaSchema,t.StringSchemaSchema,t.NumberSchemaSchema]),t.ElicitRequestFormParamsSchema=t.TaskAugmentedRequestParamsSchema.extend({mode:a.literal("form").optional(),message:a.string(),requestedSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),t.PrimitiveSchemaDefinitionSchema),required:a.array(a.string()).optional()})}),t.ElicitRequestURLParamsSchema=t.TaskAugmentedRequestParamsSchema.extend({mode:a.literal("url"),message:a.string(),elicitationId:a.string(),url:a.string().url()}),t.ElicitRequestParamsSchema=a.union([t.ElicitRequestFormParamsSchema,t.ElicitRequestURLParamsSchema]),t.ElicitRequestSchema=t.RequestSchema.extend({method:a.literal("elicitation/create"),params:t.ElicitRequestParamsSchema}),t.ElicitationCompleteNotificationParamsSchema=l.extend({elicitationId:a.string()}),t.ElicitationCompleteNotificationSchema=t.NotificationSchema.extend({method:a.literal("notifications/elicitation/complete"),params:t.ElicitationCompleteNotificationParamsSchema}),t.ElicitResultSchema=t.ResultSchema.extend({action:a.enum(["accept","decline","cancel"]),content:a.preprocess((e=>null===e?void 0:e),a.record(a.string(),a.union([a.string(),a.number(),a.boolean(),a.array(a.string())])).optional())}),t.ResourceTemplateReferenceSchema=a.object({type:a.literal("ref/resource"),uri:a.string()}),t.ResourceReferenceSchema=t.ResourceTemplateReferenceSchema,t.PromptReferenceSchema=a.object({type:a.literal("ref/prompt"),name:a.string()}),t.CompleteRequestParamsSchema=u.extend({ref:a.union([t.PromptReferenceSchema,t.ResourceTemplateReferenceSchema]),argument:a.object({name:a.string(),value:a.string()}),context:a.object({arguments:a.record(a.string(),a.string()).optional()}).optional()}),t.CompleteRequestSchema=t.RequestSchema.extend({method:a.literal("completion/complete"),params:t.CompleteRequestParamsSchema}),t.CompleteResultSchema=t.ResultSchema.extend({completion:a.looseObject({values:a.array(a.string()).max(100),total:a.optional(a.number().int()),hasMore:a.optional(a.boolean())})}),t.RootSchema=a.object({uri:a.string().startsWith("file://"),name:a.string().optional(),_meta:a.record(a.string(),a.unknown()).optional()}),t.ListRootsRequestSchema=t.RequestSchema.extend({method:a.literal("roots/list"),params:u.optional()}),t.ListRootsResultSchema=t.ResultSchema.extend({roots:a.array(t.RootSchema)}),t.RootsListChangedNotificationSchema=t.NotificationSchema.extend({method:a.literal("notifications/roots/list_changed"),params:l.optional()}),t.ClientRequestSchema=a.union([t.PingRequestSchema,t.InitializeRequestSchema,t.CompleteRequestSchema,t.SetLevelRequestSchema,t.GetPromptRequestSchema,t.ListPromptsRequestSchema,t.ListResourcesRequestSchema,t.ListResourceTemplatesRequestSchema,t.ReadResourceRequestSchema,t.SubscribeRequestSchema,t.UnsubscribeRequestSchema,t.CallToolRequestSchema,t.ListToolsRequestSchema,t.GetTaskRequestSchema,t.GetTaskPayloadRequestSchema,t.ListTasksRequestSchema,t.CancelTaskRequestSchema]),t.ClientNotificationSchema=a.union([t.CancelledNotificationSchema,t.ProgressNotificationSchema,t.InitializedNotificationSchema,t.RootsListChangedNotificationSchema,t.TaskStatusNotificationSchema]),t.ClientResultSchema=a.union([t.EmptyResultSchema,t.CreateMessageResultSchema,t.CreateMessageResultWithToolsSchema,t.ElicitResultSchema,t.ListRootsResultSchema,t.GetTaskResultSchema,t.ListTasksResultSchema,t.CreateTaskResultSchema]),t.ServerRequestSchema=a.union([t.PingRequestSchema,t.CreateMessageRequestSchema,t.ElicitRequestSchema,t.ListRootsRequestSchema,t.GetTaskRequestSchema,t.GetTaskPayloadRequestSchema,t.ListTasksRequestSchema,t.CancelTaskRequestSchema]),t.ServerNotificationSchema=a.union([t.CancelledNotificationSchema,t.ProgressNotificationSchema,t.LoggingMessageNotificationSchema,t.ResourceUpdatedNotificationSchema,t.ResourceListChangedNotificationSchema,t.ToolListChangedNotificationSchema,t.PromptListChangedNotificationSchema,t.TaskStatusNotificationSchema,t.ElicitationCompleteNotificationSchema]),t.ServerResultSchema=a.union([t.EmptyResultSchema,t.InitializeResultSchema,t.CompleteResultSchema,t.GetPromptResultSchema,t.ListPromptsResultSchema,t.ListResourcesResultSchema,t.ListResourceTemplatesResultSchema,t.ReadResourceResultSchema,t.CallToolResultSchema,t.ListToolsResultSchema,t.GetTaskResultSchema,t.ListTasksResultSchema,t.CreateTaskResultSchema]);class p extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===h.UrlElicitationRequired&&n){const e=n;if(e.elicitations)return new b(e.elicitations,t)}return new p(e,t,n)}}t.McpError=p;class b extends p{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(h.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}t.UrlElicitationRequiredError=b},17260:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class n{}t._CodeOrName=n,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends n{constructor(e){if(super(),!t.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class i extends n{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce(((e,t)=>`${e}${t}`),"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce(((e,t)=>(t instanceof r&&(e[t.str]=(e[t.str]||0)+1),e)),{})}}function o(e,...t){const n=[e[0]];let r=0;for(;r<t.length;)c(n,t[r]),n.push(e[++r]);return new i(n)}t._Code=i,t.nil=new i(""),t._=o;const a=new i("+");function s(e,...t){const n=[l(e[0])];let r=0;for(;r<t.length;)n.push(a),c(n,t[r]),n.push(a,l(e[++r]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===a){const n=u(e[t-1],e[t+1]);if(void 0!==n){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}(n),new i(n)}function c(e,t){var n;t instanceof i?e.push(...t._items):t instanceof r?e.push(t):e.push("number"==typeof(n=t)||"boolean"==typeof n||null===n?n:l(Array.isArray(n)?n.join(","):n))}function u(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof r||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof r?void 0:`"${e}${t.slice(1)}`}function l(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.str=s,t.addCodeArg=c,t.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:s`${e}${t}`},t.stringify=function(e){return new i(l(e))},t.safeStringify=l,t.getProperty=function(e){return"string"==typeof e&&t.IDENTIFIER.test(e)?new i(`.${e}`):o`[${e}]`},t.getEsmExportName=function(e){if("string"==typeof e&&t.IDENTIFIER.test(e))return new i(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)},t.regexpCode=function(e){return new i(e.toString())}},17846:(e,t)=>{var n=t;function r(e){return 1===e.length?"0"+e:e}function i(e){for(var t="",n=0;n<e.length;n++)t+=r(e[n].toString(16));return t}n.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var n=[];if("string"!=typeof e){for(var r=0;r<e.length;r++)n[r]=0|e[r];return n}if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),r=0;r<e.length;r+=2)n.push(parseInt(e[r]+e[r+1],16));else for(r=0;r<e.length;r++){var i=e.charCodeAt(r),o=i>>8,a=255&i;o?n.push(o,a):n.push(a)}return n},n.zero2=r,n.toHex=i,n.encode=function(e,t){return"hex"===t?i(e):e}},17851:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MongoLogManager=void 0;const i=r(n(17642)),o=n(62444),a=n(8763),s=n(36374),c=n(25900),u=n(93974),l=n(97557),h=n(93874);t.MongoLogManager=class{constructor(e){if(e.prefix&&!/^[a-z0-9_]+$/i.test(e.prefix))throw new Error("Prefix must only contain letters, numbers, and underscores");this._options=e}async deleteFile(e){try{await s.promises.unlink(e)}catch(t){"ENOENT"!==t?.code&&this._options.onerror(t,e)}}get prefix(){return this._options.prefix??""}async cleanupOldLogFiles(e=5e3,t=1){const n=Date.now(),r=n-86400*this._options.retentionDays*1e3,a=this._options.directory;let c;try{c=await s.promises.opendir(a)}catch{return}const l=new u.Heap(((e,t)=>e.fileTimestamp-t.fileTimestamp)),h=!!this._options.retentionGB&&isFinite(this._options.retentionGB),f=!!this._options.maxLogFileCount&&isFinite(this._options.maxLogFileCount);let d=h?0:-1/0;try{for await(const t of c){if(Date.now()-n>e)break;if(!t.isFile())continue;const c=new RegExp(`^${this.prefix}(?<id>[a-f0-9]{24})_log(\\.gz)?$`,"i"),{id:u}=c.exec(t.name)?.groups??{};if(!u)continue;const g=+new o.ObjectId(u).getTimestamp(),p=i.default.join(a,t.name);if(g<r){await this.deleteFile(p);continue}let b;if(h)try{b=(await s.promises.stat(p)).size,d+=b}catch(e){this._options.onerror(e,p);continue}if((f||h)&&l.push({fullPath:p,fileTimestamp:g,fileSize:b}),f&&this._options.maxLogFileCount&&l.size()>this._options.maxLogFileCount){const e=l.pop();if(!e)continue;await this.deleteFile(e.fullPath),d-=e.fileSize??0}}}catch(r){"ENOENT"===r.code&&t>0&&await this.cleanupOldLogFiles(e-(Date.now()-n),t-1)}if(h&&this._options.retentionGB){const t=1024*this._options.retentionGB*1024*1024;for(const r of l){if(Date.now()-n>e)break;if(d<=t)break;r.fileSize&&(await this.deleteFile(r.fullPath),d-=r.fileSize)}}}async createLogWriter(){const e=(new o.ObjectId).toString(),t=!!this._options.gzip,n=i.default.join(this._options.directory,`${this.prefix}${e}_log${t?".gz":""}`);let r,u,f;try{u=(0,s.createWriteStream)(n,{mode:384}),r=u,await(0,a.once)(u,"ready"),t?(u=(0,c.createGzip)({flush:c.constants.Z_SYNC_FLUSH,level:c.constants.Z_MAX_LEVEL}),u.pipe(r)):u.on("finish",(()=>u.emit("log-finish")))}catch(t){this._options.onwarn(t,n),u=new h.Writable({write(e,t,n){n()}}),r=u,f=new l.MongoLogWriter(e,null,u)}return f||(f=new l.MongoLogWriter(e,n,u)),r.on("finish",(()=>f?.emit("log-finish"))),f}}},18253:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CURSOR_LIMITS_TO_LLM_TEXT=t.ONE_MB=t.AGG_COUNT_MAX_TIME_MS_CAP=t.QUERY_COUNT_MAX_TIME_MS_CAP=void 0,t.QUERY_COUNT_MAX_TIME_MS_CAP=1e4,t.AGG_COUNT_MAX_TIME_MS_CAP=6e4,t.ONE_MB=1048576,t.CURSOR_LIMITS_TO_LLM_TEXT={"config.maxDocumentsPerQuery":"server's configured - maxDocumentsPerQuery","config.maxBytesPerQuery":"server's configured - maxBytesPerQuery","tool.responseBytesLimit":"tool's parameter - responseBytesLimit"}},18262:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.similarityValues=t.previewFeatureValues=void 0,t.previewFeatureValues=["search","mcpUI"],t.similarityValues=["cosine","euclidean","dotProduct"]},18620:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(47595),i=n(2337),o=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",r.default,i.default];t.default=o},18758:(e,t,n)=>{n.d(t,{oW:()=>i});var r=n(91174);r.MongoLogManager,r.MongoLogWriter;const i=r.mongoLogId},20530:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SECRET_KIND=void 0,t.redactSecretsOnString=function(e,n){let r=e;for(const{value:e,kind:o}of n){if(!t.SECRET_KIND.includes(o))throw new Error(`Unknown secret kind ${o}. Valid types: ${t.SECRET_KIND.join(", ")}`);const n=(0,i.default)(e),a=new RegExp(`(?<!\\w)${n}(?!\\w)`,"g");r=r.replace(a,`<${o}>`)}return r};const i=r(n(26140));t.SECRET_KIND=["base64","private key","user","password","email","ip","url","mongodb uri"]},20644:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ExportTool=void 0;const i=r(n(69761)),o=n(62444),a=n(58203),s=n(32665),c=n(35902),u=n(43443);class l extends a.MongoDBToolBase{constructor(){super(...arguments),this.name="export",this.description="Export a query or aggregation results in the specified EJSON format.",this.argsShape={...a.DbOperationArgs,exportTitle:i.default.string().describe("A short description to uniquely identify the export."),exportTarget:i.default.array(i.default.discriminatedUnion("name",[i.default.object({name:i.default.literal("find").describe("The literal name 'find' to represent a find cursor as target."),arguments:i.default.object({...s.FindArgs,limit:s.FindArgs.limit.removeDefault()}).describe("The arguments for 'find' operation.")}),i.default.object({name:i.default.literal("aggregate").describe("The literal name 'aggregate' to represent an aggregation cursor as target."),arguments:i.default.object((0,u.getAggregateArgs)(this.isFeatureEnabled("search"))).describe("The arguments for 'aggregate' operation.")})])).describe("The export target along with its arguments."),jsonExportFormat:c.jsonExportFormat.default("relaxed").describe(["The format to be used when exporting collection data as EJSON with default being relaxed.","relaxed: A string format that emphasizes readability and interoperability at the expense of type preservation. That is, conversion from relaxed format to BSON can lose type information.","canonical: A string format that emphasizes type preservation at the expense of readability and interoperability. That is, conversion from canonical to BSON will generally preserve type information except in certain specific cases."].join("\n"))}}async execute({database:e,collection:t,jsonExportFormat:n,exportTitle:r,exportTarget:i},{signal:a}){const s=await this.ensureConnected(),c=i[0];if(!c)throw new Error("Export target not provided. Expected one of the following: `aggregate`, `find`");let u;if("find"===c.name){const{filter:n,projection:r,sort:i,limit:o}=c.arguments;u=s.find(e,t,n??{},{projection:r,sort:i,limit:o,promoteValues:!1,bsonRegExp:!0,signal:a})}else{const{pipeline:n}=c.arguments;u=s.aggregate(e,t,n,{promoteValues:!1,bsonRegExp:!0,allowDiskUse:!0,signal:a})}const l=`${(new o.ObjectId).toString()}.json`,{exportURI:h,exportPath:f}=await this.session.exportsManager.createJSONExport({input:u,exportName:l,exportTitle:r||`Export for namespace ${e}.${t} requested on ${(new Date).toLocaleString()}`,jsonExportFormat:n}),d=[{type:"text",text:`Data for namespace ${e}.${t} is being exported and will be made available under resource URI - "${h}".`},{type:"resource_link",name:l,uri:h,description:"Resource URI for fetching exported data once it is ready.",mimeType:"application/json"}];return this.isServerRunningLocally()&&d.push({type:"text",text:`Optionally, when the export is finished, the exported data can also be accessed under path - "${f}"`}),{content:d}}isServerRunningLocally(){return"stdio"===this.config.transport||["127.0.0.1","localhost"].includes(this.config.httpHost)}}t.ExportTool=l,l.operationType="read"},20692:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reportTypeError=t.checkDataTypes=t.checkDataType=t.coerceAndCheckDataType=t.getJSONTypes=t.getSchemaTypes=t.DataType=void 0;const r=n(91784),i=n(63155),o=n(7280),a=n(78249),s=n(87351);var c;function u(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(r.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(c||(t.DataType=c={})),t.getSchemaTypes=function(e){const t=u(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},t.getJSONTypes=u,t.coerceAndCheckDataType=function(e,t){const{gen:n,data:r,opts:o}=e,s=function(e,t){return t?e.filter((e=>l.has(e)||"array"===t&&"array"===e)):[]}(t,o.coerceTypes),u=t.length>0&&!(0===s.length&&1===t.length&&(0,i.schemaHasRulesForType)(e,t[0]));if(u){const i=f(t,r,o.strictNumbers,c.Wrong);n.if(i,(()=>{s.length?function(e,t,n){const{gen:r,data:i,opts:o}=e,s=r.let("dataType",a._`typeof ${i}`),c=r.let("coerced",a._`undefined`);"array"===o.coerceTypes&&r.if(a._`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,(()=>r.assign(i,a._`${i}[0]`).assign(s,a._`typeof ${i}`).if(f(t,i,o.strictNumbers),(()=>r.assign(c,i))))),r.if(a._`${c} !== undefined`);for(const e of n)(l.has(e)||"array"===e&&"array"===o.coerceTypes)&&u(e);function u(e){switch(e){case"string":return void r.elseIf(a._`${s} == "number" || ${s} == "boolean"`).assign(c,a._`"" + ${i}`).elseIf(a._`${i} === null`).assign(c,a._`""`);case"number":return void r.elseIf(a._`${s} == "boolean" || ${i} === null
3
3
  || (${s} == "string" && ${i} && ${i} == +${i})`).assign(c,a._`+${i}`);case"integer":return void r.elseIf(a._`${s} === "boolean" || ${i} === null
4
4
  || (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(c,a._`+${i}`);case"boolean":return void r.elseIf(a._`${i} === "false" || ${i} === 0 || ${i} === null`).assign(c,!1).elseIf(a._`${i} === "true" || ${i} === 1`).assign(c,!0);case"null":return r.elseIf(a._`${i} === "" || ${i} === 0 || ${i} === false`),void r.assign(c,null);case"array":r.elseIf(a._`${s} === "string" || ${s} === "number"
5
- || ${s} === "boolean" || ${i} === null`).assign(c,a._`[${i}]`)}}r.else(),g(e),r.endIf(),r.if(a._`${c} !== undefined`,(()=>{r.assign(i,c),function({gen:e,parentData:t,parentDataProperty:n},r){e.if(a._`${t} !== undefined`,(()=>e.assign(a._`${t}[${n}]`,r)))}(e,c)}))}(e,t,s):g(e)}))}return u};const l=new Set(["string","number","integer","boolean","null"]);function h(e,t,n,r=c.Correct){const i=r===c.Correct?a.operators.EQ:a.operators.NEQ;let o;switch(e){case"null":return a._`${t} ${i} null`;case"array":o=a._`Array.isArray(${t})`;break;case"object":o=a._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=s(a._`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=s();break;default:return a._`typeof ${t} ${i} ${e}`}return r===c.Correct?o:(0,a.not)(o);function s(e=a.nil){return(0,a.and)(a._`typeof ${t} == "number"`,e,n?a._`isFinite(${t})`:a.nil)}}function f(e,t,n,r){if(1===e.length)return h(e[0],t,n,r);let i;const o=(0,s.toHash)(e);if(o.array&&o.object){const e=a._`typeof ${t} != "object"`;i=o.null?e:a._`!${t} || ${e}`,delete o.null,delete o.array,delete o.object}else i=a.nil;o.number&&delete o.integer;for(const e in o)i=(0,a.and)(i,h(e,t,n,r));return i}t.checkDataType=h,t.checkDataTypes=f;const d={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?a._`{type: ${e}}`:a._`{type: ${t}}`};function g(e){const t=function(e){const{gen:t,data:n,schema:r}=e,i=(0,s.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}(e);(0,o.reportError)(t,d)}t.reportTypeError=g},20999:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getDefaultRoleFromConfig=function(e){return e.readOnly||e.disabledTools.includes("create")&&e.disabledTools.includes("update")&&e.disabledTools.includes("delete")?r:n};const n={roleName:"readWriteAnyDatabase",databaseName:"admin"},r={roleName:"readAnyDatabase",databaseName:"admin"}},21247:function(e,t,n){var r=n(65994).process,i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.detectContainerEnv=async function(){return void 0!==a||(a=await async function(){return"linux"===r.platform&&(!!r.env.container||(await Promise.all(["/.dockerenv","/run/.containerenv","/var/run/.containerenv"].map((async e=>{try{return await o.default.access(e),!0}catch{return!1}})))).includes(!0))}()),a};const o=i(n(65981));let a},21511:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(78249),i={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxItems"===e?"more":"fewer";return r.str`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>r._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:i}=e,o="maxItems"===t?r.operators.GT:r.operators.LT;e.fail$data(r._`${n}.length ${o} ${i}`)}};t.default=i},21570:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CollectionSchemaTool=void 0;const i=n(58203),o=n(77710),a=n(33168),s=r(n(69761)),c=n(18253),u=n(92639),l=n(33532);class h extends i.MongoDBToolBase{constructor(){super(...arguments),this.name="collection-schema",this.description="Describe the schema for a collection",this.argsShape={...i.DbOperationArgs,sampleSize:s.default.number().optional().default(50).describe("Number of documents to sample for schema inference"),responseBytesLimit:s.default.number().optional().default(c.ONE_MB).describe("The maximum number of bytes to return in the response. This value is capped by the server's configured maxBytesPerQuery and cannot be exceeded.")}}async execute({database:e,collection:t,sampleSize:n,responseBytesLimit:r},{signal:i}){const s=(await this.ensureConnected()).aggregate(e,t,[{$sample:{size:Math.min(n,5e4)}}],{signal:i}),{cappedBy:c,documents:h}=await(0,u.collectCursorUntilMaxBytesLimit)({cursor:s,configuredMaxBytesPerQuery:this.config.maxBytesPerQuery,toolResponseBytesLimit:r,abortSignal:i}),f=await(0,a.getSimplifiedSchema)(h);if((0,l.isObjectEmpty)(f))return{content:[{text:`Could not deduce the schema for "${e}.${t}". This may be because it doesn't exist or is empty.`,type:"text"}]};const d=`Found ${Object.keys(f).length} fields in the schema for "${e}.${t}"`,g=void 0!==c?`\nThe schema was inferred from a subset of documents due to the response size limit. (${c})`:"";return{content:(0,o.formatUntrustedData)(`${d}${g}`,JSON.stringify(f))}}}t.CollectionSchemaTool=h,h.operationType="metadata"},22010:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UriTemplate=void 0;const n=1e6,r=1e6;class i{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,n){if(e.length>t)throw new Error(`${n} exceeds maximum length of ${t} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap((e=>"string"==typeof e?[]:e.names))}constructor(e){i.validateLength(e,n,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){const t=[];let n="",o=0,a=0;for(;o<e.length;)if("{"===e[o]){n&&(t.push(n),n="");const s=e.indexOf("}",o);if(-1===s)throw new Error("Unclosed template expression");if(a++,a>1e4)throw new Error("Template contains too many expressions (max 10000)");const c=e.slice(o+1,s),u=this.getOperator(c),l=c.includes("*"),h=this.getNames(c),f=h[0];for(const e of h)i.validateLength(e,r,"Variable name");t.push({name:f,operator:u,names:h,exploded:l}),o=s+1}else n+=e[o],o++;return n&&t.push(n),t}getOperator(e){return["+","#",".","/","?","&"].find((t=>e.startsWith(t)))||""}getNames(e){const t=this.getOperator(e);return e.slice(t.length).split(",").map((e=>e.replace("*","").trim())).filter((e=>e.length>0))}encodeValue(e,t){return i.validateLength(e,r,"Variable value"),"+"===t||"#"===t?encodeURI(e):encodeURIComponent(e)}expandPart(e,t){if("?"===e.operator||"&"===e.operator){const n=e.names.map((n=>{const r=t[n];return void 0===r?"":`${n}=${Array.isArray(r)?r.map((t=>this.encodeValue(t,e.operator))).join(","):this.encodeValue(r.toString(),e.operator)}`})).filter((e=>e.length>0));return 0===n.length?"":("?"===e.operator?"?":"&")+n.join("&")}if(e.names.length>1){const n=e.names.map((e=>t[e])).filter((e=>void 0!==e));return 0===n.length?"":n.map((e=>Array.isArray(e)?e[0]:e)).join(",")}const n=t[e.name];if(void 0===n)return"";const r=(Array.isArray(n)?n:[n]).map((t=>this.encodeValue(t,e.operator)));switch(e.operator){case"":case"+":default:return r.join(",");case"#":return"#"+r.join(",");case".":return"."+r.join(".");case"/":return"/"+r.join("/")}}expand(e){let t="",n=!1;for(const r of this.parts){if("string"==typeof r){t+=r;continue}const i=this.expandPart(r,e);i&&("?"!==r.operator&&"&"!==r.operator||!n?t+=i:t+=i.replace("?","&"),"?"!==r.operator&&"&"!==r.operator||(n=!0))}return t}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){const t=[];for(const t of e.names)i.validateLength(t,r,"Variable name");if("?"===e.operator||"&"===e.operator){for(let n=0;n<e.names.length;n++){const r=e.names[n],i=0===n?"\\"+e.operator:"&";t.push({pattern:i+this.escapeRegExp(r)+"=([^&]+)",name:r})}return t}let n;const o=e.name;switch(e.operator){case"":n=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return t.push({pattern:n,name:o}),t}match(e){i.validateLength(e,n,"URI");let t="^";const r=[];for(const e of this.parts)if("string"==typeof e)t+=this.escapeRegExp(e);else{const n=this.partToRegExp(e);for(const{pattern:i,name:o}of n)t+=i,r.push({name:o,exploded:e.exploded})}t+="$",i.validateLength(t,1e6,"Generated regex pattern");const o=new RegExp(t),a=e.match(o);if(!a)return null;const s={};for(let e=0;e<r.length;e++){const{name:t,exploded:n}=r[e],i=a[e+1],o=t.replace("*","");n&&i.includes(",")?s[o]=i.split(","):s[o]=i}return s}}t.UriTemplate=i},22384:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRandomUUID=function(){try{return n(27348).randomUUID()}catch{return"undefined"!=typeof globalThis&&globalThis.crypto&&"function"==typeof globalThis.crypto.randomUUID?globalThis.crypto.randomUUID():(new r.UUID).toString()}};const r=n(62444)},22880:(e,t,n)=>{var r=n(65994).process;Object.defineProperty(t,"__esModule",{value:!0}),t.LRUCache=void 0;const i="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,o=new Set,a="object"==typeof r&&r?r:{},s=(e,t,n,r)=>{"function"==typeof a.emitWarning?a.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)};let c=globalThis.AbortController,u=globalThis.AbortSignal;if(void 0===c){u=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},c=class{constructor(){t()}signal=new u;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==a.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,s("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}Symbol("type");const l=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),h=e=>l(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?f:null:null;class f extends Array{constructor(e){super(e),this.fill(0)}}class d{heap;length;static#e=!1;static create(e){const t=h(e);if(!t)return[];d.#e=!0;const n=new d(e,t);return d.#e=!1,n}constructor(e,t){if(!d.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class g{#t;#n;#r;#i;#o;#a;#s;#c;get perf(){return this.#c}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#u;#l;#h;#f;#d;#g;#p;#b;#m;#w;#v;#y;#S;#k;#E;#x;#M;#T;#C;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#k,autopurgeTimers:e.#E,sizes:e.#y,keyMap:e.#h,keyList:e.#f,valList:e.#d,next:e.#g,prev:e.#p,get head(){return e.#b},get tail(){return e.#m},free:e.#w,isBackgroundFetch:t=>e.#_(t),backgroundFetch:(t,n,r,i)=>e.#P(t,n,r,i),moveToTail:t=>e.#I(t),indexes:t=>e.#A(t),rindexes:t=>e.#O(t),isStale:t=>e.#j(t)}}get max(){return this.#t}get maxSize(){return this.#n}get calculatedSize(){return this.#l}get size(){return this.#u}get fetchMethod(){return this.#a}get memoMethod(){return this.#s}get dispose(){return this.#r}get onInsert(){return this.#i}get disposeAfter(){return this.#o}constructor(e){const{max:t=0,ttl:n,ttlResolution:r=1,ttlAutopurge:a,updateAgeOnGet:c,updateAgeOnHas:u,allowStale:f,dispose:p,onInsert:b,disposeAfter:m,noDisposeOnSet:w,noUpdateTTL:v,maxSize:y=0,maxEntrySize:S=0,sizeCalculation:k,fetchMethod:E,memoMethod:x,noDeleteOnFetchRejection:M,noDeleteOnStaleGet:T,allowStaleOnFetchRejection:C,allowStaleOnFetchAbort:_,ignoreFetchAbort:P,perf:I}=e;if(void 0!==I&&"function"!=typeof I?.now)throw new TypeError("perf option must have a now() method if specified");if(this.#c=I??i,0!==t&&!l(t))throw new TypeError("max option must be a nonnegative integer");const A=t?h(t):Array;if(!A)throw new Error("invalid max value: "+t);if(this.#t=t,this.#n=y,this.maxEntrySize=S||this.#n,this.sizeCalculation=k,this.sizeCalculation){if(!this.#n&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==x&&"function"!=typeof x)throw new TypeError("memoMethod must be a function if defined");if(this.#s=x,void 0!==E&&"function"!=typeof E)throw new TypeError("fetchMethod must be a function if specified");if(this.#a=E,this.#M=!!E,this.#h=new Map,this.#f=new Array(t).fill(void 0),this.#d=new Array(t).fill(void 0),this.#g=new A(t),this.#p=new A(t),this.#b=0,this.#m=0,this.#w=d.create(t),this.#u=0,this.#l=0,"function"==typeof p&&(this.#r=p),"function"==typeof b&&(this.#i=b),"function"==typeof m?(this.#o=m,this.#v=[]):(this.#o=void 0,this.#v=void 0),this.#x=!!this.#r,this.#C=!!this.#i,this.#T=!!this.#o,this.noDisposeOnSet=!!w,this.noUpdateTTL=!!v,this.noDeleteOnFetchRejection=!!M,this.allowStaleOnFetchRejection=!!C,this.allowStaleOnFetchAbort=!!_,this.ignoreFetchAbort=!!P,0!==this.maxEntrySize){if(0!==this.#n&&!l(this.#n))throw new TypeError("maxSize must be a positive integer if specified");if(!l(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!f,this.noDeleteOnStaleGet=!!T,this.updateAgeOnGet=!!c,this.updateAgeOnHas=!!u,this.ttlResolution=l(r)||0===r?r:1,this.ttlAutopurge=!!a,this.ttl=n||0,this.ttl){if(!l(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#R()}if(0===this.#t&&0===this.ttl&&0===this.#n)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#n){const e="LRU_CACHE_UNBOUNDED";(e=>!o.has(e))(e)&&(o.add(e),s("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,g))}}getRemainingTTL(e){return this.#h.has(e)?1/0:0}#R(){const e=new f(this.#t),t=new f(this.#t);this.#k=e,this.#S=t;const n=this.ttlAutopurge?new Array(this.#t):void 0;this.#E=n,this.#N=(r,i,o=this.#c.now())=>{if(t[r]=0!==i?o:0,e[r]=i,n?.[r]&&(clearTimeout(n[r]),n[r]=void 0),0!==i&&n){const e=setTimeout((()=>{this.#j(r)&&this.#L(this.#f[r],"expire")}),i+1);e.unref&&e.unref(),n[r]=e}},this.#D=n=>{t[n]=0!==e[n]?this.#c.now():0},this.#F=(n,o)=>{if(e[o]){const a=e[o],s=t[o];if(!a||!s)return;n.ttl=a,n.start=s,n.now=r||i();const c=n.now-s;n.remainingTTL=a-c}};let r=0;const i=()=>{const e=this.#c.now();if(this.ttlResolution>0){r=e;const t=setTimeout((()=>r=0),this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=n=>{const o=this.#h.get(n);if(void 0===o)return 0;const a=e[o],s=t[o];return a&&s?a-((r||i())-s):1/0},this.#j=n=>{const o=t[n],a=e[n];return!!a&&!!o&&(r||i())-o>a}}#D=()=>{};#F=()=>{};#N=()=>{};#j=()=>!1;#$(){const e=new f(this.#t);this.#l=0,this.#y=e,this.#B=t=>{this.#l-=e[t],e[t]=0},this.#z=(e,t,n,r)=>{if(this.#_(t))return 0;if(!l(n)){if(!r)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof r)throw new TypeError("sizeCalculation must be a function");if(n=r(t,e),!l(n))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return n},this.#U=(t,n,r)=>{if(e[t]=n,this.#n){const n=this.#n-e[t];for(;this.#l>n;)this.#q(!0)}this.#l+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#l)}}#B=e=>{};#U=(e,t,n)=>{};#z=(e,t,n,r)=>{if(n||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:e=this.allowStale}={}){if(this.#u)for(let t=this.#m;this.#H(t)&&(!e&&this.#j(t)||(yield t),t!==this.#b);)t=this.#p[t]}*#O({allowStale:e=this.allowStale}={}){if(this.#u)for(let t=this.#b;this.#H(t)&&(!e&&this.#j(t)||(yield t),t!==this.#m);)t=this.#g[t]}#H(e){return void 0!==e&&this.#h.get(this.#f[e])===e}*entries(){for(const e of this.#A())void 0===this.#d[e]||void 0===this.#f[e]||this.#_(this.#d[e])||(yield[this.#f[e],this.#d[e]])}*rentries(){for(const e of this.#O())void 0===this.#d[e]||void 0===this.#f[e]||this.#_(this.#d[e])||(yield[this.#f[e],this.#d[e]])}*keys(){for(const e of this.#A()){const t=this.#f[e];void 0===t||this.#_(this.#d[e])||(yield t)}}*rkeys(){for(const e of this.#O()){const t=this.#f[e];void 0===t||this.#_(this.#d[e])||(yield t)}}*values(){for(const e of this.#A())void 0===this.#d[e]||this.#_(this.#d[e])||(yield this.#d[e])}*rvalues(){for(const e of this.#O())void 0===this.#d[e]||this.#_(this.#d[e])||(yield this.#d[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const n of this.#A()){const r=this.#d[n],i=this.#_(r)?r.__staleWhileFetching:r;if(void 0!==i&&e(i,this.#f[n],this))return this.get(this.#f[n],t)}}forEach(e,t=this){for(const n of this.#A()){const r=this.#d[n],i=this.#_(r)?r.__staleWhileFetching:r;void 0!==i&&e.call(t,i,this.#f[n],this)}}rforEach(e,t=this){for(const n of this.#O()){const r=this.#d[n],i=this.#_(r)?r.__staleWhileFetching:r;void 0!==i&&e.call(t,i,this.#f[n],this)}}purgeStale(){let e=!1;for(const t of this.#O({allowStale:!0}))this.#j(t)&&(this.#L(this.#f[t],"expire"),e=!0);return e}info(e){const t=this.#h.get(e);if(void 0===t)return;const n=this.#d[t],r=this.#_(n)?n.__staleWhileFetching:n;if(void 0===r)return;const i={value:r};if(this.#k&&this.#S){const e=this.#k[t],n=this.#S[t];if(e&&n){const t=e-(this.#c.now()-n);i.ttl=t,i.start=Date.now()}}return this.#y&&(i.size=this.#y[t]),i}dump(){const e=[];for(const t of this.#A({allowStale:!0})){const n=this.#f[t],r=this.#d[t],i=this.#_(r)?r.__staleWhileFetching:r;if(void 0===i||void 0===n)continue;const o={value:i};if(this.#k&&this.#S){o.ttl=this.#k[t];const e=this.#c.now()-this.#S[t];o.start=Math.floor(Date.now()-e)}this.#y&&(o.size=this.#y[t]),e.unshift([n,o])}return e}load(e){this.clear();for(const[t,n]of e){if(n.start){const e=Date.now()-n.start;n.start=this.#c.now()-e}this.set(t,n.value,n)}}set(e,t,n={}){if(void 0===t)return this.delete(e),this;const{ttl:r=this.ttl,start:i,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:s}=n;let{noUpdateTTL:c=this.noUpdateTTL}=n;const u=this.#z(e,t,n.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return s&&(s.set="miss",s.maxEntrySizeExceeded=!0),this.#L(e,"set"),this;let l=0===this.#u?void 0:this.#h.get(e);if(void 0===l)l=0===this.#u?this.#m:0!==this.#w.length?this.#w.pop():this.#u===this.#t?this.#q(!1):this.#u,this.#f[l]=e,this.#d[l]=t,this.#h.set(e,l),this.#g[this.#m]=l,this.#p[l]=this.#m,this.#m=l,this.#u++,this.#U(l,u,s),s&&(s.set="add"),c=!1,this.#C&&this.#i?.(t,e,"add");else{this.#I(l);const n=this.#d[l];if(t!==n){if(this.#M&&this.#_(n)){n.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=n;void 0===t||o||(this.#x&&this.#r?.(t,e,"set"),this.#T&&this.#v?.push([t,e,"set"]))}else o||(this.#x&&this.#r?.(n,e,"set"),this.#T&&this.#v?.push([n,e,"set"]));if(this.#B(l),this.#U(l,u,s),this.#d[l]=t,s){s.set="replace";const e=n&&this.#_(n)?n.__staleWhileFetching:n;void 0!==e&&(s.oldValue=e)}}else s&&(s.set="update");this.#C&&this.onInsert?.(t,e,t===n?"update":"replace")}if(0===r||this.#k||this.#R(),this.#k&&(c||this.#N(l,r,i),s&&this.#F(s,l)),!o&&this.#T&&this.#v){const e=this.#v;let t;for(;t=e?.shift();)this.#o?.(...t)}return this}pop(){try{for(;this.#u;){const e=this.#d[this.#b];if(this.#q(!0),this.#_(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#T&&this.#v){const e=this.#v;let t;for(;t=e?.shift();)this.#o?.(...t)}}}#q(e){const t=this.#b,n=this.#f[t],r=this.#d[t];return this.#M&&this.#_(r)?r.__abortController.abort(new Error("evicted")):(this.#x||this.#T)&&(this.#x&&this.#r?.(r,n,"evict"),this.#T&&this.#v?.push([r,n,"evict"])),this.#B(t),this.#E?.[t]&&(clearTimeout(this.#E[t]),this.#E[t]=void 0),e&&(this.#f[t]=void 0,this.#d[t]=void 0,this.#w.push(t)),1===this.#u?(this.#b=this.#m=0,this.#w.length=0):this.#b=this.#g[t],this.#h.delete(n),this.#u--,t}has(e,t={}){const{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#h.get(e);if(void 0!==i){const e=this.#d[i];if(this.#_(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#j(i))return n&&this.#D(i),r&&(r.has="hit",this.#F(r,i)),!0;r&&(r.has="stale",this.#F(r,i))}else r&&(r.has="miss");return!1}peek(e,t={}){const{allowStale:n=this.allowStale}=t,r=this.#h.get(e);if(void 0===r||!n&&this.#j(r))return;const i=this.#d[r];return this.#_(i)?i.__staleWhileFetching:i}#P(e,t,n,r){const i=void 0===t?void 0:this.#d[t];if(this.#_(i))return i;const o=new c,{signal:a}=n;a?.addEventListener("abort",(()=>o.abort(a.reason)),{signal:o.signal});const s={signal:o.signal,options:n,context:r},u=(r,i=!1)=>{const{aborted:a}=o.signal,c=n.ignoreFetchAbort&&void 0!==r;if(n.status&&(a&&!i?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,c&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),a&&!c&&!i)return l(o.signal.reason);const u=h,f=this.#d[t];return(f===h||c&&i&&void 0===f)&&(void 0===r?void 0!==u.__staleWhileFetching?this.#d[t]=u.__staleWhileFetching:this.#L(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,r,s.options))),r},l=r=>{const{aborted:i}=o.signal,a=i&&n.allowStaleOnFetchAbort,s=a||n.allowStaleOnFetchRejection,c=s||n.noDeleteOnFetchRejection,u=h;if(this.#d[t]===h&&(c&&void 0!==u.__staleWhileFetching?a||(this.#d[t]=u.__staleWhileFetching):this.#L(e,"fetch")),s)return n.status&&void 0!==u.__staleWhileFetching&&(n.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw r};n.status&&(n.status.fetchDispatched=!0);const h=new Promise(((t,r)=>{const a=this.#a?.(e,i,s);a&&a instanceof Promise&&a.then((e=>t(void 0===e?void 0:e)),r),o.signal.addEventListener("abort",(()=>{n.ignoreFetchAbort&&!n.allowStaleOnFetchAbort||(t(void 0),n.allowStaleOnFetchAbort&&(t=e=>u(e,!0)))}))})).then(u,(e=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=e),l(e)))),f=Object.assign(h,{__abortController:o,__staleWhileFetching:i,__returned:void 0});return void 0===t?(this.set(e,f,{...s.options,status:void 0}),t=this.#h.get(e)):this.#d[t]=f,f}#_(e){if(!this.#M)return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof c}async fetch(e,t={}){const{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:s=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:h=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:d=this.allowStaleOnFetchAbort,context:g,forceRefresh:p=!1,status:b,signal:m}=t;if(!this.#M)return b&&(b.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:b});const w={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:o,noDisposeOnSet:a,size:s,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:h,allowStaleOnFetchAbort:d,ignoreFetchAbort:f,status:b,signal:m};let v=this.#h.get(e);if(void 0===v){b&&(b.fetch="miss");const t=this.#P(e,v,w,g);return t.__returned=t}{const t=this.#d[v];if(this.#_(t)){const e=n&&void 0!==t.__staleWhileFetching;return b&&(b.fetch="inflight",e&&(b.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const i=this.#j(v);if(!p&&!i)return b&&(b.fetch="hit"),this.#I(v),r&&this.#D(v),b&&this.#F(b,v),t;const o=this.#P(e,v,w,g),a=void 0!==o.__staleWhileFetching&&n;return b&&(b.fetch=i?"stale":"refresh",a&&i&&(b.returnedStale=!0)),a?o.__staleWhileFetching:o.__returned=o}}async forceFetch(e,t={}){const n=await this.fetch(e,t);if(void 0===n)throw new Error("fetch() returned undefined");return n}memo(e,t={}){const n=this.#s;if(!n)throw new Error("no memoMethod provided to constructor");const{context:r,forceRefresh:i,...o}=t,a=this.get(e,o);if(!i&&void 0!==a)return a;const s=n(e,a,{options:o,context:r});return this.set(e,s,o),s}get(e,t={}){const{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:o}=t,a=this.#h.get(e);if(void 0!==a){const t=this.#d[a],s=this.#_(t);return o&&this.#F(o,a),this.#j(a)?(o&&(o.get="stale"),s?(o&&n&&void 0!==t.__staleWhileFetching&&(o.returnedStale=!0),n?t.__staleWhileFetching:void 0):(i||this.#L(e,"expire"),o&&n&&(o.returnedStale=!0),n?t:void 0)):(o&&(o.get="hit"),s?t.__staleWhileFetching:(this.#I(a),r&&this.#D(a),t))}o&&(o.get="miss")}#J(e,t){this.#p[t]=e,this.#g[e]=t}#I(e){e!==this.#m&&(e===this.#b?this.#b=this.#g[e]:this.#J(this.#p[e],this.#g[e]),this.#J(this.#m,e),this.#m=e)}delete(e){return this.#L(e,"delete")}#L(e,t){let n=!1;if(0!==this.#u){const r=this.#h.get(e);if(void 0!==r)if(this.#E?.[r]&&(clearTimeout(this.#E?.[r]),this.#E[r]=void 0),n=!0,1===this.#u)this.#G(t);else{this.#B(r);const n=this.#d[r];if(this.#_(n)?n.__abortController.abort(new Error("deleted")):(this.#x||this.#T)&&(this.#x&&this.#r?.(n,e,t),this.#T&&this.#v?.push([n,e,t])),this.#h.delete(e),this.#f[r]=void 0,this.#d[r]=void 0,r===this.#m)this.#m=this.#p[r];else if(r===this.#b)this.#b=this.#g[r];else{const e=this.#p[r];this.#g[e]=this.#g[r];const t=this.#g[r];this.#p[t]=this.#p[r]}this.#u--,this.#w.push(r)}}if(this.#T&&this.#v?.length){const e=this.#v;let t;for(;t=e?.shift();)this.#o?.(...t)}return n}clear(){return this.#G("delete")}#G(e){for(const t of this.#O({allowStale:!0})){const n=this.#d[t];if(this.#_(n))n.__abortController.abort(new Error("deleted"));else{const r=this.#f[t];this.#x&&this.#r?.(n,r,e),this.#T&&this.#v?.push([n,r,e])}}if(this.#h.clear(),this.#d.fill(void 0),this.#f.fill(void 0),this.#k&&this.#S){this.#k.fill(0),this.#S.fill(0);for(const e of this.#E??[])void 0!==e&&clearTimeout(e);this.#E?.fill(void 0)}if(this.#y&&this.#y.fill(0),this.#b=0,this.#m=0,this.#w.length=0,this.#l=0,this.#u=0,this.#T&&this.#v){const e=this.#v;let t;for(;t=e?.shift();)this.#o?.(...t)}}}t.LRUCache=g},23319:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.redactConnectionString=t.shouldRedactCommand=void 0,t.redact=a;const r=n(94424),i=n(53442),o=n(20530);function a(e,t=void 0){if((0,i.isPlainObject)(e)){const n=Object.fromEntries(Object.entries(e).map((([e,n])=>[e,a(n,t)])));return Object.setPrototypeOf(n,Object.getPrototypeOf(e))}if(Array.isArray(e))return e.map((e=>a(e,t)));if("string"!=typeof e)return e;t&&(e=(0,o.redactSecretsOnString)(e,t));for(const[t,n]of r.regexes)e=e.replace(t,n);return e}var s=n(97872);Object.defineProperty(t,"shouldRedactCommand",{enumerable:!0,get:function(){return s.shouldRedactCommand}});var c=n(48777);Object.defineProperty(t,"redactConnectionString",{enumerable:!0,get:function(){return c.redactConnectionString}}),t.default=a},24609:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SLOW_QUERY_LOGS_COPY=t.SUGGESTED_INDEXES_COPY=t.DEFAULT_SLOW_QUERY_LOGS_LIMIT=void 0,t.getSuggestedIndexes=async function(e,t,n){try{return{suggestedIndexes:(await e.listClusterSuggestedIndexes({params:{path:{groupId:t,clusterName:n}}})).content.suggestedIndexes??[]}}catch(t){throw e.logger.debug({id:r.LogId.atlasPaSuggestedIndexesFailure,context:"performanceAdvisorUtils",message:`Failed to list suggested indexes: ${t instanceof Error?t.message:String(t)}`}),new Error(`Failed to list suggested indexes: ${t instanceof Error?t.message:String(t)}`)}},t.getDropIndexSuggestions=async function(e,t,n){try{const r=await e.listDropIndexSuggestions({params:{path:{groupId:t,clusterName:n}}});return{hiddenIndexes:r.content.hiddenIndexes??[],redundantIndexes:r.content.redundantIndexes??[],unusedIndexes:r.content.unusedIndexes??[]}}catch(t){throw e.logger.debug({id:r.LogId.atlasPaDropIndexSuggestionsFailure,context:"performanceAdvisorUtils",message:`Failed to list drop index suggestions: ${t instanceof Error?t.message:String(t)}`}),new Error(`Failed to list drop index suggestions: ${t instanceof Error?t.message:String(t)}`)}},t.getSchemaAdvice=async function(e,t,n){try{return{recommendations:(await e.listSchemaAdvice({params:{path:{groupId:t,clusterName:n}}})).content.recommendations??[]}}catch(t){throw e.logger.debug({id:r.LogId.atlasPaSchemaAdviceFailure,context:"performanceAdvisorUtils",message:`Failed to list schema advice: ${t instanceof Error?t.message:String(t)}`}),new Error(`Failed to list schema advice: ${t instanceof Error?t.message:String(t)}`)}},t.getSlowQueries=async function(e,n,o,a,s){try{const r=await(0,i.getProcessIdsFromCluster)(e,n,o);if(0===r.length)return{slowQueryLogs:[]};const c=r.map((r=>e.listSlowQueryLogs({params:{path:{groupId:n,processId:r},query:{...a&&{since:a.getTime()},...s&&{namespaces:s},nLogs:t.DEFAULT_SLOW_QUERY_LOGS_LIMIT}}})));return{slowQueryLogs:(await Promise.allSettled(c)).reduce(((e,t)=>e.concat("fulfilled"===t.status?t.value.slowQueries??[]:[])),[])}}catch(t){throw e.logger.debug({id:r.LogId.atlasPaSlowQueryLogsFailure,context:"performanceAdvisorUtils",message:`Failed to list slow query logs: ${t instanceof Error?t.message:String(t)}`}),new Error(`Failed to list slow query logs: ${t instanceof Error?t.message:String(t)}`)}};const r=n(45584),i=n(30084);t.DEFAULT_SLOW_QUERY_LOGS_LIMIT=50,t.SUGGESTED_INDEXES_COPY='Note: The "Weight" field is measured in bytes, and represents the estimated number of bytes saved in disk reads per executed read query that would be saved by implementing an index suggestion. Please convert this to MB or GB for easier readability.',t.SLOW_QUERY_LOGS_COPY=`Please notify the user that the MCP server tool limits slow query logs to the most recent ${t.DEFAULT_SLOW_QUERY_LOGS_LIMIT} slow query logs. This is a limitation of the MCP server tool only. More slow query logs and performance suggestions can be seen in the Atlas UI. Please give to the user the following docs about the performance advisor: https://www.mongodb.com/docs/atlas/performance-advisor/.`},25056:(e,t,n)=>{var r=n(65994).process;Object.defineProperty(t,"__esModule",{value:!0}),t.TransportRunnerBase=void 0;const i=n(60842),o=n(74171),a=n(84998),s=n(72389),c=n(3476),u=n(45584),l=n(35902),h=n(41654),f=n(4060),d=n(67645),g=n(98846),p=n(6467),b=n(87226),m=n(83671),w=n(50598),v=n(71777);class y{constructor({userConfig:e,createConnectionManager:t=d.createMCPConnectionManager,connectionErrorHandler:n=g.connectionErrorHandler,createAtlasLocalClient:i=b.defaultCreateAtlasLocalClient,additionalLoggers:o=[],telemetryProperties:a={},tools:s,createSessionConfig:c,createApiClient:l=v.createAtlasApiClient}){this.userConfig=e,this.createConnectionManager=t,this.connectionErrorHandler=n,this.createAtlasLocalClient=i,this.telemetryProperties=a,this.tools=s,this.createSessionConfig=c,this.createApiClient=l;const p=[...o];this.userConfig.loggers.includes("stderr")&&p.push(new u.ConsoleLogger(f.Keychain.root)),this.userConfig.loggers.includes("disk")&&p.push(new u.DiskLogger(this.userConfig.logPath,(e=>{console.error("Error initializing disk logger:",e),r.exit(1)}),f.Keychain.root)),this.logger=new u.CompositeLogger(...p),this.deviceId=h.DeviceId.create(this.logger)}async setupServer(e){let t=this.userConfig;t=this.createSessionConfig?await this.createSessionConfig({userConfig:t,request:e}):(0,w.applyConfigOverrides)({baseConfig:this.userConfig,request:e});const n=new c.McpServer({name:i.packageInfo.mcpServerName,version:i.packageInfo.version},{instructions:y.getInstructions(t)}),r=new u.CompositeLogger(this.logger),h=l.ExportsManager.init(t,r),d=await this.createConnectionManager({logger:r,userConfig:t,deviceId:this.deviceId});let g;t.apiClientId&&t.apiClientSecret&&(g=this.createApiClient({baseUrl:t.apiBaseUrl,credentials:{clientId:t.apiClientId,clientSecret:t.apiClientSecret},requestContext:e},r));const b=new a.Session({userConfig:t,atlasLocalClient:await this.createAtlasLocalClient({logger:r}),logger:r,exportsManager:h,connectionManager:d,keychain:f.Keychain.root,vectorSearchEmbeddingsManager:new m.VectorSearchEmbeddingsManager(t,d),apiClient:g}),v=s.Telemetry.create(b,t,this.deviceId,{commonProperties:this.telemetryProperties}),S=new p.Elicitation({server:n.server}),k=new o.Server({mcpServer:n,session:b,telemetry:v,userConfig:t,connectionErrorHandler:this.connectionErrorHandler,elicitation:S,tools:this.tools});return t.loggers.includes("mcp")&&r.addLogger(new u.McpLogger(k,f.Keychain.root)),k}async close(){try{await this.closeTransport()}finally{this.deviceId.close()}}static getInstructions(e){let t="\n This is the MongoDB MCP server.\n ";return e.connectionString&&(t+="\n This MCP server was configured with a MongoDB connection string, and you can assume that you are connected to a MongoDB cluster.\n "),e.apiClientId&&e.apiClientSecret&&(t+="\n This MCP server was configured with MongoDB Atlas API credentials."),t}}t.TransportRunnerBase=y},25181:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:n(89689).validateUnion,error:{message:"must match a schema in anyOf"}};t.default=r},25182:function(e,t,n){var r,i=n(9606).URL,o=n(67787).Buffer,a=n(9606).URLSearchParams,s=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),c=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),u=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=r(e),i=0;i<n.length;i++)"default"!==n[i]&&s(t,e,n[i]);return c(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.ClientCredentialsAuthProvider=void 0;const l=u(n(54617)),h=n(45584),f=n(79587);t.ClientCredentialsAuthProvider=class{constructor(e,t){this.options=e,this.logger=t,this.oauth2Issuer={issuer:e.baseUrl,token_endpoint:new i("/api/oauth/token",e.baseUrl).toString(),revocation_endpoint:new i("/api/oauth/revoke",e.baseUrl).toString(),token_endpoint_auth_methods_supported:["client_secret_basic"],grant_types_supported:["client_credentials"]},this.customFetch=(0,f.createFetch)({useEnvironmentVariableProxies:!0})}async getAuthHeaders(){const e=await this.getAccessToken();return e?{Authorization:`Bearer ${e}`}:void 0}isAccessTokenValid(){return!!(this.accessToken&&void 0!==this.accessToken.expires_at&&this.accessToken.expires_at>Date.now())}getOauthClientAuth(){const e=this.options.clientSecret,t=this.options.clientId;return{client:{client_id:t},clientAuth:(n,r,i,a)=>{const s=o.from(`${t}:${e}`).toString("base64");a.set("Authorization",`Basic ${s}`)}}}async getNewAccessToken(){if(!this.oauth2Issuer)return;const{client:e,clientAuth:t}=this.getOauthClientAuth();if(e&&t){try{const n=await l.clientCredentialsGrantRequest(this.oauth2Issuer,e,t,new a,{[l.customFetch]:this.customFetch,headers:{"User-Agent":this.options.userAgent}}),r=await l.processClientCredentialsResponse(this.oauth2Issuer,e,n);this.accessToken={access_token:r.access_token,expires_at:Date.now()+1e3*(r.expires_in??0)}}catch(e){const t=e instanceof Error?e:new Error(String(e));this.logger.error({id:h.LogId.atlasConnectFailure,context:"clientCredentialsAuth",message:`Failed to request access token: ${t.message}`})}return this.accessToken}}async getAccessToken(){return this.isAccessTokenValid()||(this.accessToken=await this.getNewAccessToken()),this.accessToken?.access_token}async validate(){return!!await this.getAccessToken()}async revoke(){const{client:e,clientAuth:t}=this.getOauthClientAuth();try{this.oauth2Issuer&&this.accessToken&&e&&t&&await l.revocationRequest(this.oauth2Issuer,e,t,this.accessToken.access_token)}catch(e){const t=e instanceof Error?e:new Error(String(e));this.logger.error({id:h.LogId.atlasApiRevokeFailure,context:"clientCredentialsAuth",message:`Failed to revoke access token: ${t.message}`})}this.accessToken=void 0}}},25220:(e,t,n)=>{n.d(t,{Ay:()=>i});var r=n(12453);const i=r;r.MAX_DATABASE_NAME_LENGTH,r.sort},25364:function(e,t,n){var r,i=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=r(e),a=0;a<n.length;a++)"default"!==n[a]&&i(t,e,n[a]);return o(t,e),t}),s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_HINT=t.DEFAULT_MAX_TIME_MS=t.DEFAULT_COLLATION=t.DEFAULT_PROJECT=t.DEFAULT_SKIP=t.DEFAULT_LIMIT=t.DEFAULT_SORT=t.DEFAULT_FILTER=t.toJSString=t.stringify=void 0,t.parseSort=T,t.parseFilter=function(e){return k(e)?g:_(e)},t.parseCollation=function(e){return k(e)?v:M(e)},t.isFilterValid=P,t.isCollationValid=I,t.parseProject=function(e){return k(e)?w:x(e)},t.isProjectValid=O,t.isSortValid=N,t.isHintValid=L,t.isMaxTimeMSValid=D,t.isSkipValid=F,t.isLimitValid=B,t.validate=function(e,t){const n=z[`is${u.default.upperFirst(e)}Valid`];return n?n(t):(d("Do not know how to validate `%s`. Returning false.",e),!1)},t.default=function(e,t=w){return 1===arguments.length&&u.default.isString(e)?_(e):{filter:_(e),project:t!==w?x(t):t}};const c=a(n(9651)),u=s(n(20990)),l=s(n(46696)),h=n(79193),f=n(60313);Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return f.stringify}}),Object.defineProperty(t,"toJSString",{enumerable:!0,get:function(){return f.toJSString}});const d=(0,l.default)("mongodb-query-parser"),g={};t.DEFAULT_FILTER=g;const p=null;t.DEFAULT_SORT=p;const b=0;t.DEFAULT_LIMIT=b;const m=0;t.DEFAULT_SKIP=m;const w=null;t.DEFAULT_PROJECT=w;const v=null;t.DEFAULT_COLLATION=v;const y=6e4;t.DEFAULT_MAX_TIME_MS=y;const S=null;function k(e){if(null==e)return!0;const t=u.default.trim("number"==typeof e?`${e}`:e);return"{}"===t||u.default.isEmpty(t)}function E(e){return k(e)?0:!!/^\d+$/.test(`${e}`)&&parseInt(`${e}`,10)}function x(e){return(0,c.default)(e,{mode:c.ParseMode.Loose})}function M(e){return(0,c.default)(e,{mode:c.ParseMode.Loose})}function T(e){return k(e)?p:(0,c.default)(e,{mode:c.ParseMode.Loose})}function C(){return!0}function _(e){return(0,c.default)(e,{mode:c.ParseMode.Loose,allowMethods:!0})}function P(e){if(k(e))return g;try{return _(e)}catch(t){return d('Filter "%s" is invalid',e,t),!1}}function I(e){if(k(e))return v;try{return function(e){for(const[t,n]of Object.entries(e)){if(!h.COLLATION_OPTIONS[t])return d('Collation "%s" is invalid bc of its keys',e),!1;if(!1===h.COLLATION_OPTIONS[t].includes(n))return d('Collation "%s" is invalid bc of its values',e),!1}return e}(M(e))}catch(t){return d('Collation "%s" is invalid',e,t),!1}}function A(){return!0}function O(e){if(k(e))return w;try{const t=x(e);return u.default.isObject(t)?u.default.every(t,A)?t:(d('Project "%s" is invalid bc of its values',e),!1):(d('Project "%s" is invalid. Only documents are allowed',e),!1)}catch(t){return d('Project "%s" is invalid',e,t),!1}}t.DEFAULT_HINT=S;const j=[1,-1,"asc","desc"];function $(e){return u.default.includes(j,e)||!(!u.default.isObject(e)||!e.$meta)}function R(e){return u.default.isArray(e)&&2===e.length&&u.default.isString(e[0])&&$(e[1])}function N(e){try{const t=T(e);return k(t)?p:u.default.isArray(t)&&u.default.every(t,R)||u.default.isObject(t)&&!u.default.isArray(t)&&u.default.every(t,$)?t:(d('Sort "%s" is invalid bc of its values',e),!1)}catch(t){return d('Sort "%s" is invalid',e,t),!1}}function L(e){if(k(e))return S;try{const t=function(e){return(0,c.default)(e,{mode:c.ParseMode.Loose})}(e);return u.default.isString(t)?t:u.default.isArray(t)||!u.default.isObject(t)?(d('Hint "%s" is invalid. Only strings or documents are allowed',e),!1):u.default.every(t,C)?t:(d('Hint "%s" is invalid bc of its values',e),!1)}catch(t){return d('Hint "%s" is invalid',e,t),!1}}function D(e){return k(e)?y:E(e)}function F(e){return k(e)?m:E(e)}function B(e){return k(e)?b:E(e)}const z={isMaxTimeMSValid:D,isFilterValid:P,isProjectValid:O,isSortValid:N,isLimitValid:B,isSkipValid:F,isCollationValid:I,isNumberValid:E,isHintValid:L}},25539:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultParserOptions=void 0,t.parseUserConfig=function({args:e,overrides:n,parserOptions:l=t.defaultParserOptions}){const h=n?c.z.object({...a.UserConfigSchema.shape,...n}):a.UserConfigSchema,{error:f,warnings:d,parsed:g}=function({args:e,schema:t=a.UserConfigSchema,parserOptions:n}){let r,i;try{const{parsed:o,deprecated:a}=(0,s.parseArgsWithCliOptions)({args:e,schema:t,parserOptions:n});r=o,i=a,delete r.fileNames}catch(e){let t;if(e instanceof s.UnknownArgumentError){const n=(0,o.matchingConfigKey)(e.argument.replace(/^(--)/,""));t=n?`Error: Invalid command line argument '${e.argument}'. Did you mean '--${n}'?`:`Error: Invalid command line argument '${e.argument}'.`}return{error:t,warnings:[],parsed:{}}}return{error:void 0,warnings:[...u(r,e),...Object.entries(i).map((([e,t])=>`Warning: The --${e} argument is deprecated. Use --${t} instead.`))],parsed:r}}({args:e,schema:h,parserOptions:l});if(f)return{error:f,warnings:d,parsed:void 0};if(g.nodb)return{error:"Error: The --nodb argument is not supported in the MCP Server. Please remove it from your configuration.",warnings:d,parsed:void 0};const{connectionSpecifier:p}=g;if(p){const e=(0,r.generateConnectionInfoFromCliArgs)({...g,connectionSpecifier:p});g.connectionString=e.connectionString}const b=h.safeParse(g),m=s.CliOptionsSchema.safeParse(g),w=b.error||m.error;if(w)return{error:`Invalid configuration for the following fields:\n${w.issues.map((e=>`${e.path.join(".")} - ${e.message}`)).join("\n")}`,warnings:d,parsed:void 0};const v={...g,...b.data};return function(e){const t=i.Keychain.root,n=(e,n)=>{e&&t.register(e,n)};n(e.apiClientId,"user"),n(e.apiClientSecret,"password"),n(e.awsAccessKeyId,"password"),n(e.awsIamSessionToken,"password"),n(e.awsSecretAccessKey,"password"),n(e.awsSessionToken,"password"),n(e.password,"password"),n(e.tlsCAFile,"url"),n(e.tlsCRLFile,"url"),n(e.tlsCertificateKeyFile,"url"),n(e.tlsCertificateKeyFilePassword,"password"),n(e.username,"user")}(v),{parsed:v,warnings:d,error:void 0}};const r=n(91841),i=n(4060),o=n(60466),a=n(59300),s=n(47645),c=n(19844);function u(e,t){const n=[];t.find((e=>e.startsWith("--connectionString")))&&n.push("Warning: The --connectionString argument is deprecated. Prefer using the MDB_MCP_CONNECTION_STRING environment variable or the first positional argument for the connection string.");const r=e.previewFeatures?.includes("search"),i=!!e.voyageApiKey;return r&&!i&&n.push("Warning: Vector search is enabled but no embeddings provider is configured.\n- Set an embeddings provider configuration option to enable auto-embeddings during document insertion and text-based queries with $vectorSearch."),!r&&i&&n.push("Warning: An embeddings provider is configured but the 'search' preview feature is not enabled.\n- Enable vector search by adding 'search' to the 'previewFeatures' configuration option, or remove the embeddings provider configuration if not needed."),n}t.defaultParserOptions={config:"config",envPrefix:"MDB_MCP_",configuration:{...s.defaultParserOptions.configuration,"populate--":!0}}},27293:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(78249),i={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>r.str`must match format "${e}"`,params:({schemaCode:e})=>r._`{format: ${e}}`},code(e,t){const{gen:n,data:i,$data:o,schema:a,schemaCode:s,it:c}=e,{opts:u,errSchemaPath:l,schemaEnv:h,self:f}=c;u.validateFormats&&(o?function(){const o=n.scopeValue("formats",{ref:f.formats,code:u.code.formats}),a=n.const("fDef",r._`${o}[${s}]`),c=n.let("fType"),l=n.let("format");n.if(r._`typeof ${a} == "object" && !(${a} instanceof RegExp)`,(()=>n.assign(c,r._`${a}.type || "string"`).assign(l,r._`${a}.validate`)),(()=>n.assign(c,r._`"string"`).assign(l,a))),e.fail$data((0,r.or)(!1===u.strictSchema?r.nil:r._`${s} && !${l}`,function(){const e=h.$async?r._`(${a}.async ? await ${l}(${i}) : ${l}(${i}))`:r._`${l}(${i})`,n=r._`(typeof ${l} == "function" ? ${e} : ${l}.test(${i}))`;return r._`${l} && ${l} !== true && ${c} === ${t} && !${n}`}()))}():function(){const o=f.formats[a];if(!o)return void function(){if(!1!==u.strictSchema)throw new Error(e());function e(){return`unknown format "${a}" ignored in schema at path "${l}"`}f.logger.warn(e())}();if(!0===o)return;const[s,c,d]=function(e){const t=e instanceof RegExp?(0,r.regexpCode)(e):u.code.formats?r._`${u.code.formats}${(0,r.getProperty)(a)}`:void 0,i=n.scopeValue("formats",{key:a,ref:e,code:t});return"object"!=typeof e||e instanceof RegExp?["string",e,i]:[e.type||"string",e.validate,r._`${i}.validate`]}(o);s===t&&e.pass(function(){if("object"==typeof o&&!(o instanceof RegExp)&&o.async){if(!h.$async)throw new Error("async format in sync schema");return r._`await ${d}(${i})`}return"function"==typeof c?r._`${d}(${i})`:r._`${d}.test(${i})`}())}())}};t.default=i},27373:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DeleteDeploymentTool=void 0;const r=n(66473),i=n(14233);class o extends r.AtlasLocalToolBase{constructor(){super(...arguments),this.name="atlas-local-delete-deployment",this.description="Delete a MongoDB Atlas local deployment",this.argsShape={deploymentName:i.CommonArgs.string().describe("Name of the deployment to delete")}}async executeWithAtlasLocalClient({deploymentName:e},{client:t}){const n=await this.lookupTelemetryMetadata(t,e);return await t.deleteDeployment(e),{content:[{type:"text",text:`Deployment "${e}" deleted successfully.`}],_meta:{...n}}}}t.DeleteDeploymentTool=o,o.operationType="delete"},28098:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(86),i=n(36937),o=n(78249),a=new o.Name("fullFormats"),s=new o.Name("fastFormats"),c=(e,t={keywords:!0})=>{if(Array.isArray(t))return u(e,t,r.fullFormats,a),e;const[n,o]="fast"===t.mode?[r.fastFormats,s]:[r.fullFormats,a];return u(e,t.formats||r.formatNames,n,o),t.keywords&&(0,i.default)(e),e};function u(e,t,n,r){var i,a;null!==(i=(a=e.opts.code).formats)&&void 0!==i||(a.formats=o._`require("ajv-formats/dist/formats").${r}`);for(const r of t)e.addFormat(r,n[r])}c.get=(e,t="full")=>{const n=("fast"===t?r.fastFormats:r.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n},e.exports=t=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c},28285:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InspectClusterTool=t.InspectClusterArgs=void 0;const r=n(77710),i=n(55415),o=n(30084),a=n(14233);t.InspectClusterArgs={projectId:a.AtlasArgs.projectId().describe("Atlas project ID"),clusterName:a.AtlasArgs.clusterName().describe("Atlas cluster name")};class s extends i.AtlasToolBase{constructor(){super(...arguments),this.name="atlas-inspect-cluster",this.description="Inspect metadata of a MongoDB Atlas cluster",this.argsShape={...t.InspectClusterArgs}}async execute({projectId:e,clusterName:t}){const n=await(0,o.inspectCluster)(this.apiClient,e,t);return this.formatOutput(n)}formatOutput(e){const t={name:e.name||"Unknown",instanceType:e.instanceType,instanceSize:e.instanceSize||"N/A",state:e.state||"UNKNOWN",mongoDBVersion:e.mongoDBVersion||"N/A",connectionStrings:e.connectionStrings||{}};return{content:(0,r.formatUntrustedData)("Cluster details:",JSON.stringify(t))}}}t.InspectClusterTool=s,s.operationType="read"},29009:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getDataLake=function(e){return d(e)&&d(e.dataLake)&&"string"==typeof e.dataLake.version?{isDataLake:!0,dlVersion:e.dataLake.version}:{isDataLake:!1,dlVersion:null}},t.isEnterprise=function(e){return!!d(e)&&(!("string"!=typeof e.gitVersion||!e.gitVersion.match(/enterprise/))||!(!Array.isArray(e.modules)||-1===e.modules.indexOf("enterprise")))},t.isAtlas=function(e){return!!p(e).match(a)},t.isLocalAtlas=async function(e){try{return await e("admin","atlascli",{managedClusterType:"atlasCliLocalDevCluster"})>0}catch{return!1}},t.isAtlasStream=function(e){const t=p(e);return!(!t.match(a)||!t.match(s))},t.isLocalhost=function(e){return!!p(e).match(c)},t.isDigitalOcean=function(e){return!!p(e).match(u)},t.getGenuineMongoDB=function(e){const t=p(e);return t.match(l)?{isGenuine:!1,serverName:"cosmosdb"}:t.match(h)?{isGenuine:!1,serverName:"documentdb"}:{isGenuine:!0,serverName:"mongodb"}},t.identifyServerName=async function({connectionString:e,adminCommand:t}){try{const n=p(e);if(n.match(a))return"mongodb";if(n.match(l))return"cosmosdb";if(n.match(h))return"documentdb";if(n.match(f))return"firestore";const r=await Promise.all([t({buildInfo:1}).then((e=>"ferretdb"in e?["ferretdb"]:[]),(e=>(o("buildInfo command failed %O",e),[]))),t({getParameter:"foo"}).then((()=>[]),(e=>e instanceof Error&&/documentdb_api/.test(e.message)?["pg_documentdb"]:[]))]).then((e=>e.flat()));return 0===r.length?"mongodb":1===r.length?r[0]:"unknown"}catch(e){return o("Failed to identify server name",e),"unknown"}},t.getBuildEnv=function(e){if(!d(e)||!d(e.buildEnvironment))return{serverOs:null,serverArch:null};const{buildEnvironment:t}=e;return{serverOs:"string"==typeof t.target_os?t.target_os:null,serverArch:"string"==typeof t.target_arch?t.target_arch:null}};const i=r(n(65031)),o=(0,n(46696).debug)("mongodb-build-info"),a=/\.mongodb(-dev|-qa|-stage)?\.net$/i,s=/^atlas-stream-.+/i,c=/^(localhost|127\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])|0\.0\.0\.0|(?:0*:)*?:?0*1)$/i,u=/\.mongo\.ondigitalocean\.com$/i,l=/\.cosmos\.azure\.com$/i,h=/docdb(-elastic)?\.amazonaws\.com$/i,f=/\.firestore.goog$/i;function d(e){return"object"==typeof e&&null!==e}function g(e){return e.startsWith("[")?e.substring(1).split("]")[0]:e.split(":")[0]}function p(e){if("string"!=typeof e)return"";try{return g(new i.default(e).hosts[0])}catch(t){return g(e)}}},29382:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReactiveResource=void 0;const r=n(45584);t.ReactiveResource=class{constructor({resourceConfiguration:e,options:t,session:n,config:r,telemetry:i,current:o}){this.resourceCallback=async e=>({contents:[{text:await this.toOutput(),mimeType:"application/json",uri:e.href}]}),this.session=n,this.config=r,this.telemetry=i,this.name=e.name,this.uri=e.uri,this.resourceConfig=e.config,this.events=t.events,this.current=o??t.initial,this.setupEventListeners()}setupEventListeners(){for(const e of this.events)this.session.on(e,((...t)=>{this.reduceApply(e,t[0]),this.triggerUpdate()}))}register(e){this.server=e,this.server.mcpServer.registerResource(this.name,this.uri,this.resourceConfig,this.resourceCallback)}triggerUpdate(){try{this.server?.sendResourceListChanged(),this.server?.sendResourceUpdated(this.uri)}catch(e){this.session.logger.warning({id:r.LogId.resourceUpdateFailure,context:"resource",message:`Could not send the latest resources to the client: ${e}`})}}reduceApply(e,...t){this.current=this.reduce(e,...t)}}},30084:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatFlexCluster=a,t.formatCluster=s,t.inspectCluster=c,t.getConnectionString=function(e,t){switch(t){case"standard":return e.standardSrv||e.standard;case"private":return e.privateSrv||e.private;case"privateEndpoint":return e.privateEndpoint?.[0]?.srvConnectionString||e.privateEndpoint?.[0]?.connectionString}},t.getProcessIdsFromCluster=async function(e,t,n){try{return(await c(e,t,n)).processIds||[]}catch(e){throw new Error(`Failed to get processIds from cluster: ${e instanceof Error?e.message:String(e)}`)}};const r=n(45584),i=n(14052);function o(e){return e?new i.ConnectionString(e).hosts:[]}function a(e){return{name:e.name,instanceType:"FLEX",instanceSize:void 0,state:e.stateName,mongoDBVersion:e.mongoDBVersion,connectionStrings:e.connectionStrings,processIds:o(e.connectionStrings?.standard??"")}}function s(e){const t=(e.replicationSpecs||[]).map((e=>e.regionConfigs||[])).flat().map((e=>({providerName:e.providerName,instanceSize:e.electableSpecs?.instanceSize||e.readOnlySpecs?.instanceSize||e.analyticsSpecs?.instanceSize}))),n=t[0]?.instanceSize??"UNKNOWN",r="M0"===n?"FREE":"DEDICATED";return{name:e.name,instanceType:r,instanceSize:"DEDICATED"===r?n:void 0,state:e.stateName,mongoDBVersion:e.mongoDBVersion,connectionStrings:e.connectionStrings,processIds:o(e.connectionStrings?.standard??"")}}async function c(e,t,n){try{return s(await e.getCluster({params:{path:{groupId:t,clusterName:n}}}))}catch(i){try{return a(await e.getFlexCluster({params:{path:{groupId:t,name:n}}}))}catch(t){const n=t instanceof Error?t:new Error(String(t));throw e.logger.error({id:r.LogId.atlasInspectFailure,context:"inspect-cluster",message:`error inspecting cluster: ${n.message}`}),i}}}},30098:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(78249),i=n(87351),o=n(89689),a=n(98245),s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>r.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>r._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:n,it:r}=e,{prefixItems:s}=n;r.items=!0,(0,i.alwaysValidSchema)(r,t)||(s?(0,a.validateAdditionalItems)(e,s):e.ok((0,o.validateArray)(e)))}};t.default=s},30784:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SwitchConnectionTool=t.DropIndexTool=t.ExportTool=t.LogsTool=t.CreateCollectionTool=t.ExplainTool=t.DropCollectionTool=t.DropDatabaseTool=t.RenameCollectionTool=t.UpdateManyTool=t.AggregateTool=t.DbStatsTool=t.CountTool=t.CollectionStorageSizeTool=t.DeleteManyTool=t.InsertManyTool=t.FindTool=t.CollectionSchemaTool=t.CreateIndexTool=t.ListDatabasesTool=t.CollectionIndexesTool=t.ListCollectionsTool=t.ConnectTool=void 0;var r=n(3668);Object.defineProperty(t,"ConnectTool",{enumerable:!0,get:function(){return r.ConnectTool}});var i=n(43376);Object.defineProperty(t,"ListCollectionsTool",{enumerable:!0,get:function(){return i.ListCollectionsTool}});var o=n(47437);Object.defineProperty(t,"CollectionIndexesTool",{enumerable:!0,get:function(){return o.CollectionIndexesTool}});var a=n(77107);Object.defineProperty(t,"ListDatabasesTool",{enumerable:!0,get:function(){return a.ListDatabasesTool}});var s=n(70444);Object.defineProperty(t,"CreateIndexTool",{enumerable:!0,get:function(){return s.CreateIndexTool}});var c=n(21570);Object.defineProperty(t,"CollectionSchemaTool",{enumerable:!0,get:function(){return c.CollectionSchemaTool}});var u=n(32665);Object.defineProperty(t,"FindTool",{enumerable:!0,get:function(){return u.FindTool}});var l=n(58272);Object.defineProperty(t,"InsertManyTool",{enumerable:!0,get:function(){return l.InsertManyTool}});var h=n(92983);Object.defineProperty(t,"DeleteManyTool",{enumerable:!0,get:function(){return h.DeleteManyTool}});var f=n(55101);Object.defineProperty(t,"CollectionStorageSizeTool",{enumerable:!0,get:function(){return f.CollectionStorageSizeTool}});var d=n(9015);Object.defineProperty(t,"CountTool",{enumerable:!0,get:function(){return d.CountTool}});var g=n(43052);Object.defineProperty(t,"DbStatsTool",{enumerable:!0,get:function(){return g.DbStatsTool}});var p=n(43443);Object.defineProperty(t,"AggregateTool",{enumerable:!0,get:function(){return p.AggregateTool}});var b=n(17179);Object.defineProperty(t,"UpdateManyTool",{enumerable:!0,get:function(){return b.UpdateManyTool}});var m=n(13511);Object.defineProperty(t,"RenameCollectionTool",{enumerable:!0,get:function(){return m.RenameCollectionTool}});var w=n(3131);Object.defineProperty(t,"DropDatabaseTool",{enumerable:!0,get:function(){return w.DropDatabaseTool}});var v=n(2622);Object.defineProperty(t,"DropCollectionTool",{enumerable:!0,get:function(){return v.DropCollectionTool}});var y=n(75966);Object.defineProperty(t,"ExplainTool",{enumerable:!0,get:function(){return y.ExplainTool}});var S=n(11062);Object.defineProperty(t,"CreateCollectionTool",{enumerable:!0,get:function(){return S.CreateCollectionTool}});var k=n(77854);Object.defineProperty(t,"LogsTool",{enumerable:!0,get:function(){return k.LogsTool}});var E=n(20644);Object.defineProperty(t,"ExportTool",{enumerable:!0,get:function(){return E.ExportTool}});var x=n(74964);Object.defineProperty(t,"DropIndexTool",{enumerable:!0,get:function(){return x.DropIndexTool}});var M=n(46096);Object.defineProperty(t,"SwitchConnectionTool",{enumerable:!0,get:function(){return M.SwitchConnectionTool}})},31022:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldPath=function(e,t,i){const o=t.split(".");if(o.some((e=>!e.trim())))throw new Error(`Invalid field path: '${t}'`);if(o.length>n)throw new Error(`Field path "${t}" has too many nested levels (maximum ${n} allowed).`);r(e,o,i,"")};const n=100;function r(e,t,n,o){const[a,...s]=t;if(!a)throw new Error(`Cannot set field at provided path: Unexpected empty key - '${a}' in field path.`);if(0===s.length)return void i(e,a,n);const c=o?`${o}.${a}`:a,u=Object.prototype.hasOwnProperty.call(e,a)?e[a]:void 0;if(null==u)i(e,a,{});else if("object"!=typeof u||Array.isArray(u))throw new Error(`Cannot set field at provided path: intermediate path '${c}' is not an object.`);r(e[a],s,n,c)}function i(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}},31999:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(78249),i=n(87351),o=n(12798),a={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>r._`{allowedValues: ${e}}`},code(e){const{gen:t,data:n,$data:a,schema:s,schemaCode:c,it:u}=e;if(!a&&0===s.length)throw new Error("enum must have non-empty array");const l=s.length>=u.opts.loopEnum;let h;const f=()=>null!=h?h:h=(0,i.useFunc)(t,o.default);let d;if(l||a)d=t.let("valid"),e.block$data(d,(function(){t.assign(d,!1),t.forOf("v",c,(e=>t.if(r._`${f()}(${n}, ${e})`,(()=>t.assign(d,!0).break()))))}));else{if(!Array.isArray(s))throw new Error("ajv implementation error");const e=t.const("vSchema",c);d=(0,r.or)(...s.map(((t,i)=>function(e,t){const i=s[t];return"object"==typeof i&&null!==i?r._`${f()}(${n}, ${e}[${t}])`:r._`${n} === ${i}`}(e,i))))}e.pass(d)}};t.default=a},32665:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FindTool=t.FindArgs=void 0;const r=n(69761),i=n(58203),o=n(77710),a=n(49446),s=n(62444),c=n(92639),u=n(86463),l=n(18253),h=n(14233),f=n(45584);t.FindArgs={filter:(0,h.zEJSON)().optional().describe("The query filter, matching the syntax of the query argument of db.collection.find()"),projection:r.z.object({}).passthrough().optional().describe("The projection, matching the syntax of the projection argument of db.collection.find()"),limit:r.z.number().optional().default(10).describe("The maximum number of documents to return"),sort:r.z.object({}).catchall(r.z.custom()).optional().describe("A document, describing the sort order, matching the syntax of the sort argument of cursor.sort(). The keys of the object are the fields to sort on, while the values are the sort directions (1 for ascending, -1 for descending).")};class d extends i.MongoDBToolBase{constructor(){super(...arguments),this.name="find",this.description="Run a find query against a MongoDB collection",this.argsShape={...i.DbOperationArgs,...t.FindArgs,responseBytesLimit:r.z.number().optional().default(l.ONE_MB).describe('The maximum number of bytes to return in the response. This value is capped by the server\'s configured maxBytesPerQuery and cannot be exceeded. Note to LLM: If the entire query result is required, use the "export" tool instead of increasing this limit.')}}async execute({database:e,collection:t,filter:n,projection:r,limit:i,sort:h,responseBytesLimit:f},{signal:d}){let g;try{const p=await this.ensureConnected();this.config.indexCheck&&await(0,a.checkIndexUsage)({database:e,collection:t,operation:"find",explainCallback:async()=>p.find(e,t,n,{projection:r,limit:i,sort:h,signal:d}).explain("queryPlanner"),logger:this.session.logger});const b=this.getLimitForFindCursor(i);g=p.find(e,t,n,{projection:r,limit:b.limit,sort:h,signal:d});const[m,w]=await Promise.all([(0,u.operationWithFallback)((()=>p.countDocuments(e,t,n,{limit:i,maxTimeMS:l.QUERY_COUNT_MAX_TIME_MS_CAP,signal:d})),void 0),(0,c.collectCursorUntilMaxBytesLimit)({cursor:g,configuredMaxBytesPerQuery:this.config.maxBytesPerQuery,toolResponseBytesLimit:f,abortSignal:d})]);return{content:(0,o.formatUntrustedData)(this.generateMessage({collection:t,queryResultsCount:m,documents:w.documents,appliedLimits:[b.cappedBy,w.cappedBy].filter((e=>!!e))}),...w.documents.length>0?[s.EJSON.stringify(w.documents)]:[])}}finally{g&&this.safeCloseCursor(g)}}async safeCloseCursor(e){try{await e.close()}catch(e){this.session.logger.warning({id:f.LogId.mongodbCursorCloseError,context:"find tool",message:`Error when closing the cursor - ${e instanceof Error?e.message:String(e)}`})}}generateMessage({collection:e,queryResultsCount:t,documents:n,appliedLimits:r}){const i=r.length?`while respecting the applied limits of ${r.map((e=>l.CURSOR_LIMITS_TO_LLM_TEXT[e])).join(", ")}. Note to LLM: If the entire query result is required then use "export" tool to export the query results.`:"";return`Query on collection "${e}" resulted in ${void 0===t?"indeterminable number of":t} documents. Returning ${n.length} documents${i?` ${i}`:"."}`}getLimitForFindCursor(e){const t=parseInt(String(this.config.maxDocumentsPerQuery),10);return Number.isNaN(t)||t<=0?{cappedBy:void 0,limit:e??void 0}:null==e?{cappedBy:"config.maxDocumentsPerQuery",limit:t}:{cappedBy:t<e?"config.maxDocumentsPerQuery":void 0,limit:Math.min(e,t)}}}t.FindTool=d,d.operationType="read"},32674:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setAppNameParamIfMissing=async function({connectionString:e,components:t}){const n=new r.ConnectionString(e),i=n.typedSearchParams();if(i.has("appName"))return n.toString();const o=`${t.appName||"unknown"}--${t.deviceId?await t.deviceId:"unknown"}--${t.clientName||"unknown"}`;return i.set("appName",o),n.toString()},t.validateConnectionString=function(e,t){try{new r.ConnectionString(e,{looseValidation:t})}catch(e){throw new Error(`Invalid connection string with error: ${e instanceof Error?e.message:String(e)}`)}};const r=n(14052)},32781:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectDeploymentTool=void 0;const r=n(66473),i=n(14233);class o extends r.AtlasLocalToolBase{constructor(){super(...arguments),this.name="atlas-local-connect-deployment",this.description="Connect to a MongoDB Atlas Local deployment",this.argsShape={deploymentName:i.CommonArgs.string().describe("Name of the deployment to connect to")}}async executeWithAtlasLocalClient({deploymentName:e},{client:t}){const n=await t.getConnectionString(e);return await this.session.connectToMongoDB({connectionString:n}),{content:[{type:"text",text:`Successfully connected to Atlas Local deployment "${e}".`}],_meta:{...await this.lookupTelemetryMetadata(t,e)}}}resolveTelemetryMetadata(e,{result:t}){return{...super.resolveTelemetryMetadata(e,{result:t}),...this.getConnectionInfoMetadata()}}}t.ConnectDeploymentTool=o,o.operationType="connect"},33168:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.toTypescriptTypeDefinition=t.schemaStats=t.SchemaAnalyzer=t.getSimplifiedSchema=t.getSchemaPaths=t.analyzeDocuments=t.parseSchema=void 0;const a=n(37057),s=n(75996);Object.defineProperty(t,"SchemaAnalyzer",{enumerable:!0,get:function(){return s.SchemaAnalyzer}});const c=n(79059),u=n(59942),l=n(61283),h=o(n(33787));t.schemaStats=h;const f=n(33859);async function d(e,t){return(await(0,s.getCompletedSchemaAnalyzer)(e,t)).getResult()}Object.defineProperty(t,"toTypescriptTypeDefinition",{enumerable:!0,get:function(){return f.toTypescriptTypeDefinition}}),t.analyzeDocuments=async function(e,t){const n=(await(0,s.getCompletedSchemaAnalyzer)(e,t)).getResult();return new a.InternalSchemaBasedAccessor(n,{internalToStandard:l.convertInternalToStandard,internalToMongoDB:u.convertInternalToMongodb,internalToExpanded:c.convertInternalToExpanded})},t.parseSchema=d,t.getSchemaPaths=async function(e){return(await(0,s.getCompletedSchemaAnalyzer)(e)).getSchemaPaths()},t.getSimplifiedSchema=async function(e){return(await(0,s.getCompletedSchemaAnalyzer)(e)).getSimplifiedSchema()},t.default=d},33433:function(e,t,n){!function(e,t){function r(e,t){if(!e)throw new Error(t||"Assertion failed")}function i(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}function o(e,t,n){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(n=t,t=10),this._init(e||0,t||10,n||"be"))}var a;"object"==typeof e?e.exports=o:t.BN=o,o.BN=o,o.wordSize=26;try{a="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:n(67787).Buffer}catch(e){}function s(e,t){var n=e.charCodeAt(t);return n>=65&&n<=70?n-55:n>=97&&n<=102?n-87:n-48&15}function c(e,t,n){var r=s(e,n);return n-1>=t&&(r|=s(e,n-1)<<4),r}function u(e,t,n,r){for(var i=0,o=Math.min(e.length,n),a=t;a<o;a++){var s=e.charCodeAt(a)-48;i*=r,i+=s>=49?s-49+10:s>=17?s-17+10:s}return i}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,n){if("number"==typeof e)return this._initNumber(e,t,n);if("object"==typeof e)return this._initArray(e,t,n);"hex"===t&&(t=16),r(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i<e.length&&(16===t?this._parseHex(e,i,n):(this._parseBase(e,t,i),"le"===n&&this._initArray(this.toArray(),t,n)))},o.prototype._initNumber=function(e,t,n){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(r(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),t,n)},o.prototype._initArray=function(e,t,n){if(r("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var o,a,s=0;if("be"===n)for(i=e.length-1,o=0;i>=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<<s&67108863,this.words[o+1]=a>>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===n)for(i=0,o=0;i<e.length;i+=3)a=e[i]|e[i+1]<<8|e[i+2]<<16,this.words[o]|=a<<s&67108863,this.words[o+1]=a>>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t,n){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r<this.length;r++)this.words[r]=0;var i,o=0,a=0;if("be"===n)for(r=e.length-1;r>=t;r-=2)i=c(e,t,r)<<o,this.words[a]|=67108863&i,o>=18?(o-=18,a+=1,this.words[a]|=i>>>26):o+=8;else for(r=(e.length-t)%2==0?t+1:t;r<e.length;r+=2)i=c(e,t,r)<<o,this.words[a]|=67108863&i,o>=18?(o-=18,a+=1,this.words[a]|=i>>>26):o+=8;this.strip()},o.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,i=1;i<=67108863;i*=t)r++;r--,i=i/t|0;for(var o=e.length-n,a=o%r,s=Math.min(o,o-a)+n,c=0,l=n;l<s;l+=r)c=u(e,l,l+r,t),this.imuln(i),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c);if(0!==a){var h=1;for(c=u(e,l,e.length,t),l=0;l<a;l++)h*=t;this.imuln(h),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c)}this.strip()},o.prototype.copy=function(e){e.words=new Array(this.length);for(var t=0;t<this.length;t++)e.words[t]=this.words[t];e.length=this.length,e.negative=this.negative,e.red=this.red},o.prototype.clone=function(){var e=new o(null);return this.copy(e),e},o.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},o.prototype.strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var l=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],h=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],f=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function d(e,t,n){n.negative=t.negative^e.negative;var r=e.length+t.length|0;n.length=r,r=r-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,c=a/67108864|0;n.words[0]=s;for(var u=1;u<r;u++){for(var l=c>>>26,h=67108863&c,f=Math.min(u,t.length-1),d=Math.max(0,u-e.length+1);d<=f;d++){var g=u-d|0;l+=(a=(i=0|e.words[g])*(o=0|t.words[d])+h)/67108864|0,h=67108863&a}n.words[u]=0|h,c=0|l}return 0!==c?n.words[u]=0|c:n.length--,n.strip()}o.prototype.toString=function(e,t){var n;if(t=0|t||1,16===(e=e||10)||"hex"===e){n="";for(var i=0,o=0,a=0;a<this.length;a++){var s=this.words[a],c=(16777215&(s<<i|o)).toString(16);n=0!=(o=s>>>24-i&16777215)||a!==this.length-1?l[6-c.length]+c+n:c+n,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(n=o.toString(16)+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(e===(0|e)&&e>=2&&e<=36){var u=h[e],d=f[e];n="";var g=this.clone();for(g.negative=0;!g.isZero();){var p=g.modn(d).toString(e);n=(g=g.idivn(d)).isZero()?p+n:l[u-p.length]+p+n}for(this.isZero()&&(n="0"+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return r(void 0!==a),this.toArrayLike(a,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var a,s,c="le"===t,u=new e(o),l=this.clone();if(c){for(s=0;!l.isZero();s++)a=l.andln(255),l.iushrn(8),u[s]=a;for(;s<o;s++)u[s]=0}else{for(s=0;s<o-i;s++)u[s]=0;for(s=0;!l.isZero();s++)a=l.andln(255),l.iushrn(8),u[o-s-1]=a}return u},Math.clz32?o.prototype._countBits=function(e){return 32-Math.clz32(e)}:o.prototype._countBits=function(e){var t=e,n=0;return t>=4096&&(n+=13,t>>>=13),t>=64&&(n+=7,t>>>=7),t>=8&&(n+=4,t>>>=4),t>=2&&(n+=2,t>>>=2),n+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,n=0;return 8191&t||(n+=13,t>>>=13),127&t||(n+=7,t>>>=7),15&t||(n+=4,t>>>=4),3&t||(n+=2,t>>>=2),1&t||n++,n},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;t<this.length;t++){var n=this._zeroBits(this.words[t]);if(e+=n,26!==n)break}return e},o.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},o.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},o.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},o.prototype.isNeg=function(){return 0!==this.negative},o.prototype.neg=function(){return this.clone().ineg()},o.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},o.prototype.iuor=function(e){for(;this.length<e.length;)this.words[this.length++]=0;for(var t=0;t<e.length;t++)this.words[t]=this.words[t]|e.words[t];return this.strip()},o.prototype.ior=function(e){return r(!(this.negative|e.negative)),this.iuor(e)},o.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var n=0;n<t.length;n++)this.words[n]=this.words[n]&e.words[n];return this.length=t.length,this.strip()},o.prototype.iand=function(e){return r(!(this.negative|e.negative)),this.iuand(e)},o.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var r=0;r<n.length;r++)this.words[r]=t.words[r]^n.words[r];if(this!==t)for(;r<t.length;r++)this.words[r]=t.words[r];return this.length=t.length,this.strip()},o.prototype.ixor=function(e){return r(!(this.negative|e.negative)),this.iuxor(e)},o.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){r("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),n=e%26;this._expand(t),n>0&&t--;for(var i=0;i<t;i++)this.words[i]=67108863&~this.words[i];return n>0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){r("number"==typeof e&&e>=0);var n=e/26|0,i=e%26;return this._expand(n+1),this.words[n]=t?this.words[n]|1<<i:this.words[n]&~(1<<i),this.strip()},o.prototype.iadd=function(e){var t,n,r;if(0!==this.negative&&0===e.negative)return this.negative=0,t=this.isub(e),this.negative^=1,this._normSign();if(0===this.negative&&0!==e.negative)return e.negative=0,t=this.isub(e),e.negative=1,t._normSign();this.length>e.length?(n=this,r=e):(n=e,r=this);for(var i=0,o=0;o<r.length;o++)t=(0|n.words[o])+(0|r.words[o])+i,this.words[o]=67108863&t,i=t>>>26;for(;0!==i&&o<n.length;o++)t=(0|n.words[o])+i,this.words[o]=67108863&t,i=t>>>26;if(this.length=n.length,0!==i)this.words[this.length]=i,this.length++;else if(n!==this)for(;o<n.length;o++)this.words[o]=n.words[o];return this},o.prototype.add=function(e){var t;return 0!==e.negative&&0===this.negative?(e.negative=0,t=this.sub(e),e.negative^=1,t):0===e.negative&&0!==this.negative?(this.negative=0,t=e.sub(this),this.negative=1,t):this.length>e.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var n,r,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(n=this,r=e):(n=e,r=this);for(var o=0,a=0;a<r.length;a++)o=(t=(0|n.words[a])-(0|r.words[a])+o)>>26,this.words[a]=67108863&t;for(;0!==o&&a<n.length;a++)o=(t=(0|n.words[a])+o)>>26,this.words[a]=67108863&t;if(0===o&&a<n.length&&n!==this)for(;a<n.length;a++)this.words[a]=n.words[a];return this.length=Math.max(this.length,a),n!==this&&(this.negative=1),this.strip()},o.prototype.sub=function(e){return this.clone().isub(e)};var g=function(e,t,n){var r,i,o,a=e.words,s=t.words,c=n.words,u=0,l=0|a[0],h=8191&l,f=l>>>13,d=0|a[1],g=8191&d,p=d>>>13,b=0|a[2],m=8191&b,w=b>>>13,v=0|a[3],y=8191&v,S=v>>>13,k=0|a[4],E=8191&k,x=k>>>13,M=0|a[5],T=8191&M,C=M>>>13,_=0|a[6],P=8191&_,I=_>>>13,A=0|a[7],O=8191&A,j=A>>>13,$=0|a[8],R=8191&$,N=$>>>13,L=0|a[9],D=8191&L,F=L>>>13,B=0|s[0],z=8191&B,U=B>>>13,q=0|s[1],H=8191&q,J=q>>>13,G=0|s[2],V=8191&G,K=G>>>13,W=0|s[3],X=8191&W,Y=W>>>13,Q=0|s[4],Z=8191&Q,ee=Q>>>13,te=0|s[5],ne=8191&te,re=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ce=8191&se,ue=se>>>13,le=0|s[8],he=8191&le,fe=le>>>13,de=0|s[9],ge=8191&de,pe=de>>>13;n.negative=e.negative^t.negative,n.length=19;var be=(u+(r=Math.imul(h,z))|0)+((8191&(i=(i=Math.imul(h,U))+Math.imul(f,z)|0))<<13)|0;u=((o=Math.imul(f,U))+(i>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(g,z),i=(i=Math.imul(g,U))+Math.imul(p,z)|0,o=Math.imul(p,U);var me=(u+(r=r+Math.imul(h,H)|0)|0)+((8191&(i=(i=i+Math.imul(h,J)|0)+Math.imul(f,H)|0))<<13)|0;u=((o=o+Math.imul(f,J)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,r=Math.imul(m,z),i=(i=Math.imul(m,U))+Math.imul(w,z)|0,o=Math.imul(w,U),r=r+Math.imul(g,H)|0,i=(i=i+Math.imul(g,J)|0)+Math.imul(p,H)|0,o=o+Math.imul(p,J)|0;var we=(u+(r=r+Math.imul(h,V)|0)|0)+((8191&(i=(i=i+Math.imul(h,K)|0)+Math.imul(f,V)|0))<<13)|0;u=((o=o+Math.imul(f,K)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(y,z),i=(i=Math.imul(y,U))+Math.imul(S,z)|0,o=Math.imul(S,U),r=r+Math.imul(m,H)|0,i=(i=i+Math.imul(m,J)|0)+Math.imul(w,H)|0,o=o+Math.imul(w,J)|0,r=r+Math.imul(g,V)|0,i=(i=i+Math.imul(g,K)|0)+Math.imul(p,V)|0,o=o+Math.imul(p,K)|0;var ve=(u+(r=r+Math.imul(h,X)|0)|0)+((8191&(i=(i=i+Math.imul(h,Y)|0)+Math.imul(f,X)|0))<<13)|0;u=((o=o+Math.imul(f,Y)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(E,z),i=(i=Math.imul(E,U))+Math.imul(x,z)|0,o=Math.imul(x,U),r=r+Math.imul(y,H)|0,i=(i=i+Math.imul(y,J)|0)+Math.imul(S,H)|0,o=o+Math.imul(S,J)|0,r=r+Math.imul(m,V)|0,i=(i=i+Math.imul(m,K)|0)+Math.imul(w,V)|0,o=o+Math.imul(w,K)|0,r=r+Math.imul(g,X)|0,i=(i=i+Math.imul(g,Y)|0)+Math.imul(p,X)|0,o=o+Math.imul(p,Y)|0;var ye=(u+(r=r+Math.imul(h,Z)|0)|0)+((8191&(i=(i=i+Math.imul(h,ee)|0)+Math.imul(f,Z)|0))<<13)|0;u=((o=o+Math.imul(f,ee)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(T,z),i=(i=Math.imul(T,U))+Math.imul(C,z)|0,o=Math.imul(C,U),r=r+Math.imul(E,H)|0,i=(i=i+Math.imul(E,J)|0)+Math.imul(x,H)|0,o=o+Math.imul(x,J)|0,r=r+Math.imul(y,V)|0,i=(i=i+Math.imul(y,K)|0)+Math.imul(S,V)|0,o=o+Math.imul(S,K)|0,r=r+Math.imul(m,X)|0,i=(i=i+Math.imul(m,Y)|0)+Math.imul(w,X)|0,o=o+Math.imul(w,Y)|0,r=r+Math.imul(g,Z)|0,i=(i=i+Math.imul(g,ee)|0)+Math.imul(p,Z)|0,o=o+Math.imul(p,ee)|0;var Se=(u+(r=r+Math.imul(h,ne)|0)|0)+((8191&(i=(i=i+Math.imul(h,re)|0)+Math.imul(f,ne)|0))<<13)|0;u=((o=o+Math.imul(f,re)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(P,z),i=(i=Math.imul(P,U))+Math.imul(I,z)|0,o=Math.imul(I,U),r=r+Math.imul(T,H)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(C,H)|0,o=o+Math.imul(C,J)|0,r=r+Math.imul(E,V)|0,i=(i=i+Math.imul(E,K)|0)+Math.imul(x,V)|0,o=o+Math.imul(x,K)|0,r=r+Math.imul(y,X)|0,i=(i=i+Math.imul(y,Y)|0)+Math.imul(S,X)|0,o=o+Math.imul(S,Y)|0,r=r+Math.imul(m,Z)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(w,Z)|0,o=o+Math.imul(w,ee)|0,r=r+Math.imul(g,ne)|0,i=(i=i+Math.imul(g,re)|0)+Math.imul(p,ne)|0,o=o+Math.imul(p,re)|0;var ke=(u+(r=r+Math.imul(h,oe)|0)|0)+((8191&(i=(i=i+Math.imul(h,ae)|0)+Math.imul(f,oe)|0))<<13)|0;u=((o=o+Math.imul(f,ae)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(O,z),i=(i=Math.imul(O,U))+Math.imul(j,z)|0,o=Math.imul(j,U),r=r+Math.imul(P,H)|0,i=(i=i+Math.imul(P,J)|0)+Math.imul(I,H)|0,o=o+Math.imul(I,J)|0,r=r+Math.imul(T,V)|0,i=(i=i+Math.imul(T,K)|0)+Math.imul(C,V)|0,o=o+Math.imul(C,K)|0,r=r+Math.imul(E,X)|0,i=(i=i+Math.imul(E,Y)|0)+Math.imul(x,X)|0,o=o+Math.imul(x,Y)|0,r=r+Math.imul(y,Z)|0,i=(i=i+Math.imul(y,ee)|0)+Math.imul(S,Z)|0,o=o+Math.imul(S,ee)|0,r=r+Math.imul(m,ne)|0,i=(i=i+Math.imul(m,re)|0)+Math.imul(w,ne)|0,o=o+Math.imul(w,re)|0,r=r+Math.imul(g,oe)|0,i=(i=i+Math.imul(g,ae)|0)+Math.imul(p,oe)|0,o=o+Math.imul(p,ae)|0;var Ee=(u+(r=r+Math.imul(h,ce)|0)|0)+((8191&(i=(i=i+Math.imul(h,ue)|0)+Math.imul(f,ce)|0))<<13)|0;u=((o=o+Math.imul(f,ue)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(R,z),i=(i=Math.imul(R,U))+Math.imul(N,z)|0,o=Math.imul(N,U),r=r+Math.imul(O,H)|0,i=(i=i+Math.imul(O,J)|0)+Math.imul(j,H)|0,o=o+Math.imul(j,J)|0,r=r+Math.imul(P,V)|0,i=(i=i+Math.imul(P,K)|0)+Math.imul(I,V)|0,o=o+Math.imul(I,K)|0,r=r+Math.imul(T,X)|0,i=(i=i+Math.imul(T,Y)|0)+Math.imul(C,X)|0,o=o+Math.imul(C,Y)|0,r=r+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(x,Z)|0,o=o+Math.imul(x,ee)|0,r=r+Math.imul(y,ne)|0,i=(i=i+Math.imul(y,re)|0)+Math.imul(S,ne)|0,o=o+Math.imul(S,re)|0,r=r+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,ae)|0)+Math.imul(w,oe)|0,o=o+Math.imul(w,ae)|0,r=r+Math.imul(g,ce)|0,i=(i=i+Math.imul(g,ue)|0)+Math.imul(p,ce)|0,o=o+Math.imul(p,ue)|0;var xe=(u+(r=r+Math.imul(h,he)|0)|0)+((8191&(i=(i=i+Math.imul(h,fe)|0)+Math.imul(f,he)|0))<<13)|0;u=((o=o+Math.imul(f,fe)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(D,z),i=(i=Math.imul(D,U))+Math.imul(F,z)|0,o=Math.imul(F,U),r=r+Math.imul(R,H)|0,i=(i=i+Math.imul(R,J)|0)+Math.imul(N,H)|0,o=o+Math.imul(N,J)|0,r=r+Math.imul(O,V)|0,i=(i=i+Math.imul(O,K)|0)+Math.imul(j,V)|0,o=o+Math.imul(j,K)|0,r=r+Math.imul(P,X)|0,i=(i=i+Math.imul(P,Y)|0)+Math.imul(I,X)|0,o=o+Math.imul(I,Y)|0,r=r+Math.imul(T,Z)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(C,Z)|0,o=o+Math.imul(C,ee)|0,r=r+Math.imul(E,ne)|0,i=(i=i+Math.imul(E,re)|0)+Math.imul(x,ne)|0,o=o+Math.imul(x,re)|0,r=r+Math.imul(y,oe)|0,i=(i=i+Math.imul(y,ae)|0)+Math.imul(S,oe)|0,o=o+Math.imul(S,ae)|0,r=r+Math.imul(m,ce)|0,i=(i=i+Math.imul(m,ue)|0)+Math.imul(w,ce)|0,o=o+Math.imul(w,ue)|0,r=r+Math.imul(g,he)|0,i=(i=i+Math.imul(g,fe)|0)+Math.imul(p,he)|0,o=o+Math.imul(p,fe)|0;var Me=(u+(r=r+Math.imul(h,ge)|0)|0)+((8191&(i=(i=i+Math.imul(h,pe)|0)+Math.imul(f,ge)|0))<<13)|0;u=((o=o+Math.imul(f,pe)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,r=Math.imul(D,H),i=(i=Math.imul(D,J))+Math.imul(F,H)|0,o=Math.imul(F,J),r=r+Math.imul(R,V)|0,i=(i=i+Math.imul(R,K)|0)+Math.imul(N,V)|0,o=o+Math.imul(N,K)|0,r=r+Math.imul(O,X)|0,i=(i=i+Math.imul(O,Y)|0)+Math.imul(j,X)|0,o=o+Math.imul(j,Y)|0,r=r+Math.imul(P,Z)|0,i=(i=i+Math.imul(P,ee)|0)+Math.imul(I,Z)|0,o=o+Math.imul(I,ee)|0,r=r+Math.imul(T,ne)|0,i=(i=i+Math.imul(T,re)|0)+Math.imul(C,ne)|0,o=o+Math.imul(C,re)|0,r=r+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,ae)|0,r=r+Math.imul(y,ce)|0,i=(i=i+Math.imul(y,ue)|0)+Math.imul(S,ce)|0,o=o+Math.imul(S,ue)|0,r=r+Math.imul(m,he)|0,i=(i=i+Math.imul(m,fe)|0)+Math.imul(w,he)|0,o=o+Math.imul(w,fe)|0;var Te=(u+(r=r+Math.imul(g,ge)|0)|0)+((8191&(i=(i=i+Math.imul(g,pe)|0)+Math.imul(p,ge)|0))<<13)|0;u=((o=o+Math.imul(p,pe)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(D,V),i=(i=Math.imul(D,K))+Math.imul(F,V)|0,o=Math.imul(F,K),r=r+Math.imul(R,X)|0,i=(i=i+Math.imul(R,Y)|0)+Math.imul(N,X)|0,o=o+Math.imul(N,Y)|0,r=r+Math.imul(O,Z)|0,i=(i=i+Math.imul(O,ee)|0)+Math.imul(j,Z)|0,o=o+Math.imul(j,ee)|0,r=r+Math.imul(P,ne)|0,i=(i=i+Math.imul(P,re)|0)+Math.imul(I,ne)|0,o=o+Math.imul(I,re)|0,r=r+Math.imul(T,oe)|0,i=(i=i+Math.imul(T,ae)|0)+Math.imul(C,oe)|0,o=o+Math.imul(C,ae)|0,r=r+Math.imul(E,ce)|0,i=(i=i+Math.imul(E,ue)|0)+Math.imul(x,ce)|0,o=o+Math.imul(x,ue)|0,r=r+Math.imul(y,he)|0,i=(i=i+Math.imul(y,fe)|0)+Math.imul(S,he)|0,o=o+Math.imul(S,fe)|0;var Ce=(u+(r=r+Math.imul(m,ge)|0)|0)+((8191&(i=(i=i+Math.imul(m,pe)|0)+Math.imul(w,ge)|0))<<13)|0;u=((o=o+Math.imul(w,pe)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(D,X),i=(i=Math.imul(D,Y))+Math.imul(F,X)|0,o=Math.imul(F,Y),r=r+Math.imul(R,Z)|0,i=(i=i+Math.imul(R,ee)|0)+Math.imul(N,Z)|0,o=o+Math.imul(N,ee)|0,r=r+Math.imul(O,ne)|0,i=(i=i+Math.imul(O,re)|0)+Math.imul(j,ne)|0,o=o+Math.imul(j,re)|0,r=r+Math.imul(P,oe)|0,i=(i=i+Math.imul(P,ae)|0)+Math.imul(I,oe)|0,o=o+Math.imul(I,ae)|0,r=r+Math.imul(T,ce)|0,i=(i=i+Math.imul(T,ue)|0)+Math.imul(C,ce)|0,o=o+Math.imul(C,ue)|0,r=r+Math.imul(E,he)|0,i=(i=i+Math.imul(E,fe)|0)+Math.imul(x,he)|0,o=o+Math.imul(x,fe)|0;var _e=(u+(r=r+Math.imul(y,ge)|0)|0)+((8191&(i=(i=i+Math.imul(y,pe)|0)+Math.imul(S,ge)|0))<<13)|0;u=((o=o+Math.imul(S,pe)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(D,Z),i=(i=Math.imul(D,ee))+Math.imul(F,Z)|0,o=Math.imul(F,ee),r=r+Math.imul(R,ne)|0,i=(i=i+Math.imul(R,re)|0)+Math.imul(N,ne)|0,o=o+Math.imul(N,re)|0,r=r+Math.imul(O,oe)|0,i=(i=i+Math.imul(O,ae)|0)+Math.imul(j,oe)|0,o=o+Math.imul(j,ae)|0,r=r+Math.imul(P,ce)|0,i=(i=i+Math.imul(P,ue)|0)+Math.imul(I,ce)|0,o=o+Math.imul(I,ue)|0,r=r+Math.imul(T,he)|0,i=(i=i+Math.imul(T,fe)|0)+Math.imul(C,he)|0,o=o+Math.imul(C,fe)|0;var Pe=(u+(r=r+Math.imul(E,ge)|0)|0)+((8191&(i=(i=i+Math.imul(E,pe)|0)+Math.imul(x,ge)|0))<<13)|0;u=((o=o+Math.imul(x,pe)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,r=Math.imul(D,ne),i=(i=Math.imul(D,re))+Math.imul(F,ne)|0,o=Math.imul(F,re),r=r+Math.imul(R,oe)|0,i=(i=i+Math.imul(R,ae)|0)+Math.imul(N,oe)|0,o=o+Math.imul(N,ae)|0,r=r+Math.imul(O,ce)|0,i=(i=i+Math.imul(O,ue)|0)+Math.imul(j,ce)|0,o=o+Math.imul(j,ue)|0,r=r+Math.imul(P,he)|0,i=(i=i+Math.imul(P,fe)|0)+Math.imul(I,he)|0,o=o+Math.imul(I,fe)|0;var Ie=(u+(r=r+Math.imul(T,ge)|0)|0)+((8191&(i=(i=i+Math.imul(T,pe)|0)+Math.imul(C,ge)|0))<<13)|0;u=((o=o+Math.imul(C,pe)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(D,oe),i=(i=Math.imul(D,ae))+Math.imul(F,oe)|0,o=Math.imul(F,ae),r=r+Math.imul(R,ce)|0,i=(i=i+Math.imul(R,ue)|0)+Math.imul(N,ce)|0,o=o+Math.imul(N,ue)|0,r=r+Math.imul(O,he)|0,i=(i=i+Math.imul(O,fe)|0)+Math.imul(j,he)|0,o=o+Math.imul(j,fe)|0;var Ae=(u+(r=r+Math.imul(P,ge)|0)|0)+((8191&(i=(i=i+Math.imul(P,pe)|0)+Math.imul(I,ge)|0))<<13)|0;u=((o=o+Math.imul(I,pe)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(D,ce),i=(i=Math.imul(D,ue))+Math.imul(F,ce)|0,o=Math.imul(F,ue),r=r+Math.imul(R,he)|0,i=(i=i+Math.imul(R,fe)|0)+Math.imul(N,he)|0,o=o+Math.imul(N,fe)|0;var Oe=(u+(r=r+Math.imul(O,ge)|0)|0)+((8191&(i=(i=i+Math.imul(O,pe)|0)+Math.imul(j,ge)|0))<<13)|0;u=((o=o+Math.imul(j,pe)|0)+(i>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,r=Math.imul(D,he),i=(i=Math.imul(D,fe))+Math.imul(F,he)|0,o=Math.imul(F,fe);var je=(u+(r=r+Math.imul(R,ge)|0)|0)+((8191&(i=(i=i+Math.imul(R,pe)|0)+Math.imul(N,ge)|0))<<13)|0;u=((o=o+Math.imul(N,pe)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863;var $e=(u+(r=Math.imul(D,ge))|0)+((8191&(i=(i=Math.imul(D,pe))+Math.imul(F,ge)|0))<<13)|0;return u=((o=Math.imul(F,pe))+(i>>>13)|0)+($e>>>26)|0,$e&=67108863,c[0]=be,c[1]=me,c[2]=we,c[3]=ve,c[4]=ye,c[5]=Se,c[6]=ke,c[7]=Ee,c[8]=xe,c[9]=Me,c[10]=Te,c[11]=Ce,c[12]=_e,c[13]=Pe,c[14]=Ie,c[15]=Ae,c[16]=Oe,c[17]=je,c[18]=$e,0!==u&&(c[19]=u,n.length++),n};function p(e,t,n){return(new b).mulp(e,t,n)}function b(e,t){this.x=e,this.y=t}Math.imul||(g=d),o.prototype.mulTo=function(e,t){var n,r=this.length+e.length;return n=10===this.length&&10===e.length?g(this,e,t):r<63?d(this,e,t):r<1024?function(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,i=0,o=0;o<n.length-1;o++){var a=i;i=0;for(var s=67108863&r,c=Math.min(o,t.length-1),u=Math.max(0,o-e.length+1);u<=c;u++){var l=o-u,h=(0|e.words[l])*(0|t.words[u]),f=67108863&h;s=67108863&(f=f+s|0),i+=(a=(a=a+(h/67108864|0)|0)+(f>>>26)|0)>>>26,a&=67108863}n.words[o]=s,r=a,a=i}return 0!==r?n.words[o]=r:n.length--,n.strip()}(this,e,t):p(this,e,t),n},b.prototype.makeRBT=function(e){for(var t=new Array(e),n=o.prototype._countBits(e)-1,r=0;r<e;r++)t[r]=this.revBin(r,n,e);return t},b.prototype.revBin=function(e,t,n){if(0===e||e===n-1)return e;for(var r=0,i=0;i<t;i++)r|=(1&e)<<t-i-1,e>>=1;return r},b.prototype.permute=function(e,t,n,r,i,o){for(var a=0;a<o;a++)r[a]=t[e[a]],i[a]=n[e[a]]},b.prototype.transform=function(e,t,n,r,i,o){this.permute(o,e,t,n,r,i);for(var a=1;a<i;a<<=1)for(var s=a<<1,c=Math.cos(2*Math.PI/s),u=Math.sin(2*Math.PI/s),l=0;l<i;l+=s)for(var h=c,f=u,d=0;d<a;d++){var g=n[l+d],p=r[l+d],b=n[l+d+a],m=r[l+d+a],w=h*b-f*m;m=h*m+f*b,b=w,n[l+d]=g+b,r[l+d]=p+m,n[l+d+a]=g-b,r[l+d+a]=p-m,d!==s&&(w=c*h-u*f,f=c*f+u*h,h=w)}},b.prototype.guessLen13b=function(e,t){var n=1|Math.max(t,e),r=1&n,i=0;for(n=n/2|0;n;n>>>=1)i++;return 1<<i+1+r},b.prototype.conjugate=function(e,t,n){if(!(n<=1))for(var r=0;r<n/2;r++){var i=e[r];e[r]=e[n-r-1],e[n-r-1]=i,i=t[r],t[r]=-t[n-r-1],t[n-r-1]=-i}},b.prototype.normalize13b=function(e,t){for(var n=0,r=0;r<t/2;r++){var i=8192*Math.round(e[2*r+1]/t)+Math.round(e[2*r]/t)+n;e[r]=67108863&i,n=i<67108864?0:i/67108864|0}return e},b.prototype.convert13b=function(e,t,n,i){for(var o=0,a=0;a<t;a++)o+=0|e[a],n[2*a]=8191&o,o>>>=13,n[2*a+1]=8191&o,o>>>=13;for(a=2*t;a<i;++a)n[a]=0;r(0===o),r(!(-8192&o))},b.prototype.stub=function(e){for(var t=new Array(e),n=0;n<e;n++)t[n]=0;return t},b.prototype.mulp=function(e,t,n){var r=2*this.guessLen13b(e.length,t.length),i=this.makeRBT(r),o=this.stub(r),a=new Array(r),s=new Array(r),c=new Array(r),u=new Array(r),l=new Array(r),h=new Array(r),f=n.words;f.length=r,this.convert13b(e.words,e.length,a,r),this.convert13b(t.words,t.length,u,r),this.transform(a,o,s,c,r,i),this.transform(u,o,l,h,r,i);for(var d=0;d<r;d++){var g=s[d]*l[d]-c[d]*h[d];c[d]=s[d]*h[d]+c[d]*l[d],s[d]=g}return this.conjugate(s,c,r),this.transform(s,c,f,o,r,i),this.conjugate(f,o,r),this.normalize13b(f,r),n.negative=e.negative^t.negative,n.length=e.length+t.length,n.strip()},o.prototype.mul=function(e){var t=new o(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},o.prototype.mulf=function(e){var t=new o(null);return t.words=new Array(this.length+e.length),p(this,e,t)},o.prototype.imul=function(e){return this.clone().mulTo(e,this)},o.prototype.imuln=function(e){r("number"==typeof e),r(e<67108864);for(var t=0,n=0;n<this.length;n++){var i=(0|this.words[n])*e,o=(67108863&i)+(67108863&t);t>>=26,t+=i/67108864|0,t+=o>>>26,this.words[n]=67108863&o}return 0!==t&&(this.words[n]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n<t.length;n++){var r=n/26|0,i=n%26;t[n]=(e.words[r]&1<<i)>>>i}return t}(e);if(0===t.length)return new o(1);for(var n=this,r=0;r<t.length&&0===t[r];r++,n=n.sqr());if(++r<t.length)for(var i=n.sqr();r<t.length;r++,i=i.sqr())0!==t[r]&&(n=n.mul(i));return n},o.prototype.iushln=function(e){r("number"==typeof e&&e>=0);var t,n=e%26,i=(e-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var a=0;for(t=0;t<this.length;t++){var s=this.words[t]&o,c=(0|this.words[t])-s<<n;this.words[t]=c|a,a=s>>>26-n}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t<i;t++)this.words[t]=0;this.length+=i}return this.strip()},o.prototype.ishln=function(e){return r(0===this.negative),this.iushln(e)},o.prototype.iushrn=function(e,t,n){var i;r("number"==typeof e&&e>=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<<o,c=n;if(i-=a,i=Math.max(0,i),c){for(var u=0;u<a;u++)c.words[u]=this.words[u];c.length=a}if(0===a);else if(this.length>a)for(this.length-=a,u=0;u<this.length;u++)this.words[u]=this.words[u+a];else this.words[0]=0,this.length=1;var l=0;for(u=this.length-1;u>=0&&(0!==l||u>=i);u--){var h=0|this.words[u];this.words[u]=l<<26-o|h>>>o,l=h&s}return c&&0!==l&&(c.words[c.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,n){return r(0===this.negative),this.iushrn(e,t,n)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){r("number"==typeof e&&e>=0);var t=e%26,n=(e-t)/26,i=1<<t;return!(this.length<=n||!(this.words[n]&i))},o.prototype.imaskn=function(e){r("number"==typeof e&&e>=0);var t=e%26,n=(e-t)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==t&&n++,this.length=Math.min(n,this.length),0!==t){var i=67108863^67108863>>>t<<t;this.words[this.length-1]&=i}return this.strip()},o.prototype.maskn=function(e){return this.clone().imaskn(e)},o.prototype.iaddn=function(e){return r("number"==typeof e),r(e<67108864),e<0?this.isubn(-e):0!==this.negative?1===this.length&&(0|this.words[0])<e?(this.words[0]=e-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(e),this.negative=1,this):this._iaddn(e)},o.prototype._iaddn=function(e){this.words[0]+=e;for(var t=0;t<this.length&&this.words[t]>=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(r("number"==typeof e),r(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=67108864,this.words[t+1]-=1;return this.strip()},o.prototype.addn=function(e){return this.clone().iaddn(e)},o.prototype.subn=function(e){return this.clone().isubn(e)},o.prototype.iabs=function(){return this.negative=0,this},o.prototype.abs=function(){return this.clone().iabs()},o.prototype._ishlnsubmul=function(e,t,n){var i,o,a=e.length+n;this._expand(a);var s=0;for(i=0;i<e.length;i++){o=(0|this.words[i+n])+s;var c=(0|e.words[i])*t;s=((o-=67108863&c)>>26)-(c/67108864|0),this.words[i+n]=67108863&o}for(;i<this.length-n;i++)s=(o=(0|this.words[i+n])+s)>>26,this.words[i+n]=67108863&o;if(0===s)return this.strip();for(r(-1===s),s=0,i=0;i<this.length;i++)s=(o=-(0|this.words[i])+s)>>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),i=e,a=0|i.words[i.length-1];0!=(n=26-this._countBits(a))&&(i=i.ushln(n),r.iushln(n),a=0|i.words[i.length-1]);var s,c=r.length-i.length;if("mod"!==t){(s=new o(null)).length=c+1,s.words=new Array(s.length);for(var u=0;u<s.length;u++)s.words[u]=0}var l=r.clone()._ishlnsubmul(i,1,c);0===l.negative&&(r=l,s&&(s.words[c]=1));for(var h=c-1;h>=0;h--){var f=67108864*(0|r.words[i.length+h])+(0|r.words[i.length+h-1]);for(f=Math.min(f/a|0,67108863),r._ishlnsubmul(i,f,h);0!==r.negative;)f--,r.negative=0,r._ishlnsubmul(i,1,h),r.isZero()||(r.negative^=1);s&&(s.words[h]=f)}return s&&s.strip(),r.strip(),"div"!==t&&0!==n&&r.iushrn(n),{div:s||null,mod:r}},o.prototype.divmod=function(e,t,n){return r(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),n&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):this.negative&e.negative?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),n&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var n=0!==t.div.negative?t.mod.isub(e):t.mod,r=e.ushrn(1),i=e.andln(1),o=n.cmp(r);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){r(e<=67108863);for(var t=(1<<26)%e,n=0,i=this.length-1;i>=0;i--)n=(t*n+(0|this.words[i]))%e;return n},o.prototype.idivn=function(e){r(e<=67108863);for(var t=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*t;this.words[n]=i/e|0,t=i%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),c=new o(1),u=0;t.isEven()&&n.isEven();)t.iushrn(1),n.iushrn(1),++u;for(var l=n.clone(),h=t.clone();!t.isZero();){for(var f=0,d=1;!(t.words[0]&d)&&f<26;++f,d<<=1);if(f>0)for(t.iushrn(f);f-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(l),a.isub(h)),i.iushrn(1),a.iushrn(1);for(var g=0,p=1;!(n.words[0]&p)&&g<26;++g,p<<=1);if(g>0)for(n.iushrn(g);g-- >0;)(s.isOdd()||c.isOdd())&&(s.iadd(l),c.isub(h)),s.iushrn(1),c.iushrn(1);t.cmp(n)>=0?(t.isub(n),i.isub(s),a.isub(c)):(n.isub(t),s.isub(i),c.isub(a))}return{a:s,b:c,gcd:n.iushln(u)}},o.prototype._invmp=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),c=n.clone();t.cmpn(1)>0&&n.cmpn(1)>0;){for(var u=0,l=1;!(t.words[0]&l)&&u<26;++u,l<<=1);if(u>0)for(t.iushrn(u);u-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);for(var h=0,f=1;!(n.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(n.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);t.cmp(n)>=0?(t.isub(n),a.isub(s)):(n.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),n=e.clone();t.negative=0,n.negative=0;for(var r=0;t.isEven()&&n.isEven();r++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var i=t.cmp(n);if(i<0){var o=t;t=n,n=o}else if(0===i||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return!(1&this.words[0])},o.prototype.isOdd=function(){return!(1&~this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){r("number"==typeof e);var t=e%26,n=(e-t)/26,i=1<<t;if(this.length<=n)return this._expand(n+1),this.words[n]|=i,this;for(var o=i,a=n;0!==o&&a<this.length;a++){var s=0|this.words[a];o=(s+=o)>>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,n=e<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)t=1;else{n&&(e=-e),r(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:i<e?-1:1}return 0!==this.negative?0|-t:t},o.prototype.cmp=function(e){if(0!==this.negative&&0===e.negative)return-1;if(0===this.negative&&0!==e.negative)return 1;var t=this.ucmp(e);return 0!==this.negative?0|-t:t},o.prototype.ucmp=function(e){if(this.length>e.length)return 1;if(this.length<e.length)return-1;for(var t=0,n=this.length-1;n>=0;n--){var r=0|this.words[n],i=0|e.words[n];if(r!==i){r<i?t=-1:r>i&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new E(e)},o.prototype.toRed=function(e){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return r(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return r(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var m={k256:null,p224:null,p192:null,p25519:null};function w(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){w.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function y(){w.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function S(){w.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function k(){w.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function E(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else r(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function x(e){E.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}w.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},w.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var r=t<this.n?-1:n.ucmp(this.p);return 0===r?(n.words[0]=0,n.length=1):r>0?n.isub(this.p):void 0!==n.strip?n.strip():n._strip(),n},w.prototype.split=function(e,t){e.iushrn(this.n,0,t)},w.prototype.imulK=function(e){return e.imul(this.k)},i(v,w),v.prototype.split=function(e,t){for(var n=4194303,r=Math.min(e.length,9),i=0;i<r;i++)t.words[i]=e.words[i];if(t.length=r,e.length<=9)return e.words[0]=0,void(e.length=1);var o=e.words[9];for(t.words[t.length++]=o&n,i=10;i<e.length;i++){var a=0|e.words[i];e.words[i-10]=(a&n)<<4|o>>>22,o=a}o>>>=22,e.words[i-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},v.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n<e.length;n++){var r=0|e.words[n];t+=977*r,e.words[n]=67108863&t,t=64*r+(t/67108864|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},i(y,w),i(S,w),i(k,w),k.prototype.imulK=function(e){for(var t=0,n=0;n<e.length;n++){var r=19*(0|e.words[n])+t,i=67108863&r;r>>>=26,e.words[n]=i,t=r}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(m[e])return m[e];var t;if("k256"===e)t=new v;else if("p224"===e)t=new y;else if("p192"===e)t=new S;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new k}return m[e]=t,t},E.prototype._verify1=function(e){r(0===e.negative,"red works only with positives"),r(e.red,"red works only with red numbers")},E.prototype._verify2=function(e,t){r(!(e.negative|t.negative),"red works only with positives"),r(e.red&&e.red===t.red,"red works only with red numbers")},E.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},E.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},E.prototype.add=function(e,t){this._verify2(e,t);var n=e.add(t);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},E.prototype.iadd=function(e,t){this._verify2(e,t);var n=e.iadd(t);return n.cmp(this.m)>=0&&n.isub(this.m),n},E.prototype.sub=function(e,t){this._verify2(e,t);var n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},E.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},E.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},E.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},E.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},E.prototype.isqr=function(e){return this.imul(e,e.clone())},E.prototype.sqr=function(e){return this.mul(e,e)},E.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(r(t%2==1),3===t){var n=this.m.add(new o(1)).iushrn(2);return this.pow(e,n)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);r(!i.isZero());var s=new o(1).toRed(this),c=s.redNeg(),u=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new o(2*l*l).toRed(this);0!==this.pow(l,u).cmp(c);)l.redIAdd(c);for(var h=this.pow(l,i),f=this.pow(e,i.addn(1).iushrn(1)),d=this.pow(e,i),g=a;0!==d.cmp(s);){for(var p=d,b=0;0!==p.cmp(s);b++)p=p.redSqr();r(b<g);var m=this.pow(h,new o(1).iushln(g-b-1));f=f.redMul(m),h=m.redSqr(),d=d.redMul(h),g=b}return f},E.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},E.prototype.pow=function(e,t){if(t.isZero())return new o(1).toRed(this);if(0===t.cmpn(1))return e.clone();var n=new Array(16);n[0]=new o(1).toRed(this),n[1]=e;for(var r=2;r<n.length;r++)n[r]=this.mul(n[r-1],e);var i=n[0],a=0,s=0,c=t.bitLength()%26;for(0===c&&(c=26),r=t.length-1;r>=0;r--){for(var u=t.words[r],l=c-1;l>=0;l--){var h=u>>l&1;i!==n[0]&&(i=this.sqr(i)),0!==h||0!==a?(a<<=1,a|=h,(4==++s||0===r&&0===l)&&(i=this.mul(i,n[a]),s=0,a=0)):s=0}c=26}return i},E.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},E.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new x(e)},i(x,E),x.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},x.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},x.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},x.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},x.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e=n.nmd(e),this)},33532:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isObjectEmpty=function(e){if(!e)return!0;for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}},33787:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default={width:function e(t){var n;let r=0;return t?(void 0===t.fields||(r+=t.fields.length,r+=t.fields.map((t=>e(t.types.find((e=>"Document"===e.name))))).reduce(((e,t)=>e+t||0),0),r+=null!==(n=t.fields.map((t=>{const n=t.types.find((e=>"Array"===e.name));if(n)return e(n.types.find((e=>"Document"===e.name)))})).reduce(((e,t)=>(null!=e?e:0)+(null!=t?t:0)||0),0))&&void 0!==n?n:0),r):r},depth:function e(t){if(!t)return 0;let n=0;return void 0!==t.fields&&t.fields.length>0&&(n=1+Math.max(Math.max(...t.fields.map((t=>e(t.types.find((e=>"Document"===e.name)))))),Math.max(...t.fields.map((t=>{const n=t.types.find((e=>"Array"===e.name));return n?e(n.types.find((e=>"Document"===e.name))):0}))))),n},branch:function e(t){const n=[];let r;return t?(void 0!==t.fields&&t.fields.length>0&&(n.push(t.fields.length),r=t.fields.map((function(t){return e(t.types.find((e=>"Document"===e.name)))})),n.push(...r.flat(1/0)),r=t.fields.map((function(t){const n=t.types.find((e=>"Array"===e.name));return n?e(n.types.find((e=>"Document"===e.name))):[]})),n.push(...r.flat(1/0))),n.sort().reverse()):n}}},33859:(e,t)=>{function n(e){return e.bsonType||e.type}function r(e,t){if(null==e)throw new Error(t)}function i(e){const t=n(e),r=(Array.isArray(t)?t:[null!=t?t:"any"]).map((e=>function(e){switch(e){case"string":return"string";case"number":case"integer":return"number";case"boolean":case"bool":return"boolean";case"null":return"null";case"double":return["bson.Double","number"];case"binData":return"bson.Binary";case"objectId":return"bson.ObjectId";case"date":return"bson.Date";case"regex":return"bson.BSONRegExp";case"symbol":return"bson.BSONSymbol";case"javascript":case"javascriptWithScope":return"bson.Code";case"int":return["bson.Int32","number"];case"timestamp":return"bson.Timestamp";case"long":return["bson.Long","number"];case"decimal":return"bson.Decimal128";case"minKey":return"bson.MinKey";case"maxKey":return"bson.MaxKey";case"dbPointer":return"bson.DBPointer";case"undefined":return"undefined";default:return"any"}}(e))).flat();return new Set(r.flat())}function o(e){const t=[];for(let n=0;n<e;n++)t.push(" ");return t.join("")}function a(e,t){return`{\n${Object.entries(e).map((([e,s])=>{switch(n(s)){case"array":return r(s.items,"schema.items must be defined"),`${o(t)}${e}?: ${c=[...i(s.items)],1===c.length?`${c[0]}[]`:`${c.join(" | ")})[]`}`;case"object":return r(s.properties,"schema.properties must be defined"),`${o(t)}${e}?: ${a(s.properties,t+1)}`;default:return`${o(t)}${e}?: ${[...i(s)].join(" | ")}`}var c})).join(";\n")};\n${o(t-1)}}`}Object.defineProperty(t,"__esModule",{value:!0}),t.toTypescriptTypeDefinition=void 0,t.toTypescriptTypeDefinition=function(e){return r(e.properties,"schema.properties must be defined"),a(e.properties,1)}},34557:e=>{e.exports=JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},34995:function(e,t,n){var r,i=n(67787).Buffer,o=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=r(e),i=0;i<n.length;i++)"default"!==n[i]&&o(t,e,n[i]);return a(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.GLOBAL_FUNCTIONS=t.GLOBALS=void 0,t.getScopeFunction=function(e,t){if(t&&f[e])return f[e];if(!t&&h[e])return h[e];if(d[e])return d[e];throw new Error(`Attempted to access scope property '${e}' that doesn't exist`)},t.isMethodWhitelisted=function(e,t){if(Object.prototype.hasOwnProperty.call(g,e)){const n=g[e].allowedMethods;return"string"==typeof n?g[n].allowedMethods[t]:n[t]}return!1},t.getClass=function(e){if(Object.prototype.hasOwnProperty.call(g,e))return g[e].class;throw new Error(`Attempted to access member '${e}' that doesn't exist`)};const c=s(n(62444));function u(e){return Object.freeze(Object.create(null,Object.getOwnPropertyDescriptors(e)))}function l(e){return"string"==typeof e?c.Long.fromString(e):c.Long.fromNumber(e)}const h=u({Date:function(...e){return Date(...e)}}),f=u({Date:function(...e){return new Date(...e)}}),d=u({RegExp,Binary:function(e,t){return new c.Binary(e,t)},LegacyJavaUUID:function(e){void 0===e&&(e=(new c.UUID).toHexString());let t=String.prototype.replace.call(e,/[{}-]/g,(()=>"")),n=String.prototype.substring.call(t,0,16),r=String.prototype.substring.call(t,16,32);n=String.prototype.substring.call(n,14,16)+String.prototype.substring.call(n,12,14)+String.prototype.substring.call(n,10,12)+String.prototype.substring.call(n,8,10)+String.prototype.substring.call(n,6,8)+String.prototype.substring.call(n,4,6)+String.prototype.substring.call(n,2,4)+String.prototype.substring.call(n,0,2),r=String.prototype.substring.call(r,14,16)+String.prototype.substring.call(r,12,14)+String.prototype.substring.call(r,10,12)+String.prototype.substring.call(r,8,10)+String.prototype.substring.call(r,6,8)+String.prototype.substring.call(r,4,6)+String.prototype.substring.call(r,2,4)+String.prototype.substring.call(r,0,2),t=n+r;const o=i.from(t,"hex");return new c.Binary(o,3)},LegacyCSharpUUID:function(e){void 0===e&&(e=(new c.UUID).toHexString());let t=String.prototype.replace.call(e,/[{}-]/g,(()=>""));t=String.prototype.substring.call(t,6,8)+String.prototype.substring.call(t,4,6)+String.prototype.substring.call(t,2,4)+String.prototype.substring.call(t,0,2)+(String.prototype.substring.call(t,10,12)+String.prototype.substring.call(t,8,10))+(String.prototype.substring.call(t,14,16)+String.prototype.substring.call(t,12,14))+String.prototype.substring.call(t,16,32);const n=i.from(t,"hex");return new c.Binary(n,3)},LegacyPythonUUID:function(e){return void 0===e?new c.Binary((new c.UUID).toBinary().buffer,3):new c.Binary(i.from(String.prototype.replace.call(e,/[{}-]/g,(()=>"")),"hex"),3)},BinData:function(e,t){return new c.Binary(i.from(t,"base64"),e)},UUID:function(e){return void 0===e?(new c.UUID).toBinary():new c.Binary(i.from(e.replace(/-/g,""),"hex"),4)},Code:function(e,t){return new c.Code(e,t)},DBRef:function(e,t,n,r){return new c.DBRef(e,t,n,r)},Decimal128:function(e){return c.Decimal128.fromString(e)},NumberDecimal:function(e){return c.Decimal128.fromString(e)},Double:function(e){return new c.Double(e)},Int32:function(e){return new c.Int32(e)},NumberInt:function(e){return new c.Int32(e)},Long:function(e,t){return new c.Long(e,t)},NumberLong:l,Int64:l,Map:function(e){return new(c.Map??Map)(e)},MaxKey:function(){return new c.MaxKey},MinKey:function(){return new c.MinKey},ObjectID:function(e){return new c.ObjectId(e)},ObjectId:function(e){return new c.ObjectId(e)},Symbol:function(e){return new c.BSONSymbol(e)},Timestamp:function(e,t){return"number"==typeof e&&"number"==typeof t||void 0!==t?new c.Timestamp({t:e,i:t}):new c.Timestamp(e)},ISODate:function(e){if(void 0===e)return new Date;if("string"!=typeof e)return new Date(e);const t=e.match(/^(?<Y>\d{4})-?(?<M>\d{2})-?(?<D>\d{2})([T ](?<h>\d{2})(:?(?<m>\d{2})(:?((?<s>\d{2})(\.(?<ms>\d+))?))?)?(?<tz>Z|([+-])(\d{2}):?(\d{2})?)?)?$/);if(null!==t&&void 0!==t.groups){const{Y:e,M:n,D:r,h:i,m:o,s:a,ms:s,tz:c}=t.groups,u=new Date(`${e}-${n}-${r}T${i||"00"}:${o||"00"}:${a||"00"}.${s||"000"}${c||"Z"}`);if(u.getTime()>=-621672192e5&&u.getTime()<=0xe677d21fdbff)return u}throw new Error(`${JSON.stringify(e)} is not a valid ISODate`)}});t.GLOBALS=u({Infinity:1/0,NaN:NaN,undefined:void 0});const g=u({Math:u({class:Math,allowedMethods:u({abs:!0,acos:!0,acosh:!0,asin:!0,asinh:!0,atan:!0,atan2:!0,atanh:!0,cbrt:!0,ceil:!0,clz32:!0,cos:!0,cosh:!0,exp:!0,expm1:!0,floor:!0,fround:!0,hypot:!0,imul:!0,log:!0,log10:!0,log1p:!0,log2:!0,max:!0,min:!0,pow:!0,round:!0,sign:!0,sin:!0,sinh:!0,sqrt:!0,tan:!0,tanh:!0,trunc:!0})}),Date:u({class:Date,allowedMethods:u({getDate:!0,getDay:!0,getFullYear:!0,getHours:!0,getMilliseconds:!0,getMinutes:!0,getMonth:!0,getSeconds:!0,getTime:!0,getTimezoneOffset:!0,getUTCDate:!0,getUTCDay:!0,getUTCFullYear:!0,getUTCHours:!0,getUTCMilliseconds:!0,getUTCMinutes:!0,getUTCMonth:!0,getUTCSeconds:!0,getYear:!0,now:!0,setDate:!0,setFullYear:!0,setHours:!0,setMilliseconds:!0,setMinutes:!0,setMonth:!0,setSeconds:!0,setTime:!0,setUTCDate:!0,setUTCFullYear:!0,setUTCHours:!0,setUTCMilliseconds:!0,setUTCMinutes:!0,setUTCMonth:!0,setUTCSeconds:!0,setYear:!0,toISOString:!0,valueOf:!0})}),ISODate:u({class:Date,allowedMethods:"Date"}),Binary:u({class:c.Binary,allowedMethods:{createFromHexString:!0,createFromBase64:!0}})});t.GLOBAL_FUNCTIONS=Object.freeze([...Object.keys(d),...Object.keys(f),...Object.keys(h)])},35902:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ExportsManager=t.jsonExportFormat=void 0,t.decodeAndNormalize=g,t.ensureExtension=p,t.isExportExpired=b;const i=r(n(69761)),o=r(n(17642)),a=r(n(65981)),s=r(n(8763)),c=n(36374),u=n(62444),l=n(93874),h=n(2444),f=n(45584);t.jsonExportFormat=i.default.enum(["relaxed","canonical"]);class d extends s.default{constructor(e,t,n){super(),this.exportsDirectoryPath=e,this.config=t,this.logger=n,this.storedExports={},this.exportsCleanupInProgress=!1,this.shutdownController=new AbortController}get availableExports(){return this.assertIsNotShuttingDown(),Object.values(this.storedExports).filter((e=>"ready"===e.exportStatus&&!b(e.exportCreatedAt,this.config.exportTimeoutMs))).map((({exportName:e,exportTitle:t,exportURI:n,exportPath:r})=>({exportName:e,exportTitle:t,exportURI:n,exportPath:r})))}init(){this.exportsCleanupInterval||(this.exportsCleanupInterval=setInterval((()=>{this.cleanupExpiredExports()}),this.config.exportCleanupIntervalMs))}async close(){if(!this.shutdownController.signal.aborted)try{clearInterval(this.exportsCleanupInterval),this.shutdownController.abort(),await a.default.rm(this.exportsDirectoryPath,{force:!0,recursive:!0}),this.emit("closed")}catch(e){this.logger.error({id:f.LogId.exportCloseError,context:"Error while closing ExportsManager",message:e instanceof Error?e.message:String(e)})}}async readExport(e){try{this.assertIsNotShuttingDown(),e=g(e);const t=this.storedExports[e];if(!t)throw new Error("Requested export has either expired or does not exist.");if("in-progress"===t.exportStatus)throw new Error("Requested export is still being generated. Try again later.");const{exportPath:n,docsTransformed:r}=t;return{content:await a.default.readFile(n,{encoding:"utf8",signal:this.shutdownController.signal}),docsTransformed:r}}catch(t){throw this.logger.error({id:f.LogId.exportReadError,context:`Error when reading export - ${e}`,message:t instanceof Error?t.message:String(t)}),t}}async createJSONExport({input:e,exportName:t,exportTitle:n,jsonExportFormat:r}){try{this.assertIsNotShuttingDown();const i=g(p(t,"json"));if(this.storedExports[i])return Promise.reject(new Error("Export with same name is either already available or being generated."));const a=`exported-data://${encodeURIComponent(i)}`,s=o.default.join(this.exportsDirectoryPath,i),c=this.storedExports[i]={exportName:i,exportTitle:n,exportPath:s,exportURI:a,exportStatus:"in-progress"};return this.startExport({input:e,jsonExportFormat:r,inProgressExport:c}),Promise.resolve(c)}catch(e){throw this.logger.error({id:f.LogId.exportCreationError,context:"Error when registering JSON export request",message:e instanceof Error?e.message:String(e)}),e}}async startExport({input:e,jsonExportFormat:t,inProgressExport:n}){try{let r=!1,i=0;try{await a.default.mkdir(this.exportsDirectoryPath,{recursive:!0});const o=(0,c.createWriteStream)(n.exportPath),s=this.docToEJSONStream(this.getEJSONOptionsForFormat(t));await(0,h.pipeline)([e.stream(),s,o],{signal:this.shutdownController.signal}),i=s.docsTransformed,r=!0}catch(e){throw delete this.storedExports[n.exportName],this.silentlyRemoveExport(n.exportPath,f.LogId.exportCreationCleanupError,`Error when removing incomplete export ${n.exportName}`),e}finally{r&&(this.storedExports[n.exportName]={...n,exportCreatedAt:Date.now(),exportStatus:"ready",docsTransformed:i},this.emit("export-available",n.exportURI)),e.close()}}catch(e){this.logger.error({id:f.LogId.exportCreationError,context:`Error when generating JSON export for ${n.exportName}`,message:e instanceof Error?e.message:String(e)})}}getEJSONOptionsForFormat(e){switch(e){case"relaxed":return{relaxed:!0};case"canonical":return{relaxed:!1};default:return}}docToEJSONStream(e){let t=0;const n=Object.assign(new l.Transform({objectMode:!0,transform(n,r,i){try{const r=u.EJSON.stringify(n,void 0,void 0,e);0===t?this.push("["+r):this.push(",\n"+r),t++,i()}catch(e){i(e)}},flush(e){0===t?this.push("[]"):this.push("]"),n.docsTransformed=t,e()}}),{docsTransformed:t});return n}async cleanupExpiredExports(){if(!this.exportsCleanupInProgress){this.exportsCleanupInProgress=!0;try{const e=[];for(const t of Object.values(this.storedExports))"ready"===t.exportStatus&&b(t.exportCreatedAt,this.config.exportTimeoutMs)&&(e.push(t),delete this.storedExports[t.exportName]);const t=[];for(const{exportPath:n,exportName:r}of e)t.push(this.silentlyRemoveExport(n,f.LogId.exportCleanupError,`Considerable error when removing export ${r}`));await Promise.allSettled(t)}catch(e){this.logger.error({id:f.LogId.exportCleanupError,context:"Error when cleaning up exports",message:e instanceof Error?e.message:String(e)})}finally{this.exportsCleanupInProgress=!1}}}async silentlyRemoveExport(e,t,n){try{await a.default.unlink(e)}catch(e){"ENOENT"!==e.code&&this.logger.error({id:t,context:n,message:e instanceof Error?e.message:String(e)})}}assertIsNotShuttingDown(){if(this.shutdownController.signal.aborted)throw new Error("ExportsManager is shutting down.")}static init(e,t,n=(new u.ObjectId).toString()){const r=o.default.join(e.exportsPath,n),i=new d(r,e,t);return i.init(),i}}function g(e){return decodeURIComponent(e).normalize("NFKC")}function p(e,t){const n=t.startsWith(".")?t:`.${t}`;return e.endsWith(n)?e:`${e}${n}`}function b(e,t){return Date.now()-e>t}t.ExportsManager=d},35941:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CommonErrors=void 0,t.CommonErrors={InvalidArgument:"COMMON-10001",InvalidOperation:"COMMON-10002",Deprecated:"COMMON-10003",CommandFailed:"COMMON-10004",UnexpectedInternalError:"COMMON-90001",NotImplemented:"COMMON-90002"}},36019:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(78249),i=n(87351),o={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:e})=>r.str`must match "${e.ifClause}" schema`,params:({params:e})=>r._`{failingKeyword: ${e.ifClause}}`},code(e){const{gen:t,parentSchema:n,it:o}=e;void 0===n.then&&void 0===n.else&&(0,i.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const s=a(o,"then"),c=a(o,"else");if(!s&&!c)return;const u=t.let("valid",!0),l=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},l);e.mergeEvaluated(t)}(),e.reset(),s&&c){const n=t.let("ifClause");e.setParams({ifClause:n}),t.if(l,h("then",n),h("else",n))}else s?t.if(l,h("then")):t.if((0,r.not)(l),h("else"));function h(n,i){return()=>{const o=e.subschema({keyword:n},l);t.assign(u,l),e.mergeValidEvaluated(o,u),i?t.assign(i,r._`${n}`):e.setParams({ifClause:n})}}e.pass(u,(()=>e.error(!0)))}};function a(e,t){const n=e.schema[t];return void 0!==n&&!(0,i.alwaysValidSchema)(e,n)}t.default=o},36937:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;const r=n(68694),i=n(78249),o=i.operators,a={formatMaximum:{okStr:"<=",ok:o.LTE,fail:o.GT},formatMinimum:{okStr:">=",ok:o.GTE,fail:o.LT},formatExclusiveMaximum:{okStr:"<",ok:o.LT,fail:o.GTE},formatExclusiveMinimum:{okStr:">",ok:o.GT,fail:o.LTE}},s={message:({keyword:e,schemaCode:t})=>i.str`should be ${a[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>i._`{comparison: ${a[e].okStr}, limit: ${t}}`};t.formatLimitDefinition={keyword:Object.keys(a),type:"string",schemaType:"string",$data:!0,error:s,code(e){const{gen:t,data:n,schemaCode:o,keyword:s,it:c}=e,{opts:u,self:l}=c;if(!u.validateFormats)return;const h=new r.KeywordCxt(c,l.RULES.all.format.definition,"format");function f(e){return i._`${e}.compare(${n}, ${o}) ${a[s].fail} 0`}h.$data?function(){const n=t.scopeValue("formats",{ref:l.formats,code:u.code.formats}),r=t.const("fmt",i._`${n}[${h.schemaCode}]`);e.fail$data((0,i.or)(i._`typeof ${r} != "object"`,i._`${r} instanceof RegExp`,i._`typeof ${r}.compare != "function"`,f(r)))}():function(){const n=h.schema,r=l.formats[n];if(!r||!0===r)return;if("object"!=typeof r||r instanceof RegExp||"function"!=typeof r.compare)throw new Error(`"${s}": format "${n}" does not define "compare" function`);const o=t.scopeValue("formats",{key:n,ref:r,code:u.code.formats?i._`${u.code.formats}${(0,i.getProperty)(n)}`:void 0});e.fail$data(f(o))}()},dependencies:["format"]},t.default=e=>(e.addKeyword(t.formatLimitDefinition),e)},37057:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalSchemaBasedAccessor=void 0,t.InternalSchemaBasedAccessor=class{constructor(e,t){this.internalSchema=e,this.converters=t}async getInternalSchema(){return this.internalSchema}async getStandardJsonSchema(e={}){var t;return null!==(t=this.standardJSONSchema)&&void 0!==t?t:this.standardJSONSchema=await this.converters.internalToStandard(this.internalSchema,e)}async getMongoDBJsonSchema(e={}){var t;return null!==(t=this.mongodbJSONSchema)&&void 0!==t?t:this.mongodbJSONSchema=await this.converters.internalToMongoDB(this.internalSchema,e)}async getExpandedJSONSchema(e={}){var t;return null!==(t=this.expandedJSONSchema)&&void 0!==t?t:this.expandedJSONSchema=await this.converters.internalToExpanded(this.internalSchema,e)}}},37370:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CreateDBUserTool=t.CreateDBUserArgs=void 0;const r=n(69761),i=n(55415),o=n(56092),a=n(5853),s=n(14233);t.CreateDBUserArgs={projectId:s.AtlasArgs.projectId().describe("Atlas project ID"),username:s.AtlasArgs.username().describe("Username for the new user"),password:s.AtlasArgs.password().nullish().describe("Password for the new user. IMPORTANT: If the user hasn't supplied an explicit password, leave it unset and under no circumstances try to generate a random one. A secure password will be generated by the MCP server if necessary."),roles:r.z.array(r.z.object({roleName:s.CommonArgs.string().describe("Role name"),databaseName:s.CommonArgs.string().describe("Database name").default("admin"),collectionName:s.CommonArgs.string().describe("Collection name").optional()})).describe("Roles for the new user"),clusters:r.z.array(s.AtlasArgs.clusterName()).describe("Clusters to assign the user to, leave empty for access to all clusters").optional()};class c extends i.AtlasToolBase{constructor(){super(...arguments),this.name="atlas-create-db-user",this.description="Create an MongoDB Atlas database user",this.argsShape={...t.CreateDBUserArgs}}async execute({projectId:e,username:t,password:n,roles:r,clusters:i}){await(0,a.ensureCurrentIpInAccessList)(this.apiClient,e);const s=!n;s&&(n=await(0,o.generateSecurePassword)());const c={groupId:e,awsIAMType:"NONE",databaseName:"admin",ldapAuthType:"NONE",oidcAuthType:"NONE",x509Type:"NONE",username:t,password:n,roles:r,scopes:i?.length?i.map((e=>({type:"CLUSTER",name:e}))):void 0};return await this.apiClient.createDatabaseUser({params:{path:{groupId:e}},body:c}),this.session.keychain.register(t,"user"),n&&this.session.keychain.register(n,"password"),{content:[{type:"text",text:`User "${t}" created successfully${s?` with password: \`${n}\``:""}.`}]}}getConfirmationMessage({projectId:e,username:t,password:n,roles:r,clusters:i}){return`You are about to create a database user in Atlas project \`${e}\`:\n\n**Username**: \`${t}\`\n\n**Password**: ${n?"(User-provided password)":"(Auto-generated secure password)"}\n\n**Roles**: ${r.map((e=>`${e.roleName}${e.collectionName?` on ${e.databaseName}.${e.collectionName}`:` on ${e.databaseName}`}`)).join(", ")}\n\n**Cluster Access**: ${i?.length?i.join(", "):"All clusters in the project"}\n\nThis will create a new database user with the specified permissions. **Do you confirm the execution of the action?**`}}t.CreateDBUserTool=c,c.operationType="create"},37939:(e,t,n)=>{var r=n(9606).URL;Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectClusterTool=t.ConnectClusterArgs=void 0;const i=n(55415),o=n(56092),a=n(45584),s=n(30084),c=n(5853),u=n(20999),l=n(14233),h="Note: Your current IP address has been added to the Atlas project's IP access list to enable secure connection.",f="Note: A temporary user has been created to enable secure connection to the cluster. For more information, see https://dochub.mongodb.org/core/mongodb-mcp-server-tools-considerations\n\nNote to LLM Agent: it is important to include the following link in your response to the user in case they want to get more information about the temporary user created: https://dochub.mongodb.org/core/mongodb-mcp-server-tools-considerations";function d(e){return new Promise((t=>setTimeout(t,e)))}t.ConnectClusterArgs={projectId:l.AtlasArgs.projectId().describe("Atlas project ID"),clusterName:l.AtlasArgs.clusterName().describe("Atlas cluster name"),connectionType:l.AtlasArgs.connectionType().describe("Type of connection (standard, private, or privateEndpoint) to an Atlas cluster")};class g extends i.AtlasToolBase{constructor(){super(...arguments),this.name="atlas-connect-cluster",this.description="Connect to MongoDB Atlas cluster",this.argsShape=t.ConnectClusterArgs}queryConnection(e,t){if(!this.session.connectedAtlasCluster)return this.session.isConnectedToMongoDB?"connected-to-other-cluster":"disconnected";const n=this.session.connectionManager.currentConnectionState;if(this.session.connectedAtlasCluster.projectId!==e||this.session.connectedAtlasCluster.clusterName!==t)return"connected-to-other-cluster";switch(n.tag){case"connecting":case"disconnected":return"connecting";case"connected":return"connected";case"errored":return this.session.logger.debug({id:a.LogId.atlasConnectFailure,context:"atlas-connect-cluster",message:`error querying cluster: ${n.errorReason}`}),"unknown"}}async prepareClusterConnection(e,t,n="standard"){const i=await(0,s.inspectCluster)(this.apiClient,e,t);if(void 0===i.connectionStrings)throw new Error("Connection strings not available");const a=(0,s.getConnectionString)(i.connectionStrings,n);if(void 0===a)throw new Error(`Connection string for connection type "${n}" is not available. Please ensure this connection type is set up in Atlas. See https://www.mongodb.com/docs/atlas/connect-to-database-deployment/#connect-to-an-atlas-cluster.`);const c=`mcpUser${Math.floor(1e5*Math.random())}`,l=await(0,o.generateSecurePassword)(),h=new Date(Date.now()+this.config.atlasTemporaryDatabaseUserLifetimeMs),f=(0,u.getDefaultRoleFromConfig)(this.config);await this.apiClient.createDatabaseUser({params:{path:{groupId:e}},body:{databaseName:"admin",groupId:e,roles:[f],scopes:[{type:"CLUSTER",name:t}],username:c,password:l,awsIAMType:"NONE",ldapAuthType:"NONE",oidcAuthType:"NONE",x509Type:"NONE",deleteAfterDate:h.toISOString(),description:"MDB MCP Temporary user, see https://dochub.mongodb.org/core/mongodb-mcp-server-tools-considerations"}});const d={username:c,projectId:e,clusterName:t,expiryDate:h},g=new r(a);return g.username=c,g.password=l,g.searchParams.set("authSource","admin"),this.session.keychain.register(c,"user"),this.session.keychain.register(l,"password"),{connectionString:g.toString(),atlas:d}}async connectToCluster(e,t){let n;this.session.logger.debug({id:a.LogId.atlasConnectAttempt,context:"atlas-connect-cluster",message:`attempting to connect to cluster: ${this.session.connectedAtlasCluster?.clusterName}`,noRedaction:!0});for(let r=0;r<600;r++){try{n=void 0,await this.session.connectToMongoDB({connectionString:e,atlas:t});break}catch(e){const t=e instanceof Error?e:new Error(String(e));n=t,this.session.logger.debug({id:a.LogId.atlasConnectFailure,context:"atlas-connect-cluster",message:`error connecting to cluster: ${t.message}`}),await d(500)}if(!this.session.connectedAtlasCluster||this.session.connectedAtlasCluster.projectId!==t.projectId||this.session.connectedAtlasCluster.clusterName!==t.clusterName)throw new Error("Cluster connection aborted")}if(n)throw this.session.connectedAtlasCluster?.projectId===t.projectId&&this.session.connectedAtlasCluster?.clusterName===t.clusterName&&this.session.connectedAtlasCluster?.username&&this.apiClient.deleteDatabaseUser({params:{path:{groupId:this.session.connectedAtlasCluster.projectId,username:this.session.connectedAtlasCluster.username,databaseName:"admin"}}}).catch((e=>{const t=e instanceof Error?e:new Error(String(e));this.session.logger.debug({id:a.LogId.atlasConnectFailure,context:"atlas-connect-cluster",message:`error deleting database user: ${t.message}`})})),n;this.session.logger.debug({id:a.LogId.atlasConnectSucceeded,context:"atlas-connect-cluster",message:`connected to cluster: ${this.session.connectedAtlasCluster?.clusterName}`,noRedaction:!0})}async execute({projectId:e,clusterName:t,connectionType:n}){const r=await(0,c.ensureCurrentIpInAccessList)(this.apiClient,e);let i=!1;switch(this.queryConnection(e,t)){case"connected-to-other-cluster":case"disconnected":{await this.session.disconnect();const{connectionString:r,atlas:o}=await this.prepareClusterConnection(e,t,n);i=!0,this.connectToCluster(r,o).catch((e=>{const t=e instanceof Error?e:new Error(String(e));this.session.logger.error({id:a.LogId.atlasConnectFailure,context:"atlas-connect-cluster",message:`error connecting to cluster: ${t.message}`})}));break}}for(let n=0;n<60;n++){if("connected"===this.queryConnection(e,t)){const e=[{type:"text",text:`Connected to cluster "${t}".`}];return r&&e.push({type:"text",text:h}),i&&e.push({type:"text",text:f}),{content:e}}await d(500)}const o=[{type:"text",text:`Attempting to connect to cluster "${t}"...`},{type:"text",text:"Warning: Provisioning a user and connecting to the cluster may take more time, please check again in a few seconds."}];return r&&o.push({type:"text",text:h}),i&&o.push({type:"text",text:f}),{content:o}}resolveTelemetryMetadata(e,{result:t}){const n=super.resolveTelemetryMetadata(e,{result:t}),r=this.getConnectionInfoMetadata();return r&&void 0!==r.project_id&&delete n.project_id,{...n,...r}}}t.ConnectClusterTool=g,g.operationType="connect"},38679:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;const r=n(87351),i=n(16428),o=n(96422),a=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);t.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!c(e):!!t&&u(e)<=t)};const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function c(e){for(const t in e){if(s.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(c))return!0;if("object"==typeof n&&c(n))return!0}return!1}function u(e){let t=0;for(const n in e){if("$ref"===n)return 1/0;if(t++,!a.has(n)&&("object"==typeof e[n]&&(0,r.eachItem)(e[n],(e=>t+=u(e))),t===1/0))return 1/0}return t}function l(e,t="",n){!1!==n&&(t=d(t));const r=e.parse(t);return h(e,r)}function h(e,t){return e.serialize(t).split("#")[0]+"#"}t.getFullPath=l,t._getFullPath=h;const f=/#\/?$/;function d(e){return e?e.replace(f,""):""}t.normalizeId=d,t.resolveUrl=function(e,t,n){return n=d(n),e.resolve(t,n)};const g=/^[a-z_][-a-z0-9._]*$/i;t.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:n,uriResolver:r}=this.opts,a=d(e[n]||t),s={"":a},c=l(r,a,!1),u={},h=new Set;return o(e,{allKeys:!0},((e,t,r,i)=>{if(void 0===i)return;const o=c+t;let a=s[i];function l(t){const n=this.opts.uriResolver.resolve;if(t=d(a?n(a,t):t),h.has(t))throw p(t);h.add(t);let r=this.refs[t];return"string"==typeof r&&(r=this.refs[r]),"object"==typeof r?f(e,r.schema,t):t!==d(o)&&("#"===t[0]?(f(e,u[t],t),u[t]=e):this.refs[t]=o),t}function b(e){if("string"==typeof e){if(!g.test(e))throw new Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}"string"==typeof e[n]&&(a=l.call(this,e[n])),b.call(this,e.$anchor),b.call(this,e.$dynamicAnchor),s[t]=a})),u;function f(e,t,n){if(void 0!==t&&!i(e,t))throw p(n)}function p(e){return new Error(`reference "${e}" resolves to more than one schema`)}}},39255:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(87351),i={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:i}=e;if((0,r.alwaysValidSchema)(i,n))return void e.fail();const o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,(()=>e.reset()),(()=>e.error()))},error:{message:"must NOT be valid"}};t.default=i},40165:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(86493);t.default={Email:r.isEmail}},40526:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(99442),i={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,r.validateTuple)(e,"items")};t.default=i},40967:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkTree=void 0;const r=n(34995);class i{constructor(e){this.options=e,this.checkSafeCall=e=>{const t=this.options.allowMethods;if("Identifier"===e.callee.type)return r.GLOBAL_FUNCTIONS.indexOf(e.callee.name)>=0&&e.arguments.every(this.checkSafeExpression);if(t&&"MemberExpression"===e.callee.type){const t=e.callee.object,n=e.callee.property;if("Identifier"===t.type&&"Identifier"===n.type)return(0,r.isMethodWhitelisted)(t.name,n.name)&&e.arguments.every(this.checkSafeExpression);if("NewExpression"!==t.type&&"CallExpression"!==t.type||"Identifier"!==t.callee.type)return this.checkSafeExpression(t)&&e.arguments.every(this.checkSafeExpression);{const i=t.callee;return(0,r.isMethodWhitelisted)(i.name,n.name)&&e.arguments.every(this.checkSafeExpression)}}return!1},this.checkSafeExpression=e=>{switch(e?.type){case"Identifier":return Object.prototype.hasOwnProperty.call(r.GLOBALS,e.name);case"Literal":return!0;case"ArrayExpression":return e.elements.every(this.checkSafeExpression);case"UnaryExpression":return this.checkSafeExpression(e.argument);case"BinaryExpression":return this.checkSafeExpression(e.left)&&this.checkSafeExpression(e.right);case"CallExpression":case"NewExpression":return this.checkSafeCall(e);case"ObjectExpression":return e.properties.every((e=>!("computed"in e&&e.computed||"method"in e&&e.method)&&!(!("key"in e)||!["Literal","Identifier"].includes(e.key.type))&&"value"in e&&(["FunctionExpression","ArrowFunctionExpression"].includes(e.value.type)||this.checkSafeExpression(e.value))));default:return!1}}}}t.checkTree=(e,t)=>"Program"===e.type&&1===e.body.length&&"ExpressionStatement"===e.body[0].type&&new i(t).checkSafeExpression(e.body[0].expression)},41654:function(e,t,n){var r,i=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=r(e),a=0;a<n.length;a++)"default"!==n[a]&&i(t,e,n[a]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.DeviceId=t.DEVICE_ID_TIMEOUT=void 0;const s=n(87641),c=n(45584);t.DEVICE_ID_TIMEOUT=3e3;class u{constructor(e,r=t.DEVICE_ID_TIMEOUT){this.logger=e,this.timeout=r,this.getMachineId=async()=>{const e=await Promise.resolve().then((()=>a(n(85745))));return(e.default?.machineId||e.machineId)(!0)},this.abortController=new AbortController,this.deviceIdPromise=u.UnknownDeviceId}initialize(){this.deviceIdPromise=(0,s.getDeviceId)({getMachineId:this.getMachineId,onError:(e,t)=>{this.handleDeviceIdError(e,String(t))},timeout:this.timeout,abortSignal:this.abortController.signal})}static create(e,n){const r=new u(e,n??t.DEVICE_ID_TIMEOUT);return r.initialize(),r}close(){this.abortController.abort()}get(){return this.deviceIdPromise}handleDeviceIdError(e,t){switch(this.deviceIdPromise=u.UnknownDeviceId,e){case"resolutionError":this.logger.debug({id:c.LogId.deviceIdResolutionError,context:"deviceId",message:`Resolution error: ${String(t)}`});break;case"timeout":this.logger.debug({id:c.LogId.deviceIdTimeout,context:"deviceId",message:"Device ID retrieval timed out",noRedaction:!0})}}}t.DeviceId=u,u.UnknownDeviceId=Promise.resolve("unknown")},42479:e=>{e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}')},43052:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DbStatsTool=void 0;const r=n(58203),i=n(77710),o=n(62444);class a extends r.MongoDBToolBase{constructor(){super(...arguments),this.name="db-stats",this.description="Returns statistics that reflect the use state of a single database",this.argsShape={database:r.DbOperationArgs.database}}async execute({database:e},{signal:t}){const n=await this.ensureConnected(),r=await n.runCommandWithCheck(e,{dbStats:1,scale:1},{signal:t});return{content:(0,i.formatUntrustedData)(`Statistics for database ${e}`,o.EJSON.stringify(r))}}}t.DbStatsTool=a,a.operationType="metadata"},43376:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListCollectionsTool=void 0;const r=n(58203),i=n(77710);class o extends r.MongoDBToolBase{constructor(){super(...arguments),this.name="list-collections",this.description="List all collections for a given database",this.argsShape={database:r.DbOperationArgs.database}}async execute({database:e},{signal:t}){const n=await this.ensureConnected(),r=await n.listCollections(e,{},{signal:t});return 0===r.length?{content:[{type:"text",text:`Found 0 collections for database "${e}". To create a collection, use the "create-collection" tool.`}]}:{content:(0,i.formatUntrustedData)(`Found ${r.length} collections for database "${e}".`,r.map((e=>`"${e.name}"`)).join("\n"))}}}t.ListCollectionsTool=o,o.operationType="metadata"},43443:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTool=t.getAggregateArgs=void 0;const r=n(69761),i=n(58203),o=n(77710),a=n(49446),s=n(62444),c=n(46319),u=n(92639),l=n(86463),h=n(18253),f=n(45584),d=n(70685),g=n(72439);t.getAggregateArgs=e=>({pipeline:r.z.array(e?r.z.union([d.VectorSearchStage,d.AnyAggregateStage]):d.AnyAggregateStage).describe(e?"An array of aggregation stages to execute.\nIf the user has asked for a vector search, `$vectorSearch` **MUST** be the first stage of the pipeline, or the first stage of a `$unionWith` subpipeline.\nIf the user has asked for lexical/Atlas search, use `$search` instead of `$text`.\n### Usage Rules for `$vectorSearch`\n- **Unset embeddings:**\n Unless the user explicitly requests the embeddings, add an `$unset` stage **at the end of the pipeline** to remove the embedding field and avoid context limits. **The $unset stage in this situation is mandatory**.\n- **Pre-filtering:**\nIf the user requests additional filtering, include filters in `$vectorSearch.filter` only for pre-filter fields in the vector index.\n NEVER include fields in $vectorSearch.filter that are not part of the vector index.\n- **Post-filtering:**\n For all remaining filters, add a $match stage after $vectorSearch.\n- If unsure which fields are filterable, use the collection-indexes tool to determine valid prefilter fields.\n- If no requested filters are valid prefilters, omit the filter key from $vectorSearch.\n\n### Usage Rules for `$search`\n- Include the index name, unless you know for a fact there's a default index. If unsure, use the collection-indexes tool to determine the index name.\n- The `$search` stage supports multiple operators, such as 'autocomplete', 'text', 'geoWithin', and others. Choose the approprate operator based on the user's query. If unsure of the exact syntax, consult the MongoDB Atlas Search documentation, which can be found here: https://www.mongodb.com/docs/atlas/atlas-search/operators-and-collectors/\n":"An array of aggregation stages to execute.")});class p extends i.MongoDBToolBase{constructor(){super(...arguments),this.name="aggregate",this.description="Run an aggregation against a MongoDB collection",this.argsShape={...i.DbOperationArgs,...(0,t.getAggregateArgs)(this.isFeatureEnabled("search")),responseBytesLimit:r.z.number().optional().default(h.ONE_MB).describe('The maximum number of bytes to return in the response. This value is capped by the server\'s configured maxBytesPerQuery and cannot be exceeded. Note to LLM: If the entire aggregation result is required, use the "export" tool instead of increasing this limit.')}}async execute({database:e,collection:t,pipeline:n,responseBytesLimit:r},{signal:i}){let l;try{const h=await this.ensureConnected();if(await this.assertOnlyUsesPermittedStages(n),await this.session.isSearchSupported()&&(0,g.assertVectorSearchFilterFieldsAreIndexed)({searchIndexes:await h.getSearchIndexes(e,t),pipeline:n,logger:this.session.logger}),this.config.indexCheck){const[r,o]=await this.isVectorSearchIndexUsed({database:e,collection:t,pipeline:n});switch(r){case"not-vector-search-query":await(0,a.checkIndexUsage)({database:e,collection:t,operation:"aggregate",explainCallback:async()=>h.aggregate(e,t,n,{signal:i},{writeConcern:void 0}).explain("queryPlanner"),logger:this.session.logger});break;case"non-existent-index":throw new c.MongoDBError(c.ErrorCodes.AtlasVectorSearchIndexNotFound,`Could not find an index with name "${o}" in namespace "${e}.${t}".`)}}let f,d;if((n=await this.replaceRawValuesWithEmbeddingsIfNecessary({database:e,collection:t,pipeline:n})).some((e=>this.isWriteStage(e))))l=h.aggregate(e,t,n,{signal:i}),d=await l.toArray(),f="The aggregation pipeline executed successfully.";else{const o=[...n];this.config.maxDocumentsPerQuery>0&&o.push({$limit:this.config.maxDocumentsPerQuery}),l=h.aggregate(e,t,o,{signal:i});const[a,s]=await Promise.all([this.countAggregationResultDocuments({provider:h,database:e,collection:t,pipeline:n,abortSignal:i}),(0,u.collectCursorUntilMaxBytesLimit)({cursor:l,configuredMaxBytesPerQuery:this.config.maxBytesPerQuery,toolResponseBytesLimit:r,abortSignal:i})]),c=this.config.maxDocumentsPerQuery>0&&!!a&&a>this.config.maxDocumentsPerQuery;d=s.documents,f=this.generateMessage({aggResultsCount:a,documents:s.documents,appliedLimits:[c?"config.maxDocumentsPerQuery":void 0,s.cappedBy].filter((e=>!!e))})}return{content:(0,o.formatUntrustedData)(f,...d.length>0?[s.EJSON.stringify(d)]:[])}}finally{l&&this.safeCloseCursor(l)}}async safeCloseCursor(e){try{await e.close()}catch(e){this.session.logger.warning({id:f.LogId.mongodbCursorCloseError,context:"aggregate tool",message:`Error when closing the cursor - ${e instanceof Error?e.message:String(e)}`})}}async assertOnlyUsesPermittedStages(e){const t=["update","create","delete"],n=await this.session.isSearchSupported();let r="";this.config.readOnly?r="In readOnly mode you can not run pipelines with $out or $merge stages.":this.config.disabledTools.some((e=>t.includes(e)))&&(r="When 'create', 'update', or 'delete' operations are disabled, you can not run pipelines with $out or $merge stages.");for(const t of e){if(this.isWriteStage(t)&&r)throw new c.MongoDBError(c.ErrorCodes.ForbiddenWriteOperation,r);if(this.isSearchStage(t)&&!n)throw new c.MongoDBError(c.ErrorCodes.AtlasSearchNotSupported,"Atlas Search is not supported in this cluster.")}}async countAggregationResultDocuments({provider:e,database:t,collection:n,pipeline:r,abortSignal:i}){const o=[...r,{$count:"totalDocuments"}];return await(0,l.operationWithFallback)((async()=>{const r=await e.aggregate(t,n,o,{signal:i}).maxTimeMS(h.AGG_COUNT_MAX_TIME_MS_CAP).toArray(),a=1===r.length?r[0]:void 0;return a&&"object"==typeof a&&"totalDocuments"in a&&"number"==typeof a.totalDocuments?a.totalDocuments:0}),void 0)}async replaceRawValuesWithEmbeddingsIfNecessary({database:e,collection:t,pipeline:n}){for(const r of n)if("$vectorSearch"in r){const{$vectorSearch:n}=r;if(Array.isArray(n.queryVector))continue;if(!n.embeddingParameters)throw new c.MongoDBError(c.ErrorCodes.AtlasVectorSearchInvalidQuery,"embeddingModel is mandatory if queryVector is a raw string.");const i=n.embeddingParameters;delete n.embeddingParameters,await this.session.vectorSearchEmbeddingsManager.assertVectorSearchIndexExists({database:e,collection:t,path:n.path});const[o]=await this.session.vectorSearchEmbeddingsManager.generateEmbeddings({rawValues:[n.queryVector],embeddingParameters:i,inputType:"query"});if(!o)throw new c.MongoDBError(c.ErrorCodes.AtlasVectorSearchInvalidQuery,"Failed to generate embeddings for the query vector.");n.queryVector=o}return await this.session.vectorSearchEmbeddingsManager.assertFieldsHaveCorrectEmbeddings({database:e,collection:t},n),n}async isVectorSearchIndexUsed({database:e,collection:t,pipeline:n}){let r=!1,i="default";for(const e of n)if("$vectorSearch"in e){const{$vectorSearch:t}=e;r=!0,i=t.index;break}return r?[await this.session.vectorSearchEmbeddingsManager.indexExists({database:e,collection:t,indexName:i})?"valid-index":"non-existent-index",i]:["not-vector-search-query"]}generateMessage({aggResultsCount:e,documents:t,appliedLimits:n}){let r=`The aggregation resulted in ${void 0===e?"indeterminable number of":e} documents.`;return(t.length!==e||n.length)&&(r+=` Returning ${t.length} documents`,n.length&&(r+=` while respecting the applied limits of ${n.map((e=>h.CURSOR_LIMITS_TO_LLM_TEXT[e])).join(", ")}. Note to LLM: If the entire query result is required then use "export" tool to export the query results`),r+="."),r}resolveTelemetryMetadata(e,{result:t}){const[n]=e.pipeline;return null!==n&&n instanceof Object&&"$vectorSearch"in n&&"embeddingParameters"in n.$vectorSearch&&this.config.voyageApiKey?{...super.resolveTelemetryMetadata(e,{result:t}),embeddingsGeneratedBy:"mcp"}:super.resolveTelemetryMetadata(e,{result:t})}isSearchStage(e){return"$vectorSearch"in e||"$search"in e||"$searchMeta"in e}isWriteStage(e){return"$out"in e||"$merge"in e}}t.AggregateTool=p,p.operationType="read"},43802:(e,t,n)=>{Object.defineProperty(t,"BJ",{value:!0}),t.On=t.R5=t.U$=void 0;var r=n(44558);Object.defineProperty(t,"U$",{enumerable:!0,get:function(){return r.translateToElectronProxyConfig}}),Object.defineProperty(t,"R5",{enumerable:!0,get:function(){return r.extractProxySecrets}}),Object.defineProperty(t,"On",{enumerable:!0,get:function(){return r.mergeProxySecrets}})},44216:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setManagedTimeout=function(e,t){let n=setTimeout((()=>{e()}),t);function r(){clearTimeout(n),n=void 0}return{cancel:r,restart:function(){r(),n=setTimeout((()=>{e()}),t)}}}},44558:(e,t,n)=>{var r=n(9606).URL,i=n(65994).process;function o(e){const t=new Map;let n="";for(const[r,i]of Object.entries(e)){if(void 0===i)continue;const e=r.toUpperCase();e.endsWith("_PROXY")&&"NO_PROXY"!==e&&t.set(e.replace(/_PROXY$/,"").toLowerCase(),i||"direct://"),"NO_PROXY"===e&&(n=i)}return{map:t,noProxy:n}}function a(e,t){if(!e)return!0;if("*"===e)return!1;for(const n of e.split(/[\s,]/)){let{host:e,port:r}=n.match(/(?<host>.+)(:(?<port>\d+)$)?/)?.groups??{};if(e||(e=n,r=""),(!r||t.port===r)&&(e===t.hostname||e.startsWith("*")&&t.hostname.endsWith(e.substring(1))))return!1}return!0}function s(e,t,n){if(e.proxy){const n=e.proxy;return"direct:"===new r(n).protocol?"":a(e.noProxyHosts||"",new r(t))?n:""}if(e.useEnvironmentVariableProxies){const{map:s,noProxy:c}=o(e.env??i.env),u=new r(t),l=(n?.overrideProtocol??u.protocol).replace(/:$/,""),h=[c,e.noProxyHosts].filter(Boolean).join(","),f=s.get(l)||s.get("all");return f&&a(h,u)?f:""}return""}function c(e){if("ssh:"===(e=new r(e.toString())).protocol)throw new Error(`Using ssh:// proxies for generic browser proxy usage is not supported (translating '${u(e)}')`);if(e.username||e.password)throw new Error(`Using authenticated proxies for generic browser proxy usage is not supported (translating '${u(e)}')`);if("http:"!==e.protocol&&"https:"!==e.protocol&&"socks5:"!==e.protocol)throw new Error(`Unsupported proxy protocol (translating '${u(e)}')`);if(e.search||e.hash)throw new Error(`Unsupported URL extensions in proxy specification (translating '${u(e)}')`);if(""===e.pathname)return e.toString();if("/"!==e.pathname)throw new Error(`Unsupported URL pathname in proxy specification (translating '${u(e)}')`);return e.toString().replace(/\/$/,"")}function u(e){const t=new r(e.toString());return t.password&&(t.password="(credential)"),t.toString()}Object.defineProperty(t,"__esModule",{value:!0}),t.proxyConfForEnvVars=o,t.proxyForUrl=s,t.translateToElectronProxyConfig=function(e){if(e.proxy){let t=e.proxy;return new r(t).protocol.startsWith("pac+")?(t=t.replace("pac+",""),{mode:"pac_script",pacScript:t.toString(),proxyBypassRules:e.noProxyHosts}):{mode:"fixed_servers",proxyRules:c(t),proxyBypassRules:e.noProxyHosts}}if(e.useEnvironmentVariableProxies){const t=[],n=[e.noProxyHosts],{map:r,noProxy:a}=o(e.env??i.env);for(const e of["http","https","ftp"]){const n=r.get(e)||r.get("all");n&&t.push(`${e}=${c(n)}`)}n.push(a);const s=t.join(";"),u=n.filter(Boolean).join(",")||void 0;return s?{mode:"fixed_servers",proxyBypassRules:u,proxyRules:s}:u?{proxyBypassRules:u}:{}}return{}},t.getSocks5OnlyProxyOptions=function(e,t){let n;if(void 0!==t?n=s(e,t):e.noProxyHosts||(n=e.proxy),!n)return;const i=new r(n);return"socks5:"!==i.protocol?void 0:{proxyHost:decodeURIComponent(i.hostname),proxyPort:+(i.port||1080),proxyUsername:decodeURIComponent(i.username)||void 0,proxyPassword:decodeURIComponent(i.password)||void 0}},t.extractProxySecrets=function(e){const t={};if(e.proxy){const n=new r(e.proxy);t.password=n.password,n.password="",e={...e,proxy:n.toString()}}return e.sshOptions&&(t.sshIdentityKeyPassphrase=e.sshOptions.identityKeyPassphrase,e={...e,sshOptions:{...e.sshOptions,identityKeyPassphrase:void 0}}),{secrets:JSON.stringify(t),proxyOptions:e}},t.mergeProxySecrets=function({proxyOptions:e,secrets:t}){const n=JSON.parse(t||"{}");if((n.username||n.password)&&e.proxy){const t=new r(e.proxy);t.password=n.password||"",e={...e,proxy:t.toString()}}return n.sshIdentityKeyPassphrase&&(e={...e,sshOptions:{...e.sshOptions,identityKeyPassphrase:n.sshIdentityKeyPassphrase}}),e},t.redactUrl=u},45334:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(78249),i=r.operators,o={maximum:{okStr:"<=",ok:i.LTE,fail:i.GT},minimum:{okStr:">=",ok:i.GTE,fail:i.LT},exclusiveMaximum:{okStr:"<",ok:i.LT,fail:i.GTE},exclusiveMinimum:{okStr:">",ok:i.GT,fail:i.LTE}},a={message:({keyword:e,schemaCode:t})=>r.str`must be ${o[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>r._`{comparison: ${o[e].okStr}, limit: ${t}}`},s={keyword:Object.keys(o),type:"number",schemaType:"number",$data:!0,error:a,code(e){const{keyword:t,data:n,schemaCode:i}=e;e.fail$data(r._`${n} ${o[t].fail} ${i} || isNaN(${n})`)}};t.default=s},45584:function(e,t,n){var r=n(65994).process,i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CompositeLogger=t.McpLogger=t.DiskLogger=t.ConsoleLogger=t.LoggerBase=t.LogId=void 0;const o=i(n(65981)),a=n(91174),s=n(23319),c=n(8763);t.LogId={serverStartFailure:(0,a.mongoLogId)(1000001),serverInitialized:(0,a.mongoLogId)(1000002),serverCloseRequested:(0,a.mongoLogId)(1000003),serverClosed:(0,a.mongoLogId)(1000004),serverCloseFailure:(0,a.mongoLogId)(1000005),serverDuplicateLoggers:(0,a.mongoLogId)(1000006),serverMcpClientSet:(0,a.mongoLogId)(1000007),atlasCheckCredentials:(0,a.mongoLogId)(1001001),atlasDeleteDatabaseUserFailure:(0,a.mongoLogId)(1001002),atlasConnectFailure:(0,a.mongoLogId)(1001003),atlasInspectFailure:(0,a.mongoLogId)(1001004),atlasConnectAttempt:(0,a.mongoLogId)(1001005),atlasConnectSucceeded:(0,a.mongoLogId)(1001006),atlasApiRevokeFailure:(0,a.mongoLogId)(1001007),atlasIpAccessListAdded:(0,a.mongoLogId)(1001008),atlasIpAccessListAddFailure:(0,a.mongoLogId)(1001009),telemetryDisabled:(0,a.mongoLogId)(1002001),telemetryEmitFailure:(0,a.mongoLogId)(1002002),telemetryEmitStart:(0,a.mongoLogId)(1002003),telemetryEmitSuccess:(0,a.mongoLogId)(1002004),telemetryMetadataError:(0,a.mongoLogId)(1002005),deviceIdResolutionError:(0,a.mongoLogId)(1002006),deviceIdTimeout:(0,a.mongoLogId)(1002007),telemetryClose:(0,a.mongoLogId)(1002008),toolExecute:(0,a.mongoLogId)(1003001),toolExecuteFailure:(0,a.mongoLogId)(1003002),toolDisabled:(0,a.mongoLogId)(1003003),toolMetadataChange:(0,a.mongoLogId)(1003004),mongodbConnectFailure:(0,a.mongoLogId)(1004001),mongodbDisconnectFailure:(0,a.mongoLogId)(1004002),mongodbConnectTry:(0,a.mongoLogId)(1004003),mongodbCursorCloseError:(0,a.mongoLogId)(1004004),mongodbIndexCheckFailure:(0,a.mongoLogId)(1004005),toolUpdateFailure:(0,a.mongoLogId)(1005001),resourceUpdateFailure:(0,a.mongoLogId)(1005002),updateToolMetadata:(0,a.mongoLogId)(1005003),toolValidationError:(0,a.mongoLogId)(1005004),streamableHttpTransportStarted:(0,a.mongoLogId)(1006001),streamableHttpTransportSessionCloseFailure:(0,a.mongoLogId)(1006002),streamableHttpTransportSessionCloseNotification:(0,a.mongoLogId)(1006003),streamableHttpTransportSessionCloseNotificationFailure:(0,a.mongoLogId)(1006004),streamableHttpTransportRequestFailure:(0,a.mongoLogId)(1006005),streamableHttpTransportCloseFailure:(0,a.mongoLogId)(1006006),streamableHttpTransportKeepAliveFailure:(0,a.mongoLogId)(1006007),streamableHttpTransportKeepAlive:(0,a.mongoLogId)(1006008),streamableHttpTransportHttpHostWarning:(0,a.mongoLogId)(1006009),exportCleanupError:(0,a.mongoLogId)(1007001),exportCreationError:(0,a.mongoLogId)(1007002),exportCreationCleanupError:(0,a.mongoLogId)(1007003),exportReadError:(0,a.mongoLogId)(1007004),exportCloseError:(0,a.mongoLogId)(1007005),exportedDataListError:(0,a.mongoLogId)(1007006),exportedDataAutoCompleteError:(0,a.mongoLogId)(1007007),exportLockError:(0,a.mongoLogId)(1007008),oidcFlow:(0,a.mongoLogId)(1008001),atlasPaSuggestedIndexesFailure:(0,a.mongoLogId)(1009001),atlasPaDropIndexSuggestionsFailure:(0,a.mongoLogId)(1009002),atlasPaSchemaAdviceFailure:(0,a.mongoLogId)(1009003),atlasPaSlowQueryLogsFailure:(0,a.mongoLogId)(1009004),atlasLocalDockerNotRunning:(0,a.mongoLogId)(1010001),atlasLocalUnsupportedPlatform:(0,a.mongoLogId)(1010002)};class u extends c.EventEmitter{constructor(e){super(),this.keychain=e,this.defaultUnredactedLogger="mcp"}log(e,t){const n=void 0!==t.noRedaction?t.noRedaction:this.defaultUnredactedLogger;this.logCore(e,{...t,message:this.redactIfNecessary(t.message,n)})}redactIfNecessary(e,t){return"boolean"==typeof t&&t||"string"==typeof t&&t===this.type||"object"==typeof t&&Array.isArray(t)&&this.type&&-1!==t.indexOf(this.type)?e:(0,s.redact)(e,this.keychain?.allSecrets??[])}info(e){this.log("info",e)}error(e){this.log("error",e)}debug(e){this.log("debug",e)}notice(e){this.log("notice",e)}warning(e){this.log("warning",e)}critical(e){this.log("critical",e)}alert(e){this.log("alert",e)}emergency(e){this.log("emergency",e)}mapToMongoDBLogLevel(e){switch(e){case"info":default:return"info";case"warning":return"warn";case"error":return"error";case"notice":case"debug":return"debug";case"critical":case"alert":case"emergency":return"fatal"}}}t.LoggerBase=u,t.ConsoleLogger=class extends u{constructor(e){super(e),this.type="console"}logCore(e,t){const{id:n,context:i,message:o}=t;console.error(`[${e.toUpperCase()}] ${n.__value} - ${i}: ${o} (${r.pid}${this.serializeAttributes(t.attributes)})`)}serializeAttributes(e){return e&&0!==Object.keys(e).length?`, ${Object.entries(e).map((([e,t])=>`${e}=${t}`)).join(", ")}`:""}},t.DiskLogger=class extends u{constructor(e,t,n){super(n),this.bufferedMessages=[],this.type="disk",this.initialize(e,t)}async initialize(e,t){try{await o.default.mkdir(e,{recursive:!0});const t=new a.MongoLogManager({directory:e,retentionDays:30,onwarn:console.warn,onerror:console.error,gzip:!1,retentionGB:1});await t.cleanupOldLogFiles(),this.logWriter=await t.createLogWriter();for(const e of this.bufferedMessages)this.logCore(e.level,e.payload);this.bufferedMessages=[],this.emit("initialized")}catch(e){t(e)}}logCore(e,t){if(!this.logWriter)return void this.bufferedMessages.push({level:e,payload:t});const{id:n,context:r,message:i}=t,o=this.mapToMongoDBLogLevel(e);this.logWriter[o]("MONGODB-MCP",n,r,i,t.attributes)}};class l extends u{constructor(e,t){super(t),this.server=e,this.type="mcp"}logCore(e,t){this.server.mcpServer.isConnected()&&(l.LOG_LEVELS.indexOf(this.server.mcpLogLevel)>l.LOG_LEVELS.indexOf(e)||this.server.mcpServer.server.sendLoggingMessage({level:e,data:`[${t.context}]: ${t.message}`}))}}t.McpLogger=l,l.LOG_LEVELS=["debug","info","notice","warning","error","critical","alert","emergency"],t.CompositeLogger=class extends u{constructor(...e){super(void 0),this.loggers=[],this.attributes={},this.loggers=e}addLogger(e){this.loggers.push(e)}log(e,t){for(const n of this.loggers){const r=Object.keys(this.attributes).length>0||t.attributes?{...this.attributes,...t.attributes}:void 0;n.log(e,{...t,attributes:r})}}logCore(){throw new Error("logCore should never be invoked on CompositeLogger")}setAttribute(e,t){this.attributes[e]=t}}},46096:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SwitchConnectionTool=void 0;const i=r(n(69761)),o=n(58203);class a extends o.MongoDBToolBase{constructor(e){super(e),this.name="switch-connection",this.description="Switch to a different MongoDB connection. If the user has configured a connection string or has previously called the connect tool, a connection is already established and there's no need to call this tool unless the user has explicitly requested to switch to a new instance.",this.argsShape={connectionString:i.default.string().optional().describe("MongoDB connection string to switch to (in the mongodb:// or mongodb+srv:// format). If a connection string is not provided, the connection string from the config will be used.")},e.session.on("connect",(()=>{this.enable()})),e.session.on("disconnect",(()=>{this.disable()}))}register(e){const t=super.register(e);return t&&!this.session.isConnectedToMongoDB&&this.disable(),t}async execute({connectionString:e}){return"string"!=typeof e?await this.session.connectToConfiguredConnection():await this.session.connectToMongoDB({connectionString:e}),{content:[{type:"text",text:"Successfully connected to MongoDB."}]}}}t.SwitchConnectionTool=a,a.operationType="connect"},46249:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdioServerTransport=void 0;const i=r(n(65994)),o=n(10083);t.StdioServerTransport=class{constructor(e=i.default.stdin,t=i.default.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new o.ReadBuffer,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}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(;;)try{const e=this._readBuffer.readMessage();if(null===e)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise((t=>{const n=(0,o.serializeMessage)(e);this._stdout.write(n)?t():this._stdout.once("drain",t)}))}}},46319:(e,t)=>{var n;Object.defineProperty(t,"__esModule",{value:!0}),t.MongoDBError=t.ErrorCodes=void 0,function(e){e[e.NotConnectedToMongoDB=1e6]="NotConnectedToMongoDB",e[e.MisconfiguredConnectionString=1000001]="MisconfiguredConnectionString",e[e.ForbiddenCollscan=1000002]="ForbiddenCollscan",e[e.ForbiddenWriteOperation=1000003]="ForbiddenWriteOperation",e[e.AtlasSearchNotSupported=1000004]="AtlasSearchNotSupported",e[e.NoEmbeddingsProviderConfigured=1000005]="NoEmbeddingsProviderConfigured",e[e.AtlasVectorSearchIndexNotFound=1000006]="AtlasVectorSearchIndexNotFound",e[e.AtlasVectorSearchInvalidQuery=1000007]="AtlasVectorSearchInvalidQuery",e[e.Unexpected=1000008]="Unexpected"}(n||(t.ErrorCodes=n={}));class r extends Error{constructor(e,t){super(t),this.code=e}}t.MongoDBError=r},46575:(e,t,n)=>{n.d(t,{Fp:()=>Dc,Jo:()=>kp,LP:()=>Sp,PV:()=>yp,R4:()=>Ai,rN:()=>Tu,yF:()=>up});var r=n(10873),i=n(96003),o=n(35196),a=n(80512),s=n(96652),c=n.n(s),u=(n(46410),n(76144)),l=n(46398),h=n(59389),f=n(92026),d=n(83008),g=n(27898),p=n(25072);function b(){return b=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},b.apply(null,arguments)}!function(){try{if(typeof document<"u"){var e=document.createElement("style");e.appendChild(document.createTextNode(".react-flow{direction:ltr;--xy-edge-stroke-default: #b1b1b7;--xy-edge-stroke-width-default: 1;--xy-edge-stroke-selected-default: #555;--xy-connectionline-stroke-default: #b1b1b7;--xy-connectionline-stroke-width-default: 1;--xy-attribution-background-color-default: rgba(255, 255, 255, .5);--xy-minimap-background-color-default: #fff;--xy-minimap-mask-background-color-default: rgb(240, 240, 240, .6);--xy-minimap-mask-stroke-color-default: transparent;--xy-minimap-mask-stroke-width-default: 1;--xy-minimap-node-background-color-default: #e2e2e2;--xy-minimap-node-stroke-color-default: transparent;--xy-minimap-node-stroke-width-default: 2;--xy-background-color-default: transparent;--xy-background-pattern-dots-color-default: #91919a;--xy-background-pattern-lines-color-default: #eee;--xy-background-pattern-cross-color-default: #e2e2e2;background-color:var(--xy-background-color, var(--xy-background-color-default));--xy-node-color-default: inherit;--xy-node-border-default: 1px solid #1a192b;--xy-node-background-color-default: #fff;--xy-node-group-background-color-default: rgba(240, 240, 240, .25);--xy-node-boxshadow-hover-default: 0 1px 4px 1px rgba(0, 0, 0, .08);--xy-node-boxshadow-selected-default: 0 0 0 .5px #1a192b;--xy-node-border-radius-default: 3px;--xy-handle-background-color-default: #1a192b;--xy-handle-border-color-default: #fff;--xy-selection-background-color-default: rgba(0, 89, 220, .08);--xy-selection-border-default: 1px dotted rgba(0, 89, 220, .8);--xy-controls-button-background-color-default: #fefefe;--xy-controls-button-background-color-hover-default: #f4f4f4;--xy-controls-button-color-default: inherit;--xy-controls-button-color-hover-default: inherit;--xy-controls-button-border-color-default: #eee;--xy-controls-box-shadow-default: 0 0 2px 1px rgba(0, 0, 0, .08);--xy-edge-label-background-color-default: #ffffff;--xy-edge-label-color-default: inherit;--xy-resize-background-color-default: #3367d9}.react-flow.dark{--xy-edge-stroke-default: #3e3e3e;--xy-edge-stroke-width-default: 1;--xy-edge-stroke-selected-default: #727272;--xy-connectionline-stroke-default: #b1b1b7;--xy-connectionline-stroke-width-default: 1;--xy-attribution-background-color-default: rgba(150, 150, 150, .25);--xy-minimap-background-color-default: #141414;--xy-minimap-mask-background-color-default: rgb(60, 60, 60, .6);--xy-minimap-mask-stroke-color-default: transparent;--xy-minimap-mask-stroke-width-default: 1;--xy-minimap-node-background-color-default: #2b2b2b;--xy-minimap-node-stroke-color-default: transparent;--xy-minimap-node-stroke-width-default: 2;--xy-background-color-default: #141414;--xy-background-pattern-dots-color-default: #777;--xy-background-pattern-lines-color-default: #777;--xy-background-pattern-cross-color-default: #777;--xy-node-color-default: #f8f8f8;--xy-node-border-default: 1px solid #3c3c3c;--xy-node-background-color-default: #1e1e1e;--xy-node-group-background-color-default: rgba(240, 240, 240, .25);--xy-node-boxshadow-hover-default: 0 1px 4px 1px rgba(255, 255, 255, .08);--xy-node-boxshadow-selected-default: 0 0 0 .5px #999;--xy-handle-background-color-default: #bebebe;--xy-handle-border-color-default: #1e1e1e;--xy-selection-background-color-default: rgba(200, 200, 220, .08);--xy-selection-border-default: 1px dotted rgba(200, 200, 220, .8);--xy-controls-button-background-color-default: #2b2b2b;--xy-controls-button-background-color-hover-default: #3e3e3e;--xy-controls-button-color-default: #f8f8f8;--xy-controls-button-color-hover-default: #fff;--xy-controls-button-border-color-default: #5b5b5b;--xy-controls-box-shadow-default: 0 0 2px 1px rgba(0, 0, 0, .08);--xy-edge-label-background-color-default: #141414;--xy-edge-label-color-default: #f8f8f8}.react-flow__background{background-color:var(--xy-background-color, var(--xy-background-color-props, var(--xy-background-color-default)));pointer-events:none;z-index:-1}.react-flow__container{position:absolute;width:100%;height:100%;top:0;left:0}.react-flow__pane{z-index:1}.react-flow__pane.draggable{cursor:grab}.react-flow__pane.dragging{cursor:grabbing}.react-flow__pane.selection{cursor:pointer}.react-flow__viewport{transform-origin:0 0;z-index:2;pointer-events:none}.react-flow__renderer{z-index:4}.react-flow__selection{z-index:6}.react-flow__nodesselection-rect:focus,.react-flow__nodesselection-rect:focus-visible{outline:none}.react-flow__edge-path{stroke:var(--xy-edge-stroke, var(--xy-edge-stroke-default));stroke-width:var(--xy-edge-stroke-width, var(--xy-edge-stroke-width-default));fill:none}.react-flow__connection-path{stroke:var(--xy-connectionline-stroke, var(--xy-connectionline-stroke-default));stroke-width:var(--xy-connectionline-stroke-width, var(--xy-connectionline-stroke-width-default));fill:none}.react-flow .react-flow__edges{position:absolute}.react-flow .react-flow__edges svg{overflow:visible;position:absolute;pointer-events:none}.react-flow__edge{pointer-events:visibleStroke}.react-flow__edge.selectable{cursor:pointer}.react-flow__edge.animated path{stroke-dasharray:5;animation:dashdraw .5s linear infinite}.react-flow__edge.animated path.react-flow__edge-interaction{stroke-dasharray:none;animation:none}.react-flow__edge.inactive{pointer-events:none}.react-flow__edge.selected,.react-flow__edge:focus,.react-flow__edge:focus-visible{outline:none}.react-flow__edge.selected .react-flow__edge-path,.react-flow__edge.selectable:focus .react-flow__edge-path,.react-flow__edge.selectable:focus-visible .react-flow__edge-path{stroke:var(--xy-edge-stroke-selected, var(--xy-edge-stroke-selected-default))}.react-flow__edge-textwrapper{pointer-events:all}.react-flow__edge .react-flow__edge-text{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.react-flow__connection{pointer-events:none}.react-flow__connection .animated{stroke-dasharray:5;animation:dashdraw .5s linear infinite}svg.react-flow__connectionline{z-index:1001;overflow:visible;position:absolute}.react-flow__nodes{pointer-events:none;transform-origin:0 0}.react-flow__node{position:absolute;-webkit-user-select:none;-moz-user-select:none;user-select:none;pointer-events:all;transform-origin:0 0;box-sizing:border-box;cursor:default}.react-flow__node.selectable{cursor:pointer}.react-flow__node.draggable{cursor:grab;pointer-events:all}.react-flow__node.draggable.dragging{cursor:grabbing}.react-flow__nodesselection{z-index:3;transform-origin:left top;pointer-events:none}.react-flow__nodesselection-rect{position:absolute;pointer-events:all;cursor:grab}.react-flow__handle{position:absolute;pointer-events:none;min-width:5px;min-height:5px;width:6px;height:6px;background-color:var(--xy-handle-background-color, var(--xy-handle-background-color-default));border:1px solid var(--xy-handle-border-color, var(--xy-handle-border-color-default));border-radius:100%}.react-flow__handle.connectingfrom{pointer-events:all}.react-flow__handle.connectionindicator{pointer-events:all;cursor:crosshair}.react-flow__handle-bottom{top:auto;left:50%;bottom:0;transform:translate(-50%,50%)}.react-flow__handle-top{top:0;left:50%;transform:translate(-50%,-50%)}.react-flow__handle-left{top:50%;left:0;transform:translate(-50%,-50%)}.react-flow__handle-right{top:50%;right:0;transform:translate(50%,-50%)}.react-flow__edgeupdater{cursor:move;pointer-events:all}.react-flow__panel{position:absolute;z-index:5;margin:15px}.react-flow__panel.top{top:0}.react-flow__panel.bottom{bottom:0}.react-flow__panel.top.center,.react-flow__panel.bottom.center{left:50%;transform:translate(-50%)}.react-flow__panel.left{left:0}.react-flow__panel.right{right:0}.react-flow__panel.left.center,.react-flow__panel.right.center{top:50%;transform:translateY(-50%)}.react-flow__attribution{font-size:10px;background:var(--xy-attribution-background-color, var(--xy-attribution-background-color-default));padding:2px 3px;margin:0}.react-flow__attribution a{text-decoration:none;color:#999}@keyframes dashdraw{0%{stroke-dashoffset:10}}.react-flow__edgelabel-renderer{position:absolute;width:100%;height:100%;pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;left:0;top:0}.react-flow__viewport-portal{position:absolute;width:100%;height:100%;left:0;top:0;-webkit-user-select:none;-moz-user-select:none;user-select:none}.react-flow__minimap{background:var( --xy-minimap-background-color-props, var(--xy-minimap-background-color, var(--xy-minimap-background-color-default)) )}.react-flow__minimap-svg{display:block}.react-flow__minimap-mask{fill:var( --xy-minimap-mask-background-color-props, var(--xy-minimap-mask-background-color, var(--xy-minimap-mask-background-color-default)) );stroke:var( --xy-minimap-mask-stroke-color-props, var(--xy-minimap-mask-stroke-color, var(--xy-minimap-mask-stroke-color-default)) );stroke-width:var( --xy-minimap-mask-stroke-width-props, var(--xy-minimap-mask-stroke-width, var(--xy-minimap-mask-stroke-width-default)) )}.react-flow__minimap-node{fill:var( --xy-minimap-node-background-color-props, var(--xy-minimap-node-background-color, var(--xy-minimap-node-background-color-default)) );stroke:var( --xy-minimap-node-stroke-color-props, var(--xy-minimap-node-stroke-color, var(--xy-minimap-node-stroke-color-default)) );stroke-width:var( --xy-minimap-node-stroke-width-props, var(--xy-minimap-node-stroke-width, var(--xy-minimap-node-stroke-width-default)) )}.react-flow__background-pattern.dots{fill:var( --xy-background-pattern-color-props, var(--xy-background-pattern-color, var(--xy-background-pattern-dots-color-default)) )}.react-flow__background-pattern.lines{stroke:var( --xy-background-pattern-color-props, var(--xy-background-pattern-color, var(--xy-background-pattern-lines-color-default)) )}.react-flow__background-pattern.cross{stroke:var( --xy-background-pattern-color-props, var(--xy-background-pattern-color, var(--xy-background-pattern-cross-color-default)) )}.react-flow__controls{display:flex;flex-direction:column;box-shadow:var(--xy-controls-box-shadow, var(--xy-controls-box-shadow-default))}.react-flow__controls.horizontal{flex-direction:row}.react-flow__controls-button{display:flex;justify-content:center;align-items:center;height:26px;width:26px;padding:4px;border:none;background:var(--xy-controls-button-background-color, var(--xy-controls-button-background-color-default));border-bottom:1px solid var( --xy-controls-button-border-color-props, var(--xy-controls-button-border-color, var(--xy-controls-button-border-color-default)) );color:var( --xy-controls-button-color-props, var(--xy-controls-button-color, var(--xy-controls-button-color-default)) );cursor:pointer;-webkit-user-select:none;-moz-user-select:none;user-select:none}.react-flow__controls-button svg{width:100%;max-width:12px;max-height:12px;fill:currentColor}.react-flow__edge.updating .react-flow__edge-path{stroke:#777}.react-flow__edge-text{font-size:10px}.react-flow__node.selectable:focus,.react-flow__node.selectable:focus-visible{outline:none}.react-flow__node-input,.react-flow__node-default,.react-flow__node-output,.react-flow__node-group{padding:10px;border-radius:var(--xy-node-border-radius, var(--xy-node-border-radius-default));width:150px;font-size:12px;color:var(--xy-node-color, var(--xy-node-color-default));text-align:center;border:var(--xy-node-border, var(--xy-node-border-default));background-color:var(--xy-node-background-color, var(--xy-node-background-color-default))}.react-flow__node-input.selectable:hover,.react-flow__node-default.selectable:hover,.react-flow__node-output.selectable:hover,.react-flow__node-group.selectable:hover{box-shadow:var(--xy-node-boxshadow-hover, var(--xy-node-boxshadow-hover-default))}.react-flow__node-input.selectable.selected,.react-flow__node-input.selectable:focus,.react-flow__node-input.selectable:focus-visible,.react-flow__node-default.selectable.selected,.react-flow__node-default.selectable:focus,.react-flow__node-default.selectable:focus-visible,.react-flow__node-output.selectable.selected,.react-flow__node-output.selectable:focus,.react-flow__node-output.selectable:focus-visible,.react-flow__node-group.selectable.selected,.react-flow__node-group.selectable:focus,.react-flow__node-group.selectable:focus-visible{box-shadow:var(--xy-node-boxshadow-selected, var(--xy-node-boxshadow-selected-default))}.react-flow__node-group{background-color:var(--xy-node-group-background-color, var(--xy-node-group-background-color-default))}.react-flow__nodesselection-rect,.react-flow__selection{background:var(--xy-selection-background-color, var(--xy-selection-background-color-default));border:var(--xy-selection-border, var(--xy-selection-border-default))}.react-flow__nodesselection-rect:focus,.react-flow__nodesselection-rect:focus-visible,.react-flow__selection:focus,.react-flow__selection:focus-visible{outline:none}.react-flow__controls-button:hover{background:var( --xy-controls-button-background-color-hover-props, var(--xy-controls-button-background-color-hover, var(--xy-controls-button-background-color-hover-default)) );color:var( --xy-controls-button-color-hover-props, var(--xy-controls-button-color-hover, var(--xy-controls-button-color-hover-default)) )}.react-flow__controls-button:disabled{pointer-events:none}.react-flow__controls-button:disabled svg{fill-opacity:.4}.react-flow__controls-button:last-child{border-bottom:none}.react-flow__resize-control{position:absolute}.react-flow__resize-control.left,.react-flow__resize-control.right{cursor:ew-resize}.react-flow__resize-control.top,.react-flow__resize-control.bottom{cursor:ns-resize}.react-flow__resize-control.top.left,.react-flow__resize-control.bottom.right{cursor:nwse-resize}.react-flow__resize-control.bottom.left,.react-flow__resize-control.top.right{cursor:nesw-resize}.react-flow__resize-control.handle{width:4px;height:4px;border:1px solid #fff;border-radius:1px;background-color:var(--xy-resize-background-color, var(--xy-resize-background-color-default));transform:translate(-50%,-50%)}.react-flow__resize-control.handle.left{left:0;top:50%}.react-flow__resize-control.handle.right{left:100%;top:50%}.react-flow__resize-control.handle.top{left:50%;top:0}.react-flow__resize-control.handle.bottom{left:50%;top:100%}.react-flow__resize-control.handle.top.left,.react-flow__resize-control.handle.bottom.left{left:0}.react-flow__resize-control.handle.top.right,.react-flow__resize-control.handle.bottom.right{left:100%}.react-flow__resize-control.line{border-color:var(--xy-resize-background-color, var(--xy-resize-background-color-default));border-width:0;border-style:solid}.react-flow__resize-control.line.left,.react-flow__resize-control.line.right{width:1px;transform:translate(-50%);top:0;height:100%}.react-flow__resize-control.line.left{left:0;border-left-width:1px}.react-flow__resize-control.line.right{left:100%;border-right-width:1px}.react-flow__resize-control.line.top,.react-flow__resize-control.line.bottom{height:1px;transform:translateY(-50%);left:0;width:100%}.react-flow__resize-control.line.top{top:0;border-top-width:1px}.react-flow__resize-control.line.bottom{border-bottom-width:1px;top:100%}.react-flow__edge-textbg{fill:var(--xy-edge-label-background-color, var(--xy-edge-label-background-color-default))}.react-flow__edge-text{fill:var(--xy-edge-label-color, var(--xy-edge-label-color-default))}")),document.head.appendChild(e)}}catch(e){console.error("vite-plugin-css-injected-by-js",e)}}();var m={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,scale:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1};function w(e){var t=Object.create(null);return function(n){return void 0===t[n]&&(t[n]=e(n)),t[n]}}var v=/[A-Z]|^ms/g,y=/_EMO_([^_]+?)_([^]*?)_EMO_/g,S=function(e){return 45===e.charCodeAt(1)},k=function(e){return null!=e&&"boolean"!=typeof e},E=w((function(e){return S(e)?e:e.replace(v,"-$&").toLowerCase()})),x=function(e,t){switch(e){case"animation":case"animationName":if("string"==typeof t)return t.replace(y,(function(e,t,n){return T={name:t,styles:n,next:T},t}))}return 1===m[e]||S(e)||"number"!=typeof t||0===t?t:t+"px"};function M(e,t,n){if(null==n)return"";var r=n;if(void 0!==r.__emotion_styles)return r;switch(typeof n){case"boolean":return"";case"object":var i=n;if(1===i.anim)return T={name:i.name,styles:i.styles,next:T},i.name;var o=n;if(void 0!==o.styles){var a=o.next;if(void 0!==a)for(;void 0!==a;)T={name:a.name,styles:a.styles,next:T},a=a.next;return o.styles+";"}return function(e,t,n){var r="";if(Array.isArray(n))for(var i=0;i<n.length;i++)r+=M(e,t,n[i])+";";else for(var o in n){var a=n[o];if("object"!=typeof a){var s=a;null!=t&&void 0!==t[s]?r+=o+"{"+t[s]+"}":k(s)&&(r+=E(o)+":"+x(o,s)+";")}else if(!Array.isArray(a)||"string"!=typeof a[0]||null!=t&&void 0!==t[a[0]]){var c=M(e,t,a);switch(o){case"animation":case"animationName":r+=E(o)+":"+c+";";break;default:r+=o+"{"+c+"}"}}else for(var u=0;u<a.length;u++)k(a[u])&&(r+=E(o)+":"+x(o,a[u])+";")}return r}(e,t,n);case"function":if(void 0!==e){var s=T,c=n(e);return T=s,M(e,t,c)}}var u=n;if(null==t)return u;var l=t[u];return void 0!==l?l:u}var T,C=/label:\s*([^\s;{]+)\s*(;|$)/g,_=!!s.useInsertionEffect&&s.useInsertionEffect||function(e){return e()},P=function(e,t,n){var r=e.key+"-"+t.name;!1===n&&void 0===e.registered[r]&&(e.registered[r]=t.styles)},I=/^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|disableRemotePlayback|download|draggable|encType|enterKeyHint|fetchpriority|fetchPriority|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/,A=w((function(e){return I.test(e)||111===e.charCodeAt(0)&&110===e.charCodeAt(1)&&e.charCodeAt(2)<91})),O=A,j=function(e){return"theme"!==e},$=function(e){return"string"==typeof e&&e.charCodeAt(0)>96?O:j},R=function(e,t,n){var r;if(t){var i=t.shouldForwardProp;r=e.__emotion_forwardProp&&i?function(t){return e.__emotion_forwardProp(t)&&i(t)}:i}return"function"!=typeof r&&n&&(r=e.__emotion_forwardProp),r},N=function(e){var t=e.cache,n=e.serialized,r=e.isStringTag;return P(t,n,r),_((function(){return function(e,t,n){P(e,t,n);var r=e.key+"-"+t.name;if(void 0===e.inserted[t.name]){var i=t;do{e.insert(t===i?"."+r:"",i,e.sheet,!0),i=i.next}while(void 0!==i)}}(t,n,r)})),null},L=function e(t,n){var r,i,a=t.__emotion_real===t,c=a&&t.__emotion_base||t;void 0!==n&&(r=n.label,i=n.target);var u=R(t,n,a),l=u||$(c),h=!l("as");return function(){var f=arguments,d=a&&void 0!==t.__emotion_styles?t.__emotion_styles.slice(0):[];if(void 0!==r&&d.push("label:"+r+";"),null==f[0]||void 0===f[0].raw)d.push.apply(d,f);else{var g=f[0];d.push(g[0]);for(var p=f.length,m=1;m<p;m++)d.push(f[m],g[m])}var w=(0,o.w)((function(e,t,n){var r=h&&e.as||c,a="",f=[],g=e;if(null==e.theme){for(var p in g={},e)g[p]=e[p];g.theme=s.useContext(o.T)}"string"==typeof e.className?a=function(e,t,n){var r="";return n.split(" ").forEach((function(n){void 0!==e[n]?t.push(e[n]+";"):n&&(r+=n+" ")})),r}(t.registered,f,e.className):null!=e.className&&(a=e.className+" ");var b=function(e,t,n){if(1===e.length&&"object"==typeof e[0]&&null!==e[0]&&void 0!==e[0].styles)return e[0];var r=!0,i="";T=void 0;var o=e[0];null==o||void 0===o.raw?(r=!1,i+=M(n,t,o)):i+=o[0];for(var a=1;a<e.length;a++)i+=M(n,t,e[a]),r&&(i+=o[a]);C.lastIndex=0;for(var s,c="";null!==(s=C.exec(i));)c+="-"+s[1];var u=function(e){for(var t,n=0,r=0,i=e.length;i>=4;++r,i-=4)t=1540483477*(65535&(t=255&e.charCodeAt(r)|(255&e.charCodeAt(++r))<<8|(255&e.charCodeAt(++r))<<16|(255&e.charCodeAt(++r))<<24))+(59797*(t>>>16)<<16),n=1540483477*(65535&(t^=t>>>24))+(59797*(t>>>16)<<16)^1540483477*(65535&n)+(59797*(n>>>16)<<16);switch(i){case 3:n^=(255&e.charCodeAt(r+2))<<16;case 2:n^=(255&e.charCodeAt(r+1))<<8;case 1:n=1540483477*(65535&(n^=255&e.charCodeAt(r)))+(59797*(n>>>16)<<16)}return(((n=1540483477*(65535&(n^=n>>>13))+(59797*(n>>>16)<<16))^n>>>15)>>>0).toString(36)}(i)+c;return{name:u,styles:i,next:T}}(d.concat(f),t.registered,g);a+=t.key+"-"+b.name,void 0!==i&&(a+=" "+i);var m=h&&void 0===u?$(r):l,w={};for(var v in e)h&&"as"===v||m(v)&&(w[v]=e[v]);return w.className=a,n&&(w.ref=n),s.createElement(s.Fragment,null,s.createElement(N,{cache:t,serialized:b,isStringTag:"string"==typeof r}),s.createElement(r,w))}));return w.displayName=void 0!==r?r:"Styled("+("string"==typeof c?c:c.displayName||c.name||"Component")+")",w.defaultProps=t.defaultProps,w.__emotion_real=w,w.__emotion_base=c,w.__emotion_styles=d,w.__emotion_forwardProp=u,Object.defineProperty(w,"toString",{value:function(){return"."+i}}),w.withComponent=function(t,r){return e(t,b({},n,r,{shouldForwardProp:R(w,r,!0)})).apply(void 0,d)},w}}.bind(null);function D(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","marquee","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","tspan"].forEach((function(e){L[e]=L(e)}));var F,B,z={exports:{}},U=z.exports={};function q(){throw new Error("setTimeout has not been defined")}function H(){throw new Error("clearTimeout has not been defined")}function J(e){if(F===setTimeout)return setTimeout(e,0);if((F===q||!F)&&setTimeout)return F=setTimeout,setTimeout(e,0);try{return F(e,0)}catch{try{return F.call(null,e,0)}catch{return F.call(this,e,0)}}}!function(){try{F="function"==typeof setTimeout?setTimeout:q}catch{F=q}try{B="function"==typeof clearTimeout?clearTimeout:H}catch{B=H}}();var G,V=[],K=!1,W=-1;function X(){!K||!G||(K=!1,G.length?V=G.concat(V):W=-1,V.length&&Y())}function Y(){if(!K){var e=J(X);K=!0;for(var t=V.length;t;){for(G=V,V=[];++W<t;)G&&G[W].run();W=-1,t=V.length}G=null,K=!1,function(e){if(B===clearTimeout)return clearTimeout(e);if((B===H||!B)&&clearTimeout)return B=clearTimeout,clearTimeout(e);try{return B(e)}catch{try{return B.call(null,e)}catch{return B.call(this,e)}}}(e)}}function Q(e,t){this.fun=e,this.array=t}function Z(){}U.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];V.push(new Q(e,t)),1===V.length&&!K&&J(Y)},Q.prototype.run=function(){this.fun.apply(null,this.array)},U.title="browser",U.browser=!0,U.env={},U.argv=[],U.version="",U.versions={},U.on=Z,U.addListener=Z,U.once=Z,U.off=Z,U.removeListener=Z,U.removeAllListeners=Z,U.emit=Z,U.prependListener=Z,U.prependOnceListener=Z,U.listeners=function(e){return[]},U.binding=function(e){throw new Error("process.binding is not supported")},U.cwd=function(){return"/"},U.chdir=function(e){throw new Error("process.chdir is not supported")},U.umask=function(){return 0};const ee=D(z.exports);function te(e){if("string"==typeof e||"number"==typeof e)return""+e;let t="";if(Array.isArray(e))for(let n,r=0;r<e.length;r++)""!==(n=te(e[r]))&&(t+=(t&&" ")+n);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var ne={value:()=>{}};function re(){for(var e,t=0,n=arguments.length,r={};t<n;++t){if(!(e=arguments[t]+"")||e in r||/[\s.]/.test(e))throw new Error("illegal type: "+e);r[e]=[]}return new ie(r)}function ie(e){this._=e}function oe(e,t){for(var n,r=0,i=e.length;r<i;++r)if((n=e[r]).name===t)return n.value}function ae(e,t,n){for(var r=0,i=e.length;r<i;++r)if(e[r].name===t){e[r]=ne,e=e.slice(0,r).concat(e.slice(r+1));break}return null!=n&&e.push({name:t,value:n}),e}ie.prototype=re.prototype={constructor:ie,on:function(e,t){var n,r=this._,i=function(e,t){return e.trim().split(/^|\s+/).map((function(e){var n="",r=e.indexOf(".");if(r>=0&&(n=e.slice(r+1),e=e.slice(0,r)),e&&!t.hasOwnProperty(e))throw new Error("unknown type: "+e);return{type:e,name:n}}))}(e+"",r),o=-1,a=i.length;if(!(arguments.length<2)){if(null!=t&&"function"!=typeof t)throw new Error("invalid callback: "+t);for(;++o<a;)if(n=(e=i[o]).type)r[n]=ae(r[n],e.name,t);else if(null==t)for(n in r)r[n]=ae(r[n],e.name,null);return this}for(;++o<a;)if((n=(e=i[o]).type)&&(n=oe(r[n],e.name)))return n},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new ie(e)},call:function(e,t){if((n=arguments.length-2)>0)for(var n,r,i=new Array(n),o=0;o<n;++o)i[o]=arguments[o+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(o=0,n=(r=this._[e]).length;o<n;++o)r[o].value.apply(t,i)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],i=0,o=r.length;i<o;++i)r[i].value.apply(t,n)}};var se="http://www.w3.org/1999/xhtml";const ce={svg:"http://www.w3.org/2000/svg",xhtml:se,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function ue(e){var t=e+="",n=t.indexOf(":");return n>=0&&"xmlns"!==(t=e.slice(0,n))&&(e=e.slice(n+1)),ce.hasOwnProperty(t)?{space:ce[t],local:e}:e}function le(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===se&&t.documentElement.namespaceURI===se?t.createElement(e):t.createElementNS(n,e)}}function he(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function fe(e){var t=ue(e);return(t.local?he:le)(t)}function de(){}function ge(e){return null==e?de:function(){return this.querySelector(e)}}function pe(){return[]}function be(e){return null==e?pe:function(){return this.querySelectorAll(e)}}function me(e){return function(){return this.matches(e)}}function we(e){return function(t){return t.matches(e)}}var ve=Array.prototype.find;function ye(){return this.firstElementChild}var Se=Array.prototype.filter;function ke(){return Array.from(this.children)}function Ee(e){return new Array(e.length)}function xe(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function Me(e,t,n,r,i,o){for(var a,s=0,c=t.length,u=o.length;s<u;++s)(a=t[s])?(a.__data__=o[s],r[s]=a):n[s]=new xe(e,o[s]);for(;s<c;++s)(a=t[s])&&(i[s]=a)}function Te(e,t,n,r,i,o,a){var s,c,u,l=new Map,h=t.length,f=o.length,d=new Array(h);for(s=0;s<h;++s)(c=t[s])&&(d[s]=u=a.call(c,c.__data__,s,t)+"",l.has(u)?i[s]=c:l.set(u,c));for(s=0;s<f;++s)u=a.call(e,o[s],s,o)+"",(c=l.get(u))?(r[s]=c,c.__data__=o[s],l.delete(u)):n[s]=new xe(e,o[s]);for(s=0;s<h;++s)(c=t[s])&&l.get(d[s])===c&&(i[s]=c)}function Ce(e){return e.__data__}function _e(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function Pe(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function Ie(e){return function(){this.removeAttribute(e)}}function Ae(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Oe(e,t){return function(){this.setAttribute(e,t)}}function je(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function $e(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}}function Re(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function Ne(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function Le(e){return function(){this.style.removeProperty(e)}}function De(e,t,n){return function(){this.style.setProperty(e,t,n)}}function Fe(e,t,n){return function(){var r=t.apply(this,arguments);null==r?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function Be(e,t){return e.style.getPropertyValue(t)||Ne(e).getComputedStyle(e,null).getPropertyValue(t)}function ze(e){return function(){delete this[e]}}function Ue(e,t){return function(){this[e]=t}}function qe(e,t){return function(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}}function He(e){return e.trim().split(/^|\s+/)}function Je(e){return e.classList||new Ge(e)}function Ge(e){this._node=e,this._names=He(e.getAttribute("class")||"")}function Ve(e,t){for(var n=Je(e),r=-1,i=t.length;++r<i;)n.add(t[r])}function Ke(e,t){for(var n=Je(e),r=-1,i=t.length;++r<i;)n.remove(t[r])}function We(e){return function(){Ve(this,e)}}function Xe(e){return function(){Ke(this,e)}}function Ye(e,t){return function(){(t.apply(this,arguments)?Ve:Ke)(this,e)}}function Qe(){this.textContent=""}function Ze(e){return function(){this.textContent=e}}function et(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function tt(){this.innerHTML=""}function nt(e){return function(){this.innerHTML=e}}function rt(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function it(){this.nextSibling&&this.parentNode.appendChild(this)}function ot(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function at(){return null}function st(){var e=this.parentNode;e&&e.removeChild(this)}function ct(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function ut(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function lt(e){return function(){var t=this.__on;if(t){for(var n,r=0,i=-1,o=t.length;r<o;++r)n=t[r],e.type&&n.type!==e.type||n.name!==e.name?t[++i]=n:this.removeEventListener(n.type,n.listener,n.options);++i?t.length=i:delete this.__on}}}function ht(e,t,n){return function(){var r,i=this.__on,o=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(i)for(var a=0,s=i.length;a<s;++a)if((r=i[a]).type===e.type&&r.name===e.name)return this.removeEventListener(r.type,r.listener,r.options),this.addEventListener(r.type,r.listener=o,r.options=n),void(r.value=t);this.addEventListener(e.type,o,n),r={type:e.type,name:e.name,value:t,listener:o,options:n},i?i.push(r):this.__on=[r]}}function ft(e,t,n){var r=Ne(e),i=r.CustomEvent;"function"==typeof i?i=new i(t,n):(i=r.document.createEvent("Event"),n?(i.initEvent(t,n.bubbles,n.cancelable),i.detail=n.detail):i.initEvent(t,!1,!1)),e.dispatchEvent(i)}function dt(e,t){return function(){return ft(this,e,t)}}function gt(e,t){return function(){return ft(this,e,t.apply(this,arguments))}}xe.prototype={constructor:xe,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}},Ge.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var pt=[null];function bt(e,t){this._groups=e,this._parents=t}function mt(){return new bt([[document.documentElement]],pt)}function wt(e){return"string"==typeof e?new bt([[document.querySelector(e)]],[document.documentElement]):new bt([[e]],pt)}function vt(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,[(r=r.matrixTransform(t.getScreenCTM().inverse())).x,r.y]}if(t.getBoundingClientRect){var i=t.getBoundingClientRect();return[e.clientX-i.left-t.clientLeft,e.clientY-i.top-t.clientTop]}}return[e.pageX,e.pageY]}bt.prototype=mt.prototype={constructor:bt,select:function(e){"function"!=typeof e&&(e=ge(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o,a,s=t[i],c=s.length,u=r[i]=new Array(c),l=0;l<c;++l)(o=s[l])&&(a=e.call(o,o.__data__,l,s))&&("__data__"in o&&(a.__data__=o.__data__),u[l]=a);return new bt(r,this._parents)},selectAll:function(e){e="function"==typeof e?function(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}(e):be(e);for(var t=this._groups,n=t.length,r=[],i=[],o=0;o<n;++o)for(var a,s=t[o],c=s.length,u=0;u<c;++u)(a=s[u])&&(r.push(e.call(a,a.__data__,u,s)),i.push(a));return new bt(r,i)},selectChild:function(e){return this.select(null==e?ye:function(e){return function(){return ve.call(this.children,e)}}("function"==typeof e?e:we(e)))},selectChildren:function(e){return this.selectAll(null==e?ke:function(e){return function(){return Se.call(this.children,e)}}("function"==typeof e?e:we(e)))},filter:function(e){"function"!=typeof e&&(e=me(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o,a=t[i],s=a.length,c=r[i]=[],u=0;u<s;++u)(o=a[u])&&e.call(o,o.__data__,u,a)&&c.push(o);return new bt(r,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,Ce);var n=t?Te:Me,r=this._parents,i=this._groups;"function"!=typeof e&&(e=function(e){return function(){return e}}(e));for(var o=i.length,a=new Array(o),s=new Array(o),c=new Array(o),u=0;u<o;++u){var l=r[u],h=i[u],f=h.length,d=_e(e.call(l,l&&l.__data__,u,r)),g=d.length,p=s[u]=new Array(g),b=a[u]=new Array(g);n(l,h,p,b,c[u]=new Array(f),d,t);for(var m,w,v=0,y=0;v<g;++v)if(m=p[v]){for(v>=y&&(y=v+1);!(w=b[y])&&++y<g;);m._next=w||null}}return(a=new bt(a,r))._enter=s,a._exit=c,a},enter:function(){return new bt(this._enter||this._groups.map(Ee),this._parents)},exit:function(){return new bt(this._exit||this._groups.map(Ee),this._parents)},join:function(e,t,n){var r=this.enter(),i=this,o=this.exit();return"function"==typeof e?(r=e(r))&&(r=r.selection()):r=r.append(e+""),null!=t&&(i=t(i))&&(i=i.selection()),null==n?o.remove():n(o),r&&i?r.merge(i).order():i},merge:function(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,i=n.length,o=r.length,a=Math.min(i,o),s=new Array(i),c=0;c<a;++c)for(var u,l=n[c],h=r[c],f=l.length,d=s[c]=new Array(f),g=0;g<f;++g)(u=l[g]||h[g])&&(d[g]=u);for(;c<i;++c)s[c]=n[c];return new bt(s,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r,i=e[t],o=i.length-1,a=i[o];--o>=0;)(r=i[o])&&(a&&4^r.compareDocumentPosition(a)&&a.parentNode.insertBefore(r,a),a=r);return this},sort:function(e){function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}e||(e=Pe);for(var n=this._groups,r=n.length,i=new Array(r),o=0;o<r;++o){for(var a,s=n[o],c=s.length,u=i[o]=new Array(c),l=0;l<c;++l)(a=s[l])&&(u[l]=a);u.sort(t)}return new bt(i,this._parents).order()},call:function(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],i=0,o=r.length;i<o;++i){var a=r[i];if(a)return a}return null},size:function(){let e=0;for(const t of this)++e;return e},empty:function(){return!this.node()},each:function(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var i,o=t[n],a=0,s=o.length;a<s;++a)(i=o[a])&&e.call(i,i.__data__,a,o);return this},attr:function(e,t){var n=ue(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((null==t?n.local?Ae:Ie:"function"==typeof t?n.local?Re:$e:n.local?je:Oe)(n,t))},style:function(e,t,n){return arguments.length>1?this.each((null==t?Le:"function"==typeof t?Fe:De)(e,t,n??"")):Be(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?ze:"function"==typeof t?qe:Ue)(e,t)):this.node()[e]},classed:function(e,t){var n=He(e+"");if(arguments.length<2){for(var r=Je(this.node()),i=-1,o=n.length;++i<o;)if(!r.contains(n[i]))return!1;return!0}return this.each(("function"==typeof t?Ye:t?We:Xe)(n,t))},text:function(e){return arguments.length?this.each(null==e?Qe:("function"==typeof e?et:Ze)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?tt:("function"==typeof e?rt:nt)(e)):this.node().innerHTML},raise:function(){return this.each(it)},lower:function(){return this.each(ot)},append:function(e){var t="function"==typeof e?e:fe(e);return this.select((function(){return this.appendChild(t.apply(this,arguments))}))},insert:function(e,t){var n="function"==typeof e?e:fe(e),r=null==t?at:"function"==typeof t?t:ge(t);return this.select((function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)}))},remove:function(){return this.each(st)},clone:function(e){return this.select(e?ut:ct)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,n){var r,i,o=function(e){return e.trim().split(/^|\s+/).map((function(e){var t="",n=e.indexOf(".");return n>=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}}))}(e+""),a=o.length;if(!(arguments.length<2)){for(s=t?ht:lt,r=0;r<a;++r)this.each(s(o[r],t,n));return this}var s=this.node().__on;if(s)for(var c,u=0,l=s.length;u<l;++u)for(r=0,c=s[u];r<a;++r)if((i=o[r]).type===c.type&&i.name===c.name)return c.value},dispatch:function(e,t){return this.each(("function"==typeof t?gt:dt)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r,i=e[t],o=0,a=i.length;o<a;++o)(r=i[o])&&(yield r)}};const yt={passive:!1},St={capture:!0,passive:!1};function kt(e){e.stopImmediatePropagation()}function Et(e){e.preventDefault(),e.stopImmediatePropagation()}function xt(e){var t=e.document.documentElement,n=wt(e).on("dragstart.drag",Et,St);"onselectstart"in t?n.on("selectstart.drag",Et,St):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function Mt(e,t){var n=e.document.documentElement,r=wt(e).on("dragstart.drag",null);t&&(r.on("click.drag",Et,St),setTimeout((function(){r.on("click.drag",null)}),0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const Tt=e=>()=>e;function Ct(e,{sourceEvent:t,subject:n,target:r,identifier:i,active:o,x:a,y:s,dx:c,dy:u,dispatch:l}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:i,enumerable:!0,configurable:!0},active:{value:o,enumerable:!0,configurable:!0},x:{value:a,enumerable:!0,configurable:!0},y:{value:s,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:l}})}function _t(e){return!e.ctrlKey&&!e.button}function Pt(){return this.parentNode}function It(e,t){return t??{x:e.x,y:e.y}}function At(){return navigator.maxTouchPoints||"ontouchstart"in this}function Ot(){var e,t,n,r,i=_t,o=Pt,a=It,s=At,c={},u=re("start","drag","end"),l=0,h=0;function f(e){e.on("mousedown.drag",d).filter(s).on("touchstart.drag",b).on("touchmove.drag",m,yt).on("touchend.drag touchcancel.drag",w).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function d(a,s){if(!r&&i.call(this,a,s)){var c=v(this,o.call(this,a,s),a,s,"mouse");c&&(wt(a.view).on("mousemove.drag",g,St).on("mouseup.drag",p,St),xt(a.view),kt(a),n=!1,e=a.clientX,t=a.clientY,c("start",a))}}function g(r){if(Et(r),!n){var i=r.clientX-e,o=r.clientY-t;n=i*i+o*o>h}c.mouse("drag",r)}function p(e){wt(e.view).on("mousemove.drag mouseup.drag",null),Mt(e.view,n),Et(e),c.mouse("end",e)}function b(e,t){if(i.call(this,e,t)){var n,r,a=e.changedTouches,s=o.call(this,e,t),c=a.length;for(n=0;n<c;++n)(r=v(this,s,e,t,a[n].identifier,a[n]))&&(kt(e),r("start",e,a[n]))}}function m(e){var t,n,r=e.changedTouches,i=r.length;for(t=0;t<i;++t)(n=c[r[t].identifier])&&(Et(e),n("drag",e,r[t]))}function w(e){var t,n,i=e.changedTouches,o=i.length;for(r&&clearTimeout(r),r=setTimeout((function(){r=null}),500),t=0;t<o;++t)(n=c[i[t].identifier])&&(kt(e),n("end",e,i[t]))}function v(e,t,n,r,i,o){var s,h,d,g=u.copy(),p=vt(o||n,t);if(null!=(d=a.call(e,new Ct("beforestart",{sourceEvent:n,target:f,identifier:i,active:l,x:p[0],y:p[1],dx:0,dy:0,dispatch:g}),r)))return s=d.x-p[0]||0,h=d.y-p[1]||0,function n(o,a,u){var b,m=p;switch(o){case"start":c[i]=n,b=l++;break;case"end":delete c[i],--l;case"drag":p=vt(u||a,t),b=l}g.call(o,e,new Ct(o,{sourceEvent:a,subject:d,target:f,identifier:i,active:b,x:p[0]+s,y:p[1]+h,dx:p[0]-m[0],dy:p[1]-m[1],dispatch:g}),r)}}return f.filter=function(e){return arguments.length?(i="function"==typeof e?e:Tt(!!e),f):i},f.container=function(e){return arguments.length?(o="function"==typeof e?e:Tt(e),f):o},f.subject=function(e){return arguments.length?(a="function"==typeof e?e:Tt(e),f):a},f.touchable=function(e){return arguments.length?(s="function"==typeof e?e:Tt(!!e),f):s},f.on=function(){var e=u.on.apply(u,arguments);return e===u?f:e},f.clickDistance=function(e){return arguments.length?(h=(e=+e)*e,f):Math.sqrt(h)},f}function jt(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function $t(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Rt(){}Ct.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};var Nt=.7,Lt=1/Nt,Dt="\\s*([+-]?\\d+)\\s*",Ft="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Bt="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",zt=/^#([0-9a-f]{3,8})$/,Ut=new RegExp(`^rgb\\(${Dt},${Dt},${Dt}\\)$`),qt=new RegExp(`^rgb\\(${Bt},${Bt},${Bt}\\)$`),Ht=new RegExp(`^rgba\\(${Dt},${Dt},${Dt},${Ft}\\)$`),Jt=new RegExp(`^rgba\\(${Bt},${Bt},${Bt},${Ft}\\)$`),Gt=new RegExp(`^hsl\\(${Ft},${Bt},${Bt}\\)$`),Vt=new RegExp(`^hsla\\(${Ft},${Bt},${Bt},${Ft}\\)$`),Kt={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function Wt(){return this.rgb().formatHex()}function Xt(){return this.rgb().formatRgb()}function Yt(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=zt.exec(e))?(n=t[1].length,t=parseInt(t[1],16),6===n?Qt(t):3===n?new tn(t>>8&15|t>>4&240,t>>4&15|240&t,(15&t)<<4|15&t,1):8===n?Zt(t>>24&255,t>>16&255,t>>8&255,(255&t)/255):4===n?Zt(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|240&t,((15&t)<<4|15&t)/255):null):(t=Ut.exec(e))?new tn(t[1],t[2],t[3],1):(t=qt.exec(e))?new tn(255*t[1]/100,255*t[2]/100,255*t[3]/100,1):(t=Ht.exec(e))?Zt(t[1],t[2],t[3],t[4]):(t=Jt.exec(e))?Zt(255*t[1]/100,255*t[2]/100,255*t[3]/100,t[4]):(t=Gt.exec(e))?cn(t[1],t[2]/100,t[3]/100,1):(t=Vt.exec(e))?cn(t[1],t[2]/100,t[3]/100,t[4]):Kt.hasOwnProperty(e)?Qt(Kt[e]):"transparent"===e?new tn(NaN,NaN,NaN,0):null}function Qt(e){return new tn(e>>16&255,e>>8&255,255&e,1)}function Zt(e,t,n,r){return r<=0&&(e=t=n=NaN),new tn(e,t,n,r)}function en(e,t,n,r){return 1===arguments.length?function(e){return e instanceof Rt||(e=Yt(e)),e?new tn((e=e.rgb()).r,e.g,e.b,e.opacity):new tn}(e):new tn(e,t,n,r??1)}function tn(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}function nn(){return`#${sn(this.r)}${sn(this.g)}${sn(this.b)}`}function rn(){const e=on(this.opacity);return`${1===e?"rgb(":"rgba("}${an(this.r)}, ${an(this.g)}, ${an(this.b)}${1===e?")":`, ${e})`}`}function on(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function an(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function sn(e){return((e=an(e))<16?"0":"")+e.toString(16)}function cn(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new ln(e,t,n,r)}function un(e){if(e instanceof ln)return new ln(e.h,e.s,e.l,e.opacity);if(e instanceof Rt||(e=Yt(e)),!e)return new ln;if(e instanceof ln)return e;var t=(e=e.rgb()).r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),o=Math.max(t,n,r),a=NaN,s=o-i,c=(o+i)/2;return s?(a=t===o?(n-r)/s+6*(n<r):n===o?(r-t)/s+2:(t-n)/s+4,s/=c<.5?o+i:2-o-i,a*=60):s=c>0&&c<1?0:a,new ln(a,s,c,e.opacity)}function ln(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}function hn(e){return(e=(e||0)%360)<0?e+360:e}function fn(e){return Math.max(0,Math.min(1,e||0))}function dn(e,t,n){return 255*(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)}jt(Rt,Yt,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Wt,formatHex:Wt,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return un(this).formatHsl()},formatRgb:Xt,toString:Xt}),jt(tn,en,$t(Rt,{brighter(e){return e=null==e?Lt:Math.pow(Lt,e),new tn(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=null==e?Nt:Math.pow(Nt,e),new tn(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new tn(an(this.r),an(this.g),an(this.b),on(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:nn,formatHex:nn,formatHex8:function(){return`#${sn(this.r)}${sn(this.g)}${sn(this.b)}${sn(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:rn,toString:rn})),jt(ln,(function(e,t,n,r){return 1===arguments.length?un(e):new ln(e,t,n,r??1)}),$t(Rt,{brighter(e){return e=null==e?Lt:Math.pow(Lt,e),new ln(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=null==e?Nt:Math.pow(Nt,e),new ln(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+360*(this.h<0),t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,i=2*n-r;return new tn(dn(e>=240?e-240:e+120,i,r),dn(e,i,r),dn(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new ln(hn(this.h),fn(this.s),fn(this.l),on(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=on(this.opacity);return`${1===e?"hsl(":"hsla("}${hn(this.h)}, ${100*fn(this.s)}%, ${100*fn(this.l)}%${1===e?")":`, ${e})`}`}}));const gn=e=>()=>e;function pn(e,t){var n=t-e;return n?function(e,t){return function(n){return e+n*t}}(e,n):gn(isNaN(e)?t:e)}const bn=function e(t){var n=function(e){return 1==(e=+e)?pn:function(t,n){return n-t?function(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}(t,n,e):gn(isNaN(t)?n:t)}}(t);function r(e,t){var r=n((e=en(e)).r,(t=en(t)).r),i=n(e.g,t.g),o=n(e.b,t.b),a=pn(e.opacity,t.opacity);return function(t){return e.r=r(t),e.g=i(t),e.b=o(t),e.opacity=a(t),e+""}}return r.gamma=e,r}(1);function mn(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var wn=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,vn=new RegExp(wn.source,"g");function yn(e,t){var n,r,i,o=wn.lastIndex=vn.lastIndex=0,a=-1,s=[],c=[];for(e+="",t+="";(n=wn.exec(e))&&(r=vn.exec(t));)(i=r.index)>o&&(i=t.slice(o,i),s[a]?s[a]+=i:s[++a]=i),(n=n[0])===(r=r[0])?s[a]?s[a]+=r:s[++a]=r:(s[++a]=null,c.push({i:a,x:mn(n,r)})),o=vn.lastIndex;return o<t.length&&(i=t.slice(o),s[a]?s[a]+=i:s[++a]=i),s.length<2?c[0]?function(e){return function(t){return e(t)+""}}(c[0].x):function(e){return function(){return e}}(t):(t=c.length,function(e){for(var n,r=0;r<t;++r)s[(n=c[r]).i]=n.x(e);return s.join("")})}var Sn,kn=180/Math.PI,En={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function xn(e,t,n,r,i,o){var a,s,c;return(a=Math.sqrt(e*e+t*t))&&(e/=a,t/=a),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(s=Math.sqrt(n*n+r*r))&&(n/=s,r/=s,c/=s),e*r<t*n&&(e=-e,t=-t,c=-c,a=-a),{translateX:i,translateY:o,rotate:Math.atan2(t,e)*kn,skewX:Math.atan(c)*kn,scaleX:a,scaleY:s}}function Mn(e,t,n,r){function i(e){return e.length?e.pop()+" ":""}return function(o,a){var s=[],c=[];return o=e(o),a=e(a),function(e,r,i,o,a,s){if(e!==i||r!==o){var c=a.push("translate(",null,t,null,n);s.push({i:c-4,x:mn(e,i)},{i:c-2,x:mn(r,o)})}else(i||o)&&a.push("translate("+i+t+o+n)}(o.translateX,o.translateY,a.translateX,a.translateY,s,c),function(e,t,n,o){e!==t?(e-t>180?t+=360:t-e>180&&(e+=360),o.push({i:n.push(i(n)+"rotate(",null,r)-2,x:mn(e,t)})):t&&n.push(i(n)+"rotate("+t+r)}(o.rotate,a.rotate,s,c),function(e,t,n,o){e!==t?o.push({i:n.push(i(n)+"skewX(",null,r)-2,x:mn(e,t)}):t&&n.push(i(n)+"skewX("+t+r)}(o.skewX,a.skewX,s,c),function(e,t,n,r,o,a){if(e!==n||t!==r){var s=o.push(i(o)+"scale(",null,",",null,")");a.push({i:s-4,x:mn(e,n)},{i:s-2,x:mn(t,r)})}else(1!==n||1!==r)&&o.push(i(o)+"scale("+n+","+r+")")}(o.scaleX,o.scaleY,a.scaleX,a.scaleY,s,c),o=a=null,function(e){for(var t,n=-1,r=c.length;++n<r;)s[(t=c[n]).i]=t.x(e);return s.join("")}}}var Tn=Mn((function(e){const t=new("function"==typeof DOMMatrix?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?En:xn(t.a,t.b,t.c,t.d,t.e,t.f)}),"px, ","px)","deg)"),Cn=Mn((function(e){return null!=e&&(Sn||(Sn=document.createElementNS("http://www.w3.org/2000/svg","g")),Sn.setAttribute("transform",e),e=Sn.transform.baseVal.consolidate())?xn((e=e.matrix).a,e.b,e.c,e.d,e.e,e.f):En}),", ",")",")");function _n(e){return((e=Math.exp(e))+1/e)/2}const Pn=function e(t,n,r){function i(e,i){var o,a,s=e[0],c=e[1],u=e[2],l=i[0],h=i[1],f=i[2],d=l-s,g=h-c,p=d*d+g*g;if(p<1e-12)a=Math.log(f/u)/t,o=function(e){return[s+e*d,c+e*g,u*Math.exp(t*e*a)]};else{var b=Math.sqrt(p),m=(f*f-u*u+r*p)/(2*u*n*b),w=(f*f-u*u-r*p)/(2*f*n*b),v=Math.log(Math.sqrt(m*m+1)-m),y=Math.log(Math.sqrt(w*w+1)-w);a=(y-v)/t,o=function(e){var r=e*a,i=_n(v),o=u/(n*b)*(i*function(e){return((e=Math.exp(2*e))-1)/(e+1)}(t*r+v)-function(e){return((e=Math.exp(e))-1/e)/2}(v));return[s+o*d,c+o*g,u*i/_n(t*r+v)]}}return o.duration=1e3*a*t/Math.SQRT2,o}return i.rho=function(t){var n=Math.max(.001,+t),r=n*n;return e(n,r,r*r)},i}(Math.SQRT2,2,4);var In,An,On=0,jn=0,$n=0,Rn=1e3,Nn=0,Ln=0,Dn=0,Fn="object"==typeof performance&&performance.now?performance:Date,Bn="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function zn(){return Ln||(Bn(Un),Ln=Fn.now()+Dn)}function Un(){Ln=0}function qn(){this._call=this._time=this._next=null}function Hn(e,t,n){var r=new qn;return r.restart(e,t,n),r}function Jn(){Ln=(Nn=Fn.now())+Dn,On=jn=0;try{!function(){zn(),++On;for(var e,t=In;t;)(e=Ln-t._time)>=0&&t._call.call(void 0,e),t=t._next;--On}()}finally{On=0,function(){for(var e,t,n=In,r=1/0;n;)n._call?(r>n._time&&(r=n._time),e=n,n=n._next):(t=n._next,n._next=null,n=e?e._next=t:In=t);An=e,Vn(r)}(),Ln=0}}function Gn(){var e=Fn.now(),t=e-Nn;t>Rn&&(Dn-=t,Nn=e)}function Vn(e){On||(jn&&(jn=clearTimeout(jn)),e-Ln>24?(e<1/0&&(jn=setTimeout(Jn,e-Fn.now()-Dn)),$n&&($n=clearInterval($n))):($n||(Nn=Fn.now(),$n=setInterval(Gn,Rn)),On=1,Bn(Jn)))}function Kn(e,t,n){var r=new qn;return t=null==t?0:+t,r.restart((n=>{r.stop(),e(n+t)}),t,n),r}qn.prototype=Hn.prototype={constructor:qn,restart:function(e,t,n){if("function"!=typeof e)throw new TypeError("callback is not a function");n=(null==n?zn():+n)+(null==t?0:+t),!this._next&&An!==this&&(An?An._next=this:In=this,An=this),this._call=e,this._time=n,Vn()},stop:function(){this._call&&(this._call=null,this._time=1/0,Vn())}};var Wn=re("start","end","cancel","interrupt"),Xn=[],Yn=0,Qn=2,Zn=3,er=5,tr=6;function nr(e,t,n,r,i,o){var a=e.__transition;if(a){if(n in a)return}else e.__transition={};!function(e,t,n){var r,i=e.__transition;function o(c){var u,l,h,f;if(1!==n.state)return s();for(u in i)if((f=i[u]).name===n.name){if(f.state===Zn)return Kn(o);4===f.state?(f.state=tr,f.timer.stop(),f.on.call("interrupt",e,e.__data__,f.index,f.group),delete i[u]):+u<t&&(f.state=tr,f.timer.stop(),f.on.call("cancel",e,e.__data__,f.index,f.group),delete i[u])}if(Kn((function(){n.state===Zn&&(n.state=4,n.timer.restart(a,n.delay,n.time),a(c))})),n.state=Qn,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Qn){for(n.state=Zn,r=new Array(h=n.tween.length),u=0,l=-1;u<h;++u)(f=n.tween[u].value.call(e,e.__data__,n.index,n.group))&&(r[++l]=f);r.length=l+1}}function a(t){for(var i=t<n.duration?n.ease.call(null,t/n.duration):(n.timer.restart(s),n.state=er,1),o=-1,a=r.length;++o<a;)r[o].call(e,i);n.state===er&&(n.on.call("end",e,e.__data__,n.index,n.group),s())}function s(){for(var r in n.state=tr,n.timer.stop(),delete i[t],i)return;delete e.__transition}i[t]=n,n.timer=Hn((function(e){n.state=1,n.timer.restart(o,n.delay,n.time),n.delay<=e&&o(e-n.delay)}),0,n.time)}(e,n,{name:t,index:r,group:i,on:Wn,tween:Xn,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:Yn})}function rr(e,t){var n=or(e,t);if(n.state>Yn)throw new Error("too late; already scheduled");return n}function ir(e,t){var n=or(e,t);if(n.state>Zn)throw new Error("too late; already running");return n}function or(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function ar(e,t){var n,r,i,o=e.__transition,a=!0;if(o){for(i in t=null==t?null:t+"",o)(n=o[i]).name===t?(r=n.state>Qn&&n.state<er,n.state=tr,n.timer.stop(),n.on.call(r?"interrupt":"cancel",e,e.__data__,n.index,n.group),delete o[i]):a=!1;a&&delete e.__transition}}function sr(e,t){var n,r;return function(){var i=ir(this,e),o=i.tween;if(o!==n)for(var a=0,s=(r=n=o).length;a<s;++a)if(r[a].name===t){(r=r.slice()).splice(a,1);break}i.tween=r}}function cr(e,t,n){var r,i;if("function"!=typeof n)throw new Error;return function(){var o=ir(this,e),a=o.tween;if(a!==r){i=(r=a).slice();for(var s={name:t,value:n},c=0,u=i.length;c<u;++c)if(i[c].name===t){i[c]=s;break}c===u&&i.push(s)}o.tween=i}}function ur(e,t,n){var r=e._id;return e.each((function(){var e=ir(this,r);(e.value||(e.value={}))[t]=n.apply(this,arguments)})),function(e){return or(e,r).value[t]}}function lr(e,t){var n;return("number"==typeof t?mn:t instanceof Yt?bn:(n=Yt(t))?(t=n,bn):yn)(e,t)}function hr(e){return function(){this.removeAttribute(e)}}function fr(e){return function(){this.removeAttributeNS(e.space,e.local)}}function dr(e,t,n){var r,i,o=n+"";return function(){var a=this.getAttribute(e);return a===o?null:a===r?i:i=t(r=a,n)}}function gr(e,t,n){var r,i,o=n+"";return function(){var a=this.getAttributeNS(e.space,e.local);return a===o?null:a===r?i:i=t(r=a,n)}}function pr(e,t,n){var r,i,o;return function(){var a,s,c=n(this);return null==c?void this.removeAttribute(e):(a=this.getAttribute(e))===(s=c+"")?null:a===r&&s===i?o:(i=s,o=t(r=a,c))}}function br(e,t,n){var r,i,o;return function(){var a,s,c=n(this);return null==c?void this.removeAttributeNS(e.space,e.local):(a=this.getAttributeNS(e.space,e.local))===(s=c+"")?null:a===r&&s===i?o:(i=s,o=t(r=a,c))}}function mr(e,t){var n,r;function i(){var i=t.apply(this,arguments);return i!==r&&(n=(r=i)&&function(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}(e,i)),n}return i._value=t,i}function wr(e,t){var n,r;function i(){var i=t.apply(this,arguments);return i!==r&&(n=(r=i)&&function(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}(e,i)),n}return i._value=t,i}function vr(e,t){return function(){rr(this,e).delay=+t.apply(this,arguments)}}function yr(e,t){return t=+t,function(){rr(this,e).delay=t}}function Sr(e,t){return function(){ir(this,e).duration=+t.apply(this,arguments)}}function kr(e,t){return t=+t,function(){ir(this,e).duration=t}}var Er=mt.prototype.constructor;function xr(e){return function(){this.style.removeProperty(e)}}var Mr=0;function Tr(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Cr(){return++Mr}var _r=mt.prototype;Tr.prototype={constructor:Tr,select:function(e){var t=this._name,n=this._id;"function"!=typeof e&&(e=ge(e));for(var r=this._groups,i=r.length,o=new Array(i),a=0;a<i;++a)for(var s,c,u=r[a],l=u.length,h=o[a]=new Array(l),f=0;f<l;++f)(s=u[f])&&(c=e.call(s,s.__data__,f,u))&&("__data__"in s&&(c.__data__=s.__data__),h[f]=c,nr(h[f],t,n,f,h,or(s,n)));return new Tr(o,this._parents,t,n)},selectAll:function(e){var t=this._name,n=this._id;"function"!=typeof e&&(e=be(e));for(var r=this._groups,i=r.length,o=[],a=[],s=0;s<i;++s)for(var c,u=r[s],l=u.length,h=0;h<l;++h)if(c=u[h]){for(var f,d=e.call(c,c.__data__,h,u),g=or(c,n),p=0,b=d.length;p<b;++p)(f=d[p])&&nr(f,t,n,p,d,g);o.push(d),a.push(c)}return new Tr(o,a,t,n)},selectChild:_r.selectChild,selectChildren:_r.selectChildren,filter:function(e){"function"!=typeof e&&(e=me(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o,a=t[i],s=a.length,c=r[i]=[],u=0;u<s;++u)(o=a[u])&&e.call(o,o.__data__,u,a)&&c.push(o);return new Tr(r,this._parents,this._name,this._id)},merge:function(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,i=n.length,o=Math.min(r,i),a=new Array(r),s=0;s<o;++s)for(var c,u=t[s],l=n[s],h=u.length,f=a[s]=new Array(h),d=0;d<h;++d)(c=u[d]||l[d])&&(f[d]=c);for(;s<r;++s)a[s]=t[s];return new Tr(a,this._parents,this._name,this._id)},selection:function(){return new Er(this._groups,this._parents)},transition:function(){for(var e=this._name,t=this._id,n=Cr(),r=this._groups,i=r.length,o=0;o<i;++o)for(var a,s=r[o],c=s.length,u=0;u<c;++u)if(a=s[u]){var l=or(a,t);nr(a,e,n,u,s,{time:l.time+l.delay+l.duration,delay:0,duration:l.duration,ease:l.ease})}return new Tr(r,this._parents,e,n)},call:_r.call,nodes:_r.nodes,node:_r.node,size:_r.size,empty:_r.empty,each:_r.each,on:function(e,t){var n=this._id;return arguments.length<2?or(this.node(),n).on.on(e):this.each(function(e,t,n){var r,i,o=function(e){return(e+"").trim().split(/^|\s+/).every((function(e){var t=e.indexOf(".");return t>=0&&(e=e.slice(0,t)),!e||"start"===e}))}(t)?rr:ir;return function(){var a=o(this,e),s=a.on;s!==r&&(i=(r=s).copy()).on(t,n),a.on=i}}(n,e,t))},attr:function(e,t){var n=ue(e),r="transform"===n?Cn:lr;return this.attrTween(e,"function"==typeof t?(n.local?br:pr)(n,r,ur(this,"attr."+e,t)):null==t?(n.local?fr:hr)(n):(n.local?gr:dr)(n,r,t))},attrTween:function(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(null==t)return this.tween(n,null);if("function"!=typeof t)throw new Error;var r=ue(e);return this.tween(n,(r.local?mr:wr)(r,t))},style:function(e,t,n){var r="transform"==(e+="")?Tn:lr;return null==t?this.styleTween(e,function(e,t){var n,r,i;return function(){var o=Be(this,e),a=(this.style.removeProperty(e),Be(this,e));return o===a?null:o===n&&a===r?i:i=t(n=o,r=a)}}(e,r)).on("end.style."+e,xr(e)):"function"==typeof t?this.styleTween(e,function(e,t,n){var r,i,o;return function(){var a=Be(this,e),s=n(this),c=s+"";return null==s&&(this.style.removeProperty(e),c=s=Be(this,e)),a===c?null:a===r&&c===i?o:(i=c,o=t(r=a,s))}}(e,r,ur(this,"style."+e,t))).each(function(e,t){var n,r,i,o,a="style."+t,s="end."+a;return function(){var c=ir(this,e),u=c.on,l=null==c.value[a]?o||(o=xr(t)):void 0;(u!==n||i!==l)&&(r=(n=u).copy()).on(s,i=l),c.on=r}}(this._id,e)):this.styleTween(e,function(e,t,n){var r,i,o=n+"";return function(){var a=Be(this,e);return a===o?null:a===r?i:i=t(r=a,n)}}(e,r,t),n).on("end.style."+e,null)},styleTween:function(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==t)return this.tween(r,null);if("function"!=typeof t)throw new Error;return this.tween(r,function(e,t,n){var r,i;function o(){var o=t.apply(this,arguments);return o!==i&&(r=(i=o)&&function(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}(e,o,n)),r}return o._value=t,o}(e,t,n??""))},text:function(e){return this.tween("text","function"==typeof e?function(e){return function(){var t=e(this);this.textContent=t??""}}(ur(this,"text",e)):function(e){return function(){this.textContent=e}}(null==e?"":e+""))},textTween:function(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(null==e)return this.tween(t,null);if("function"!=typeof e)throw new Error;return this.tween(t,function(e){var t,n;function r(){var r=e.apply(this,arguments);return r!==n&&(t=(n=r)&&function(e){return function(t){this.textContent=e.call(this,t)}}(r)),t}return r._value=e,r}(e))},remove:function(){return this.on("end.remove",(e=this._id,function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}));var e},tween:function(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r,i=or(this.node(),n).tween,o=0,a=i.length;o<a;++o)if((r=i[o]).name===e)return r.value;return null}return this.each((null==t?sr:cr)(n,e,t))},delay:function(e){var t=this._id;return arguments.length?this.each(("function"==typeof e?vr:yr)(t,e)):or(this.node(),t).delay},duration:function(e){var t=this._id;return arguments.length?this.each(("function"==typeof e?Sr:kr)(t,e)):or(this.node(),t).duration},ease:function(e){var t=this._id;return arguments.length?this.each(function(e,t){if("function"!=typeof t)throw new Error;return function(){ir(this,e).ease=t}}(t,e)):or(this.node(),t).ease},easeVarying:function(e){if("function"!=typeof e)throw new Error;return this.each(function(e,t){return function(){var n=t.apply(this,arguments);if("function"!=typeof n)throw new Error;ir(this,e).ease=n}}(this._id,e))},end:function(){var e,t,n=this,r=n._id,i=n.size();return new Promise((function(o,a){var s={value:a},c={value:function(){0==--i&&o()}};n.each((function(){var n=ir(this,r),i=n.on;i!==e&&((t=(e=i).copy())._.cancel.push(s),t._.interrupt.push(s),t._.end.push(c)),n.on=t})),0===i&&o()}))},[Symbol.iterator]:_r[Symbol.iterator]};var Pr={time:null,delay:0,duration:250,ease:function(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}};function Ir(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}mt.prototype.interrupt=function(e){return this.each((function(){ar(this,e)}))},mt.prototype.transition=function(e){var t,n;e instanceof Tr?(t=e._id,e=e._name):(t=Cr(),(n=Pr).time=zn(),e=null==e?null:e+"");for(var r=this._groups,i=r.length,o=0;o<i;++o)for(var a,s=r[o],c=s.length,u=0;u<c;++u)(a=s[u])&&nr(a,e,t,u,s,n||Ir(a,t));return new Tr(r,this._parents,e,t)};const Ar=e=>()=>e;function Or(e,{sourceEvent:t,target:n,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}})}function jr(e,t,n){this.k=e,this.x=t,this.y=n}jr.prototype={constructor:jr,scale:function(e){return 1===e?this:new jr(this.k*e,this.x,this.y)},translate:function(e,t){return 0===e&0===t?this:new jr(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var $r=new jr(1,0,0);function Rr(e){for(;!e.__zoom;)if(!(e=e.parentNode))return $r;return e.__zoom}function Nr(e){e.stopImmediatePropagation()}function Lr(e){e.preventDefault(),e.stopImmediatePropagation()}function Dr(e){return!(e.ctrlKey&&"wheel"!==e.type||e.button)}function Fr(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e).hasAttribute("viewBox")?[[(e=e.viewBox.baseVal).x,e.y],[e.x+e.width,e.y+e.height]]:[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]:[[0,0],[e.clientWidth,e.clientHeight]]}function Br(){return this.__zoom||$r}function zr(e){return-e.deltaY*(1===e.deltaMode?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function Ur(){return navigator.maxTouchPoints||"ontouchstart"in this}function qr(e,t,n){var r=e.invertX(t[0][0])-n[0][0],i=e.invertX(t[1][0])-n[1][0],o=e.invertY(t[0][1])-n[0][1],a=e.invertY(t[1][1])-n[1][1];return e.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),a>o?(o+a)/2:Math.min(0,o)||Math.max(0,a))}function Hr(){var e,t,n,r=Dr,i=Fr,o=qr,a=zr,s=Ur,c=[0,1/0],u=[[-1/0,-1/0],[1/0,1/0]],l=250,h=Pn,f=re("start","zoom","end"),d=500,g=150,p=0,b=10;function m(e){e.property("__zoom",Br).on("wheel.zoom",x,{passive:!1}).on("mousedown.zoom",M).on("dblclick.zoom",T).filter(s).on("touchstart.zoom",C).on("touchmove.zoom",_).on("touchend.zoom touchcancel.zoom",P).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function w(e,t){return(t=Math.max(c[0],Math.min(c[1],t)))===e.k?e:new jr(t,e.x,e.y)}function v(e,t,n){var r=t[0]-n[0]*e.k,i=t[1]-n[1]*e.k;return r===e.x&&i===e.y?e:new jr(e.k,r,i)}function y(e){return[(+e[0][0]+ +e[1][0])/2,(+e[0][1]+ +e[1][1])/2]}function S(e,t,n,r){e.on("start.zoom",(function(){k(this,arguments).event(r).start()})).on("interrupt.zoom end.zoom",(function(){k(this,arguments).event(r).end()})).tween("zoom",(function(){var e=this,o=arguments,a=k(e,o).event(r),s=i.apply(e,o),c=null==n?y(s):"function"==typeof n?n.apply(e,o):n,u=Math.max(s[1][0]-s[0][0],s[1][1]-s[0][1]),l=e.__zoom,f="function"==typeof t?t.apply(e,o):t,d=h(l.invert(c).concat(u/l.k),f.invert(c).concat(u/f.k));return function(e){if(1===e)e=f;else{var t=d(e),n=u/t[2];e=new jr(n,c[0]-t[0]*n,c[1]-t[1]*n)}a.zoom(null,e)}}))}function k(e,t,n){return!n&&e.__zooming||new E(e,t)}function E(e,t){this.that=e,this.args=t,this.active=0,this.sourceEvent=null,this.extent=i.apply(e,t),this.taps=0}function x(e,...t){if(r.apply(this,arguments)){var n=k(this,t).event(e),i=this.__zoom,s=Math.max(c[0],Math.min(c[1],i.k*Math.pow(2,a.apply(this,arguments)))),l=vt(e);if(n.wheel)(n.mouse[0][0]!==l[0]||n.mouse[0][1]!==l[1])&&(n.mouse[1]=i.invert(n.mouse[0]=l)),clearTimeout(n.wheel);else{if(i.k===s)return;n.mouse=[l,i.invert(l)],ar(this),n.start()}Lr(e),n.wheel=setTimeout((function(){n.wheel=null,n.end()}),g),n.zoom("mouse",o(v(w(i,s),n.mouse[0],n.mouse[1]),n.extent,u))}}function M(e,...t){if(!n&&r.apply(this,arguments)){var i=e.currentTarget,a=k(this,t,!0).event(e),s=wt(e.view).on("mousemove.zoom",(function(e){if(Lr(e),!a.moved){var t=e.clientX-l,n=e.clientY-h;a.moved=t*t+n*n>p}a.event(e).zoom("mouse",o(v(a.that.__zoom,a.mouse[0]=vt(e,i),a.mouse[1]),a.extent,u))}),!0).on("mouseup.zoom",(function(e){s.on("mousemove.zoom mouseup.zoom",null),Mt(e.view,a.moved),Lr(e),a.event(e).end()}),!0),c=vt(e,i),l=e.clientX,h=e.clientY;xt(e.view),Nr(e),a.mouse=[c,this.__zoom.invert(c)],ar(this),a.start()}}function T(e,...t){if(r.apply(this,arguments)){var n=this.__zoom,a=vt(e.changedTouches?e.changedTouches[0]:e,this),s=n.invert(a),c=n.k*(e.shiftKey?.5:2),h=o(v(w(n,c),a,s),i.apply(this,t),u);Lr(e),l>0?wt(this).transition().duration(l).call(S,h,a,e):wt(this).call(m.transform,h,a,e)}}function C(n,...i){if(r.apply(this,arguments)){var o,a,s,c,u=n.touches,l=u.length,h=k(this,i,n.changedTouches.length===l).event(n);for(Nr(n),a=0;a<l;++a)c=[c=vt(s=u[a],this),this.__zoom.invert(c),s.identifier],h.touch0?!h.touch1&&h.touch0[2]!==c[2]&&(h.touch1=c,h.taps=0):(h.touch0=c,o=!0,h.taps=1+!!e);e&&(e=clearTimeout(e)),o&&(h.taps<2&&(t=c[0],e=setTimeout((function(){e=null}),d)),ar(this),h.start())}}function _(e,...t){if(this.__zooming){var n,r,i,a,s=k(this,t).event(e),c=e.changedTouches,l=c.length;for(Lr(e),n=0;n<l;++n)i=vt(r=c[n],this),s.touch0&&s.touch0[2]===r.identifier?s.touch0[0]=i:s.touch1&&s.touch1[2]===r.identifier&&(s.touch1[0]=i);if(r=s.that.__zoom,s.touch1){var h=s.touch0[0],f=s.touch0[1],d=s.touch1[0],g=s.touch1[1],p=(p=d[0]-h[0])*p+(p=d[1]-h[1])*p,b=(b=g[0]-f[0])*b+(b=g[1]-f[1])*b;r=w(r,Math.sqrt(p/b)),i=[(h[0]+d[0])/2,(h[1]+d[1])/2],a=[(f[0]+g[0])/2,(f[1]+g[1])/2]}else{if(!s.touch0)return;i=s.touch0[0],a=s.touch0[1]}s.zoom("touch",o(v(r,i,a),s.extent,u))}}function P(e,...r){if(this.__zooming){var i,o,a=k(this,r).event(e),s=e.changedTouches,c=s.length;for(Nr(e),n&&clearTimeout(n),n=setTimeout((function(){n=null}),d),i=0;i<c;++i)o=s[i],a.touch0&&a.touch0[2]===o.identifier?delete a.touch0:a.touch1&&a.touch1[2]===o.identifier&&delete a.touch1;if(a.touch1&&!a.touch0&&(a.touch0=a.touch1,delete a.touch1),a.touch0)a.touch0[1]=this.__zoom.invert(a.touch0[0]);else if(a.end(),2===a.taps&&(o=vt(o,this),Math.hypot(t[0]-o[0],t[1]-o[1])<b)){var u=wt(this).on("dblclick.zoom");u&&u.apply(this,arguments)}}}return m.transform=function(e,t,n,r){var i=e.selection?e.selection():e;i.property("__zoom",Br),e!==i?S(e,t,n,r):i.interrupt().each((function(){k(this,arguments).event(r).start().zoom(null,"function"==typeof t?t.apply(this,arguments):t).end()}))},m.scaleBy=function(e,t,n,r){m.scaleTo(e,(function(){return this.__zoom.k*("function"==typeof t?t.apply(this,arguments):t)}),n,r)},m.scaleTo=function(e,t,n,r){m.transform(e,(function(){var e=i.apply(this,arguments),r=this.__zoom,a=null==n?y(e):"function"==typeof n?n.apply(this,arguments):n,s=r.invert(a),c="function"==typeof t?t.apply(this,arguments):t;return o(v(w(r,c),a,s),e,u)}),n,r)},m.translateBy=function(e,t,n,r){m.transform(e,(function(){return o(this.__zoom.translate("function"==typeof t?t.apply(this,arguments):t,"function"==typeof n?n.apply(this,arguments):n),i.apply(this,arguments),u)}),null,r)},m.translateTo=function(e,t,n,r,a){m.transform(e,(function(){var e=i.apply(this,arguments),a=this.__zoom,s=null==r?y(e):"function"==typeof r?r.apply(this,arguments):r;return o($r.translate(s[0],s[1]).scale(a.k).translate("function"==typeof t?-t.apply(this,arguments):-t,"function"==typeof n?-n.apply(this,arguments):-n),e,u)}),r,a)},E.prototype={event:function(e){return e&&(this.sourceEvent=e),this},start:function(){return 1==++this.active&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(e,t){return this.mouse&&"mouse"!==e&&(this.mouse[1]=t.invert(this.mouse[0])),this.touch0&&"touch"!==e&&(this.touch0[1]=t.invert(this.touch0[0])),this.touch1&&"touch"!==e&&(this.touch1[1]=t.invert(this.touch1[0])),this.that.__zoom=t,this.emit("zoom"),this},end:function(){return 0==--this.active&&(delete this.that.__zooming,this.emit("end")),this},emit:function(e){var t=wt(this.that).datum();f.call(e,this.that,new Or(e,{sourceEvent:this.sourceEvent,target:m,transform:this.that.__zoom,dispatch:f}),t)}},m.wheelDelta=function(e){return arguments.length?(a="function"==typeof e?e:Ar(+e),m):a},m.filter=function(e){return arguments.length?(r="function"==typeof e?e:Ar(!!e),m):r},m.touchable=function(e){return arguments.length?(s="function"==typeof e?e:Ar(!!e),m):s},m.extent=function(e){return arguments.length?(i="function"==typeof e?e:Ar([[+e[0][0],+e[0][1]],[+e[1][0],+e[1][1]]]),m):i},m.scaleExtent=function(e){return arguments.length?(c[0]=+e[0],c[1]=+e[1],m):[c[0],c[1]]},m.translateExtent=function(e){return arguments.length?(u[0][0]=+e[0][0],u[1][0]=+e[1][0],u[0][1]=+e[0][1],u[1][1]=+e[1][1],m):[[u[0][0],u[0][1]],[u[1][0],u[1][1]]]},m.constrain=function(e){return arguments.length?(o=e,m):o},m.duration=function(e){return arguments.length?(l=+e,m):l},m.interpolate=function(e){return arguments.length?(h=e,m):h},m.on=function(){var e=f.on.apply(f,arguments);return e===f?m:e},m.clickDistance=function(e){return arguments.length?(p=(e=+e)*e,m):Math.sqrt(p)},m.tapDistance=function(e){return arguments.length?(b=+e,m):b},m}Rr.prototype=jr.prototype;const Jr={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${"source"===e?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},Gr=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Vr=["Enter"," ","Escape"];var Kr,Wr,Xr,Yr;(Wr=Kr||(Kr={})).Strict="strict",Wr.Loose="loose",function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"}(Xr||(Xr={})),function(e){e.Partial="partial",e.Full="full"}(Yr||(Yr={}));const Qr={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null};var Zr,ei,ti;!function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"}(Zr||(Zr={})),function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"}(ei||(ei={})),function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"}(ti||(ti={}));const ni={[ti.Left]:ti.Right,[ti.Right]:ti.Left,[ti.Top]:ti.Bottom,[ti.Bottom]:ti.Top};function ri(e){return null===e?null:e?"valid":"invalid"}const ii=e=>"id"in e&&"source"in e&&"target"in e,oi=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),ai=(e,t=[0,0])=>{const{width:n,height:r}=$i(e),i=e.origin??t,o=n*i[0],a=r*i[1];return{x:e.position.x-o,y:e.position.y-a}},si=(e,t={nodeOrigin:[0,0],nodeLookup:void 0})=>{if("development"===ee.env.NODE_ENV&&!t.nodeLookup&&console.warn("Please use `getNodesBounds` from `useReactFlow`/`useSvelteFlow` hook to ensure correct values for sub flows. If not possible, you have to provide a nodeLookup to support sub flows."),0===e.length)return{x:0,y:0,width:0,height:0};const n=e.reduce(((e,n)=>{const r="string"==typeof n;let i=t.nodeLookup||r?void 0:n;t.nodeLookup&&(i=r?t.nodeLookup.get(n):oi(n)?n:t.nodeLookup.get(n.id));const o=i?Si(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return mi(e,o)}),{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return vi(n)},ci=(e,t={})=>{if(0===e.size)return{x:0,y:0,width:0,height:0};let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0};return e.forEach((e=>{if(void 0===t.filter||t.filter(e)){const t=Si(e);n=mi(n,t)}})),vi(n)},ui=(e,t,[n,r,i]=[0,0,1],o=!1,a=!1)=>{const s={..._i(t,[n,r,i]),width:t.width/i,height:t.height/i},c=[];for(const t of e.values()){const{measured:e,selectable:n=!0,hidden:r=!1}=t;if(a&&!n||r)continue;const i=e.width??t.width??t.initialWidth??null,u=e.height??t.height??t.initialHeight??null,l=Ei(s,yi(t)),h=(i??0)*(u??0),f=o&&l>0;(!t.internals.handleBounds||f||l>=h||t.dragging)&&c.push(t)}return c},li=(e,t)=>{const n=new Set;return e.forEach((e=>{n.add(e.id)})),t.filter((e=>n.has(e.source)||n.has(e.target)))};function hi({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:i,onError:o}){const a=n.get(e),s=a.parentId?n.get(a.parentId):void 0,{x:c,y:u}=s?s.internals.positionAbsolute:{x:0,y:0},l=a.origin??r;let h=i;if("parent"!==a.extent||a.expandParent)s&&ji(a.extent)&&(h=[[a.extent[0][0]+c,a.extent[0][1]+u],[a.extent[1][0]+c,a.extent[1][1]+u]]);else if(s){const e=s.measured.width,t=s.measured.height;e&&t&&(h=[[c,u],[c+e,u+t]])}else o?.("005",Jr.error005());const f=ji(h)?di(t,h,a.measured):t;return(void 0===a.measured.width||void 0===a.measured.height)&&o?.("015",Jr.error015()),{position:{x:f.x-c+(a.measured.width??0)*l[0],y:f.y-u+(a.measured.height??0)*l[1]},positionAbsolute:f}}const fi=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),di=(e={x:0,y:0},t,n)=>({x:fi(e.x,t[0][0],t[1][0]-(n?.width??0)),y:fi(e.y,t[0][1],t[1][1]-(n?.height??0))});function gi(e,t,n){const{width:r,height:i}=$i(n),{x:o,y:a}=n.internals.positionAbsolute;return di(e,[[o,a],[o+r,a+i]],t)}const pi=(e,t,n)=>e<t?fi(Math.abs(e-t),1,t)/t:e>n?-fi(Math.abs(e-n),1,t)/t:0,bi=(e,t,n=15,r=40)=>[pi(e.x,r,t.width-r)*n,pi(e.y,r,t.height-r)*n],mi=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),wi=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),vi=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),yi=(e,t=[0,0])=>{const{x:n,y:r}=oi(e)?e.internals.positionAbsolute:ai(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},Si=(e,t=[0,0])=>{const{x:n,y:r}=oi(e)?e.internals.positionAbsolute:ai(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},ki=(e,t)=>vi(mi(wi(e),wi(t))),Ei=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},xi=e=>Mi(e.width)&&Mi(e.height)&&Mi(e.x)&&Mi(e.y),Mi=e=>!isNaN(e)&&isFinite(e),Ti=(e,t)=>{"development"===ee.env.NODE_ENV&&console.warn(`[React Flow]: ${t} Help: https://reactflow.dev/error#${e}`)},Ci=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),_i=({x:e,y:t},[n,r,i],o=!1,a=[1,1])=>{const s={x:(e-n)/i,y:(t-r)/i};return o?Ci(s,a):s},Pi=({x:e,y:t},[n,r,i])=>({x:e*i+n,y:t*i+r});function Ii(e,t){if("number"==typeof e)return Math.floor(t-t/(1+e));if("string"==typeof e&&e.endsWith("px")){const t=parseFloat(e);if(!Number.isNaN(t))return Math.floor(t)}if("string"==typeof e&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}const Ai=(e,t,n,r,i,o)=>{const a=function(e,t,n){if("string"==typeof e||"number"==typeof e){const r=Ii(e,n),i=Ii(e,t);return{top:r,right:i,bottom:r,left:i,x:2*i,y:2*r}}if("object"==typeof e){const r=Ii(e.top??e.y??0,n),i=Ii(e.bottom??e.y??0,n),o=Ii(e.left??e.x??0,t),a=Ii(e.right??e.x??0,t);return{top:r,right:a,bottom:i,left:o,x:o+a,y:r+i}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}(o,t,n),s=(t-a.x)/e.width,c=(n-a.y)/e.height,u=Math.min(s,c),l=fi(u,r,i),h=t/2-(e.x+e.width/2)*l,f=n/2-(e.y+e.height/2)*l,d=function(e,t,n,r,i,o){const{x:a,y:s}=Pi(e,[t,n,r]),{x:c,y:u}=Pi({x:e.x+e.width,y:e.y+e.height},[t,n,r]),l=i-c,h=o-u;return{left:Math.floor(a),top:Math.floor(s),right:Math.floor(l),bottom:Math.floor(h)}}(e,h,f,l,t,n),g=Math.min(d.left-a.left,0),p=Math.min(d.top-a.top,0);return{x:h-g+Math.min(d.right-a.right,0),y:f-p+Math.min(d.bottom-a.bottom,0),zoom:l}},Oi=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function ji(e){return void 0!==e&&"parent"!==e}function $i(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function Ri(e){return void 0!==(e.measured?.width??e.width??e.initialWidth)&&void 0!==(e.measured?.height??e.height??e.initialHeight)}function Ni(e,t={width:0,height:0},n,r,i){const o={...e},a=r.get(n);if(a){const e=a.origin||i;o.x+=a.internals.positionAbsolute.x-(t.width??0)*e[0],o.y+=a.internals.positionAbsolute.y-(t.height??0)*e[1]}return o}function Li(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function Di(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:i}){const{x:o,y:a}=Hi(e),s=_i({x:o-(i?.left??0),y:a-(i?.top??0)},r),{x:c,y:u}=n?Ci(s,t):s;return{xSnapped:c,ySnapped:u,...s}}const Fi=e=>({width:e.offsetWidth,height:e.offsetHeight}),Bi=e=>e?.getRootNode?.()||window?.document,zi=["INPUT","SELECT","TEXTAREA"];function Ui(e){const t=e.composedPath?.()?.[0]||e.target;return 1===t?.nodeType&&(zi.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey"))}const qi=e=>"clientX"in e,Hi=(e,t)=>{const n=qi(e),r=n?e.clientX:e.touches?.[0].clientX,i=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:i-(t?.top??0)}},Ji=(e,t,n,r,i)=>{const o=t.querySelectorAll(`.${e}`);return o&&o.length?Array.from(o).map((t=>{const o=t.getBoundingClientRect();return{id:t.getAttribute("data-handleid"),type:e,nodeId:i,position:t.getAttribute("data-handlepos"),x:(o.left-n.left)/r,y:(o.top-n.top)/r,...Fi(t)}})):null};function Gi({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:i,sourceControlY:o,targetControlX:a,targetControlY:s}){const c=.125*e+.375*i+.375*a+.125*n,u=.125*t+.375*o+.375*s+.125*r;return[c,u,Math.abs(c-e),Math.abs(u-t)]}function Vi(e,t){return e>=0?.5*e:25*t*Math.sqrt(-e)}function Ki({pos:e,x1:t,y1:n,x2:r,y2:i,c:o}){switch(e){case ti.Left:return[t-Vi(t-r,o),n];case ti.Right:return[t+Vi(r-t,o),n];case ti.Top:return[t,n-Vi(n-i,o)];case ti.Bottom:return[t,n+Vi(i-n,o)]}}function Wi({sourceX:e,sourceY:t,sourcePosition:n=ti.Bottom,targetX:r,targetY:i,targetPosition:o=ti.Top,curvature:a=.25}){const[s,c]=Ki({pos:n,x1:e,y1:t,x2:r,y2:i,c:a}),[u,l]=Ki({pos:o,x1:r,y1:i,x2:e,y2:t,c:a}),[h,f,d,g]=Gi({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:s,sourceControlY:c,targetControlX:u,targetControlY:l});return[`M${e},${t} C${s},${c} ${u},${l} ${r},${i}`,h,f,d,g]}function Xi({sourceX:e,sourceY:t,targetX:n,targetY:r}){const i=Math.abs(n-e)/2,o=n<e?n+i:n-i,a=Math.abs(r-t)/2;return[o,r<t?r+a:r-a,i,a]}function Yi({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:i=!1}){if(!i)return r;const o=n||t.selected||e.selected,a=Math.max(e.internals.z||0,t.internals.z||0,1e3);return r+(o?a:0)}function Qi({sourceNode:e,targetNode:t,width:n,height:r,transform:i}){const o=mi(Si(e),Si(t));o.x===o.x2&&(o.x2+=1),o.y===o.y2&&(o.y2+=1);const a={x:-i[0]/i[2],y:-i[1]/i[2],width:n/i[2],height:r/i[2]};return Ei(a,vi(o))>0}const Zi=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`;function eo({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[i,o,a,s]=Xi({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,i,o,a,s]}const to={[ti.Left]:{x:-1,y:0},[ti.Right]:{x:1,y:0},[ti.Top]:{x:0,y:-1},[ti.Bottom]:{x:0,y:1}},no=({source:e,sourcePosition:t=ti.Bottom,target:n})=>t===ti.Left||t===ti.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},ro=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function io({sourceX:e,sourceY:t,sourcePosition:n=ti.Bottom,targetX:r,targetY:i,targetPosition:o=ti.Top,borderRadius:a=5,centerX:s,centerY:c,offset:u=20}){const[l,h,f,d,g]=function({source:e,sourcePosition:t=ti.Bottom,target:n,targetPosition:r=ti.Top,center:i,offset:o}){const a=to[t],s=to[r],c={x:e.x+a.x*o,y:e.y+a.y*o},u={x:n.x+s.x*o,y:n.y+s.y*o},l=no({source:c,sourcePosition:t,target:u}),h=0!==l.x?"x":"y",f=l[h];let d,g,p=[];const b={x:0,y:0},m={x:0,y:0},[w,v,y,S]=Xi({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(a[h]*s[h]==-1){d=i.x??w,g=i.y??v;const e=[{x:d,y:c.y},{x:d,y:u.y}],t=[{x:c.x,y:g},{x:u.x,y:g}];p=a[h]===f?"x"===h?e:t:"x"===h?t:e}else{const i=[{x:c.x,y:u.y}],l=[{x:u.x,y:c.y}];if(p="x"===h?a.x===f?l:i:a.y===f?i:l,t===r){const t=Math.abs(e[h]-n[h]);if(t<=o){const r=Math.min(o-1,o-t);a[h]===f?b[h]=(c[h]>e[h]?-1:1)*r:m[h]=(u[h]>n[h]?-1:1)*r}}if(t!==r){const e="x"===h?"y":"x",t=a[h]===s[e],n=c[e]>u[e],r=c[e]<u[e];(1===a[h]&&(!t&&n||t&&r)||1!==a[h]&&(!t&&r||t&&n))&&(p="x"===h?i:l)}const w={x:c.x+b.x,y:c.y+b.y},v={x:u.x+m.x,y:u.y+m.y};Math.max(Math.abs(w.x-p[0].x),Math.abs(v.x-p[0].x))>=Math.max(Math.abs(w.y-p[0].y),Math.abs(v.y-p[0].y))?(d=(w.x+v.x)/2,g=p[0].y):(d=p[0].x,g=(w.y+v.y)/2)}return[[e,{x:c.x+b.x,y:c.y+b.y},...p,{x:u.x+m.x,y:u.y+m.y},n],d,g,y,S]}({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:i},targetPosition:o,center:{x:s,y:c},offset:u});return[l.reduce(((e,t,n)=>{let r="";return r=n>0&&n<l.length-1?function(e,t,n,r){const i=Math.min(ro(e,t)/2,ro(t,n)/2,r),{x:o,y:a}=t;if(e.x===o&&o===n.x||e.y===a&&a===n.y)return`L${o} ${a}`;if(e.y===a)return`L ${o+i*(e.x<n.x?-1:1)},${a}Q ${o},${a} ${o},${a+i*(e.y<n.y?1:-1)}`;const s=e.x<n.x?1:-1;return`L ${o},${a+i*(e.y<n.y?-1:1)}Q ${o},${a} ${o+i*s},${a}`}(l[n-1],t,l[n+1],a):`${0===n?"M":"L"}${t.x} ${t.y}`,e+r}),""),h,f,d,g]}function oo(e){return e&&!(!e.internals.handleBounds&&!e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function ao(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,"source"===r.type?t.push(r):"target"===r.type&&n.push(r);return{source:t,target:n}}function so(e,t,n=ti.Left,r=!1){const i=(t?.x??0)+e.internals.positionAbsolute.x,o=(t?.y??0)+e.internals.positionAbsolute.y,{width:a,height:s}=t??$i(e);if(r)return{x:i+a/2,y:o+s/2};switch(t?.position??n){case ti.Top:return{x:i+a/2,y:o};case ti.Right:return{x:i+a,y:o+s/2};case ti.Bottom:return{x:i+a/2,y:o+s};case ti.Left:return{x:i,y:o+s/2}}}function co(e,t){return e&&(t?e.find((e=>e.id===t)):e[0])||null}function uo(e,t){return e?"string"==typeof e?e:`${t?`${t}__`:""}${Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&")}`:""}const lo={nodeOrigin:[0,0],nodeExtent:Gr,elevateNodesOnSelect:!0,defaults:{}},ho={...lo,checkEquality:!0};function fo(e,t){const n={...e};for(const e in t)void 0!==t[e]&&(n[e]=t[e]);return n}function go(e,t,n,r){const i=fo(ho,r);let o=!0;const a=new Map(t),s=i?.elevateNodesOnSelect?1e3:0;t.clear(),n.clear();for(const c of e){let e=a.get(c.id);if(i.checkEquality&&c===e?.internals.userNode)t.set(c.id,e);else{const n=ai(c,i.nodeOrigin),r=ji(c.extent)?c.extent:i.nodeExtent,o=di(n,r,$i(c));e={...i.defaults,...c,measured:{width:c.measured?.width,height:c.measured?.height},internals:{positionAbsolute:o,handleBounds:c.measured?e?.internals.handleBounds:void 0,z:bo(c,s),userNode:c}},t.set(c.id,e)}e.measured&&e.measured.width&&e.measured.height||e.hidden||(o=!1),c.parentId&&po(e,t,n,r)}return o}function po(e,t,n,r){const{elevateNodesOnSelect:i,nodeOrigin:o,nodeExtent:a}=fo(lo,r),s=e.parentId,c=t.get(s);if(!c)return void console.warn(`Parent node ${s} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);!function(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}(e,n);const u=i?1e3:0,{x:l,y:h,z:f}=function(e,t,n,r,i){const{x:o,y:a}=t.internals.positionAbsolute,s=$i(e),c=ai(e,n),u=ji(e.extent)?di(c,e.extent,s):c;let l=di({x:o+u.x,y:a+u.y},r,s);"parent"===e.extent&&(l=gi(l,s,t));const h=bo(e,i),f=t.internals.z??0;return{x:l.x,y:l.y,z:f>h?f:h}}(e,c,o,a,u),{positionAbsolute:d}=e.internals,g=l!==d.x||h!==d.y;(g||f!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:g?{x:l,y:h}:d,z:f}})}function bo(e,t){return(Mi(e.zIndex)?e.zIndex:0)+(e.selected?t:0)}function mo(e,t,n,r=[0,0]){const i=[],o=new Map;for(const n of e){const e=t.get(n.parentId);if(!e)continue;const r=o.get(n.parentId)?.expandedRect??yi(e),i=ki(r,n.rect);o.set(n.parentId,{expandedRect:i,parent:e})}return o.size>0&&o.forEach((({expandedRect:t,parent:o},a)=>{const s=o.internals.positionAbsolute,c=$i(o),u=o.origin??r,l=t.x<s.x?Math.round(Math.abs(s.x-t.x)):0,h=t.y<s.y?Math.round(Math.abs(s.y-t.y)):0,f=Math.max(c.width,Math.round(t.width)),d=Math.max(c.height,Math.round(t.height)),g=(f-c.width)*u[0],p=(d-c.height)*u[1];(l>0||h>0||g||p)&&(i.push({id:a,type:"position",position:{x:o.position.x-l+g,y:o.position.y-h+p}}),n.get(a)?.forEach((t=>{e.some((e=>e.id===t.id))||i.push({id:t.id,type:"position",position:{x:t.position.x+l,y:t.position.y+h}})}))),(c.width<t.width||c.height<t.height||l||h)&&i.push({id:a,type:"dimensions",setAttributes:!0,dimensions:{width:f+(l?u[0]*l-g:0),height:d+(h?u[1]*h-p:0)}})})),i}function wo(e,t,n,r,i,o){let a=i;const s=r.get(a)||new Map;r.set(a,s.set(n,t)),a=`${i}-${e}`;const c=r.get(a)||new Map;if(r.set(a,c.set(n,t)),o){a=`${i}-${e}-${o}`;const s=r.get(a)||new Map;r.set(a,s.set(n,t))}}function vo(e,t,n){e.clear(),t.clear();for(const r of n){const{source:n,target:i,sourceHandle:o=null,targetHandle:a=null}=r,s={edgeId:r.id,source:n,target:i,sourceHandle:o,targetHandle:a},c=`${n}-${o}--${i}-${a}`;wo("source",s,`${i}-${a}--${n}-${o}`,e,n,o),wo("target",s,c,e,i,a),t.set(r.id,r)}}function yo(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return!!n&&(!!n.selected||yo(n,t))}function So(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function ko({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const i=[];for(const[e,o]of t){const t=n.get(e)?.internals.userNode;t&&i.push({...t,position:o.position,dragging:r})}if(!e)return[i[0],i];const o=n.get(e)?.internals.userNode;return[o?{...o,position:t.get(e)?.position||o.position,dragging:r}:i[0],i]}function Eo(e,t,n,r,i,o=!1){const a=r.get(e);if(!a)return null;const s="strict"===i?a.internals.handleBounds?.[t]:[...a.internals.handleBounds?.source??[],...a.internals.handleBounds?.target??[]],c=(n?s?.find((e=>e.id===n)):s?.[0])??null;return c&&o?{...c,...so(a,c,c.position,!0)}:c}function xo(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}const Mo=()=>!0;function To(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:i,fromType:o,doc:a,lib:s,flowId:c,isValidConnection:u=Mo,nodeLookup:l}){const h="target"===o,f=t?a.querySelector(`.${s}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:d,y:g}=Hi(e),p=a.elementFromPoint(d,g),b=p?.classList.contains(`${s}-flow__handle`)?p:f,m={handleDomNode:b,isValid:!1,connection:null,toHandle:null};if(b){const e=xo(void 0,b),t=b.getAttribute("data-nodeid"),o=b.getAttribute("data-handleid"),a=b.classList.contains("connectable"),s=b.classList.contains("connectableend");if(!t||!e)return m;const c={source:h?t:r,sourceHandle:h?o:i,target:h?r:t,targetHandle:h?i:o};m.connection=c;const f=a&&s&&(n===Kr.Strict?h&&"source"===e||!h&&"target"===e:t!==r||o!==i);m.isValid=f&&u(c),m.toHandle=Eo(t,e,o,l,n,!1)}return m}const Co={onPointerDown:function(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:i,edgeUpdaterType:o,isTarget:a,domNode:s,nodeLookup:c,lib:u,autoPanOnConnect:l,flowId:h,panBy:f,cancelConnection:d,onConnectStart:g,onConnect:p,onConnectEnd:b,isValidConnection:m=Mo,onReconnectEnd:w,updateConnection:v,getTransform:y,getFromHandle:S,autoPanSpeed:k}){const E=Bi(e.target);let x,M=0;const{x:T,y:C}=Hi(e),_=E?.elementFromPoint(T,C),P=xo(o,_),I=s?.getBoundingClientRect();if(!I||!P)return;const A=Eo(i,P,r,c,t);if(!A)return;let O=Hi(e,I),j=!1,$=null,R=!1,N=null;function L(){if(!l||!I)return;const[e,t]=bi(O,I,k);f({x:e,y:t}),M=requestAnimationFrame(L)}const D={...A,nodeId:i,type:P,position:A.position},F=c.get(i),B={inProgress:!0,isValid:null,from:so(F,D,ti.Left,!0),fromHandle:D,fromPosition:D.position,fromNode:F,to:O,toHandle:null,toPosition:ni[D.position],toNode:null};v(B);let z=B;function U(e){if(!S()||!D)return void q(e);const o=y();O=Hi(e,I),x=function(e,t,n,r){let i=[],o=1/0;const a=function(e,t,n){const r=[],i={x:e.x-n,y:e.y-n,width:2*n,height:2*n};for(const e of t.values())Ei(i,yi(e))>0&&r.push(e);return r}(e,n,t+250);for(const n of a){const a=[...n.internals.handleBounds?.source??[],...n.internals.handleBounds?.target??[]];for(const s of a){if(r.nodeId===s.nodeId&&r.type===s.type&&r.id===s.id)continue;const{x:a,y:c}=so(n,s,s.position,!0),u=Math.sqrt(Math.pow(a-e.x,2)+Math.pow(c-e.y,2));u>t||(u<o?(i=[{...s,x:a,y:c}],o=u):u===o&&i.push({...s,x:a,y:c}))}}if(!i.length)return null;if(i.length>1){const e="source"===r.type?"target":"source";return i.find((t=>t.type===e))??i[0]}return i[0]}(_i(O,o,!1,[1,1]),n,c,D),j||(L(),j=!0);const s=To(e,{handle:x,connectionMode:t,fromNodeId:i,fromHandleId:r,fromType:a?"target":"source",isValidConnection:m,doc:E,lib:u,flowId:h,nodeLookup:c});N=s.handleDomNode,$=s.connection,R=function(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}(!!x,s.isValid);const l={...z,isValid:R,to:x&&R?Pi({x:x.x,y:x.y},o):O,toHandle:s.toHandle,toPosition:R&&s.toHandle?s.toHandle.position:ni[D.position],toNode:s.toHandle?c.get(s.toHandle.nodeId):null};R&&x&&z.toHandle&&l.toHandle&&z.toHandle.type===l.toHandle.type&&z.toHandle.nodeId===l.toHandle.nodeId&&z.toHandle.id===l.toHandle.id&&z.to.x===l.to.x&&z.to.y===l.to.y||(v(l),z=l)}function q(e){(x||N)&&$&&R&&p?.($);const{inProgress:t,...n}=z,r={...n,toPosition:z.toHandle?z.toPosition:null};b?.(e,r),o&&w?.(e,r),d(),cancelAnimationFrame(M),j=!1,R=!1,$=null,N=null,E.removeEventListener("mousemove",U),E.removeEventListener("mouseup",q),E.removeEventListener("touchmove",U),E.removeEventListener("touchend",q)}g?.(e,{nodeId:i,handleId:r,handleType:P}),E.addEventListener("mousemove",U),E.addEventListener("mouseup",q),E.addEventListener("touchmove",U),E.addEventListener("touchend",q)},isValid:To},_o=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,Po=e=>({x:e.x,y:e.y,zoom:e.k}),Io=({x:e,y:t,zoom:n})=>$r.translate(e,t).scale(n),Ao=(e,t)=>e.target.closest(`.${t}`),Oo=(e,t)=>2===t&&Array.isArray(e)&&e.includes(2),jo=(e,t=0,n=()=>{})=>{const r="number"==typeof t&&t>0;return r||n(),r?e.transition().duration(t).on("end",n):e},$o=e=>{const t=e.ctrlKey&&Oi()?10:1;return-e.deltaY*(1===e.deltaMode?.05:e.deltaMode?1:.002)*t};var Ro;function No(e,t){return Math.max(0,t-e)}function Lo(e,t){return Math.max(0,e-t)}function Do(e,t,n){return Math.max(0,t-e,e-n)}function Fo(e,t){return e?!t:t}!function(e){e.Line="line",e.Handle="handle"}(Ro||(Ro={}));const Bo={width:0,height:0,x:0,y:0},zo={...Bo,pointerX:0,pointerY:0,aspectRatio:1};function Uo(e,t,n){const r=t.position.x+e.position.x,i=t.position.y+e.position.y,o=e.measured.width??0,a=e.measured.height??0,s=n[0]*o,c=n[1]*a;return[[r-s,i-c],[r+o-s,i+a-c]]}var qo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof n.g<"u"?n.g:typeof self<"u"?self:{};function Ho(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Jo,Go,Vo,Ko,Wo={exports:{}},Xo={},Yo={exports:{}},Qo={},Zo={};function ea(){return Vo||(Vo=1,"production"===ee.env.NODE_ENV?Yo.exports=function(){if(Jo)return Qo;Jo=1;var e=c(),t="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},n=e.useState,r=e.useEffect,i=e.useLayoutEffect,o=e.useDebugValue;function a(e){var n=e.getSnapshot;e=e.value;try{var r=n();return!t(e,r)}catch{return!0}}var s=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?function(e,t){return t()}:function(e,t){var s=t(),c=n({inst:{value:s,getSnapshot:t}}),u=c[0].inst,l=c[1];return i((function(){u.value=s,u.getSnapshot=t,a(u)&&l({inst:u})}),[e,s,t]),r((function(){return a(u)&&l({inst:u}),e((function(){a(u)&&l({inst:u})}))}),[e]),o(s),s};return Qo.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:s,Qo}():Yo.exports=(Go||(Go=1,"production"!==ee.env.NODE_ENV&&function(){function e(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!n(e,r)}catch{return!0}}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var t=c(),n="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=t.useState,i=t.useEffect,o=t.useLayoutEffect,a=t.useDebugValue,s=!1,u=!1,l=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?function(e,t){return t()}:function(c,l){s||void 0===t.startTransition||(s=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var h=l();if(!u){var f=l();n(h,f)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),u=!0)}var d=(f=r({inst:{value:h,getSnapshot:l}}))[0].inst,g=f[1];return o((function(){d.value=h,d.getSnapshot=l,e(d)&&g({inst:d})}),[c,h,l]),i((function(){return e(d)&&g({inst:d}),c((function(){e(d)&&g({inst:d})}))}),[c]),a(h),h};Zo.useSyncExternalStore=void 0!==t.useSyncExternalStore?t.useSyncExternalStore:l,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),Zo)),Yo.exports}var ta,na,ra={},ia=(na||(na=1,"production"===ee.env.NODE_ENV?Wo.exports=function(){if(Ko)return Xo;Ko=1;var e=c(),t=ea(),n="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=t.useSyncExternalStore,i=e.useRef,o=e.useEffect,a=e.useMemo,s=e.useDebugValue;return Xo.useSyncExternalStoreWithSelector=function(e,t,c,u,l){var h=i(null);if(null===h.current){var f={hasValue:!1,value:null};h.current=f}else f=h.current;h=a((function(){function e(e){if(!o){if(o=!0,r=e,e=u(e),void 0!==l&&f.hasValue){var t=f.value;if(l(t,e))return i=t}return i=e}if(t=i,n(r,e))return t;var a=u(e);return void 0!==l&&l(t,a)?(r=e,t):(r=e,i=a)}var r,i,o=!1,a=void 0===c?null:c;return[function(){return e(t())},null===a?void 0:function(){return e(a())}]}),[t,c,u,l]);var d=r(e,h[0],h[1]);return o((function(){f.hasValue=!0,f.value=d}),[d]),s(d),d},Xo}():Wo.exports=(ta||(ta=1,"production"!==ee.env.NODE_ENV&&function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var e=c(),t=ea(),n="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=t.useSyncExternalStore,i=e.useRef,o=e.useEffect,a=e.useMemo,s=e.useDebugValue;ra.useSyncExternalStoreWithSelector=function(e,t,c,u,l){var h=i(null);if(null===h.current){var f={hasValue:!1,value:null};h.current=f}else f=h.current;h=a((function(){function e(e){if(!o){if(o=!0,r=e,e=u(e),void 0!==l&&f.hasValue){var t=f.value;if(l(t,e))return i=t}return i=e}if(t=i,n(r,e))return t;var a=u(e);return void 0!==l&&l(t,a)?(r=e,t):(r=e,i=a)}var r,i,o=!1,a=void 0===c?null:c;return[function(){return e(t())},null===a?void 0:function(){return e(a())}]}),[t,c,u,l]);var d=r(e,h[0],h[1]);return o((function(){f.hasValue=!0,f.value=d}),[d]),s(d),d},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),ra)),Wo.exports);const oa=Ho(ia),aa={},sa=e=>{let t;const n=new Set,r=(e,r)=>{const i="function"==typeof e?e(t):e;if(!Object.is(i,t)){const e=t;t=r??("object"!=typeof i||null===i)?i:Object.assign({},t,i),n.forEach((n=>n(t,e)))}},i=()=>t,o={setState:r,getState:i,getInitialState:()=>a,subscribe:e=>(n.add(e),()=>n.delete(e)),destroy:()=>{"production"!==(aa?"production":void 0)&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},a=t=e(r,i,o);return o},{useDebugValue:ca}=c(),{useSyncExternalStoreWithSelector:ua}=oa,la=e=>e;function ha(e,t=la,n){const r=ua(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return ca(r),r}const fa=(e,t)=>{const n=(e=>e?sa(e):sa)(e),r=(e,r=t)=>ha(n,e,r);return Object.assign(r,n),r};function da(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[n,r]of e)if(!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}const ga=(0,s.createContext)(null),pa=ga.Provider,ba=Jr.error001();function ma(e,t){const n=(0,s.useContext)(ga);if(null===n)throw new Error(ba);return ha(n,e,t)}function wa(){const e=(0,s.useContext)(ga);if(null===e)throw new Error(ba);return(0,s.useMemo)((()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe})),[e])}const va={display:"none"},ya={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},Sa="react-flow__node-desc",ka="react-flow__edge-desc",Ea="react-flow__aria-live",xa=e=>e.ariaLiveMessage;function Ma({rfId:e}){const t=ma(xa);return(0,r.jsx)("div",{id:`${Ea}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:ya,children:t})}function Ta({rfId:e,disableKeyboardA11y:t}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{id:`${Sa}-${e}`,style:va,children:["Press enter or space to select a node.",!t&&"You can then use the arrow keys to move the node around."," Press delete to remove it and escape to cancel."," "]}),(0,r.jsx)("div",{id:`${ka}-${e}`,style:va,children:"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."}),!t&&(0,r.jsx)(Ma,{rfId:e})]})}const Ca=e=>e.userSelectionActive?"none":"all",_a=(0,s.forwardRef)((({position:e="top-left",children:t,className:n,style:i,...o},a)=>{const s=ma(Ca),c=`${e}`.split("-");return(0,r.jsx)("div",{className:te(["react-flow__panel",n,...c]),style:{...i,pointerEvents:s},ref:a,...o,children:t})}));function Pa({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:(0,r.jsx)(_a,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:(0,r.jsx)("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}_a.displayName="Panel";const Ia=e=>{const t=[],n=[];for(const[,n]of e.nodeLookup)n.selected&&t.push(n.internals.userNode);for(const[,t]of e.edgeLookup)t.selected&&n.push(t);return{selectedNodes:t,selectedEdges:n}},Aa=e=>e.id;function Oa(e,t){return da(e.selectedNodes.map(Aa),t.selectedNodes.map(Aa))&&da(e.selectedEdges.map(Aa),t.selectedEdges.map(Aa))}function ja({onSelectionChange:e}){const t=wa(),{selectedNodes:n,selectedEdges:r}=ma(Ia,Oa);return(0,s.useEffect)((()=>{const i={nodes:n,edges:r};e?.(i),t.getState().onSelectionChangeHandlers.forEach((e=>e(i)))}),[n,r,e]),null}const $a=e=>!!e.onSelectionChangeHandlers;function Ra({onSelectionChange:e}){const t=ma($a);return e||t?(0,r.jsx)(ja,{onSelectionChange:e}):null}const Na=[0,0],La={x:0,y:0,zoom:1},Da=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","onBeforeDelete","debug","autoPanSpeed","paneClickDistance","rfId"],Fa=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges,setPaneClickDistance:e.setPaneClickDistance}),Ba={translateExtent:Gr,nodeOrigin:Na,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1",paneClickDistance:0};function za(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:i,setTranslateExtent:o,setNodeExtent:a,reset:c,setDefaultNodesAndEdges:u,setPaneClickDistance:l}=ma(Fa,da),h=wa();(0,s.useEffect)((()=>(u(e.defaultNodes,e.defaultEdges),()=>{f.current=Ba,c()})),[]);const f=(0,s.useRef)(Ba);return(0,s.useEffect)((()=>{for(const s of Da){const c=e[s];c!==f.current[s]&&(typeof e[s]>"u"||("nodes"===s?t(c):"edges"===s?n(c):"minZoom"===s?r(c):"maxZoom"===s?i(c):"translateExtent"===s?o(c):"nodeExtent"===s?a(c):"paneClickDistance"===s?l(c):"fitView"===s?h.setState({fitViewQueued:c}):"fitViewOptions"===s?h.setState({fitViewOptions:c}):h.setState({[s]:c})))}f.current=e}),Da.map((t=>e[t]))),null}function Ua(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}const qa=typeof document<"u"?document:null;function Ha(e=null,t={target:qa,actInsideInputWithModifier:!0}){const[n,r]=(0,s.useState)(!1),i=(0,s.useRef)(!1),o=(0,s.useRef)(new Set([])),[a,c]=(0,s.useMemo)((()=>{if(null!==e){const t=(Array.isArray(e)?e:[e]).filter((e=>"string"==typeof e)).map((e=>e.replace("+","\n").replace("\n\n","\n+").split("\n"))),n=t.reduce(((e,t)=>e.concat(...t)),[]);return[t,n]}return[[],[]]}),[e]);return(0,s.useEffect)((()=>{const n=t?.target||qa;if(null!==e){const e=e=>{if(i.current=e.ctrlKey||e.metaKey||e.shiftKey||e.altKey,(!i.current||i.current&&!t.actInsideInputWithModifier)&&Ui(e))return!1;const n=Ga(e.code,c);if(o.current.add(e[n]),Ja(a,o.current,!1)){const n=e.composedPath?.()?.[0]||e.target,o="BUTTON"===n?.nodeName||"A"===n?.nodeName;!1!==t.preventDefault&&(i.current||!o)&&e.preventDefault(),r(!0)}},s=e=>{const t=Ga(e.code,c);Ja(a,o.current,!0)?(r(!1),o.current.clear()):o.current.delete(e[t]),"Meta"===e.key&&o.current.clear(),i.current=!1},u=()=>{o.current.clear(),r(!1)};return n?.addEventListener("keydown",e),n?.addEventListener("keyup",s),window.addEventListener("blur",u),window.addEventListener("contextmenu",u),()=>{n?.removeEventListener("keydown",e),n?.removeEventListener("keyup",s),window.removeEventListener("blur",u),window.removeEventListener("contextmenu",u)}}}),[e,r]),n}function Ja(e,t,n){return e.filter((e=>n||e.length===t.size)).some((e=>e.every((e=>t.has(e)))))}function Ga(e,t){return t.includes(e)?"code":"key"}const Va=()=>{const e=wa();return(0,s.useMemo)((()=>({zoomIn:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1.2,{duration:t?.duration}):Promise.resolve(!1)},zoomOut:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,{duration:t?.duration}):Promise.resolve(!1)},zoomTo:(t,n)=>{const{panZoom:r}=e.getState();return r?r.scaleTo(t,{duration:n?.duration}):Promise.resolve(!1)},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{const{transform:[r,i,o],panZoom:a}=e.getState();return a?(await a.setViewport({x:t.x??r,y:t.y??i,zoom:t.zoom??o},{duration:n?.duration}),Promise.resolve(!0)):Promise.resolve(!1)},getViewport:()=>{const[t,n,r]=e.getState().transform;return{x:t,y:n,zoom:r}},setCenter:async(t,n,r)=>{const{width:i,height:o,maxZoom:a,panZoom:s}=e.getState(),c=typeof r?.zoom<"u"?r.zoom:a,u=i/2-t*c,l=o/2-n*c;return s?(await s.setViewport({x:u,y:l,zoom:c},{duration:r?.duration}),Promise.resolve(!0)):Promise.resolve(!1)},fitBounds:async(t,n)=>{const{width:r,height:i,minZoom:o,maxZoom:a,panZoom:s}=e.getState(),c=Ai(t,r,i,o,a,n?.padding??.1);return s?(await s.setViewport(c,{duration:n?.duration}),Promise.resolve(!0)):Promise.resolve(!1)},screenToFlowPosition:(t,n={})=>{const{transform:r,snapGrid:i,snapToGrid:o,domNode:a}=e.getState();if(!a)return t;const{x:s,y:c}=a.getBoundingClientRect(),u={x:t.x-s,y:t.y-c},l=n.snapGrid??i,h=n.snapToGrid??o;return _i(u,r,h,l)},flowToScreenPosition:t=>{const{transform:n,domNode:r}=e.getState();if(!r)return t;const{x:i,y:o}=r.getBoundingClientRect(),a=Pi(t,n);return{x:a.x+i,y:a.y+o}}})),[])};function Ka(e,t){const n=[],r=new Map,i=[];for(const t of e)if("add"!==t.type)if("remove"===t.type||"replace"===t.type)r.set(t.id,[t]);else{const e=r.get(t.id);e?e.push(t):r.set(t.id,[t])}else i.push(t);for(const e of t){const t=r.get(e.id);if(!t){n.push(e);continue}if("remove"===t[0].type)continue;if("replace"===t[0].type){n.push({...t[0].item});continue}const i={...e};for(const e of t)Wa(e,i);n.push(i)}return i.length&&i.forEach((e=>{void 0!==e.index?n.splice(e.index,0,{...e.item}):n.push({...e.item})})),n}function Wa(e,t){switch(e.type){case"select":t.selected=e.selected;break;case"position":typeof e.position<"u"&&(t.position=e.position),typeof e.dragging<"u"&&(t.dragging=e.dragging);break;case"dimensions":typeof e.dimensions<"u"&&(t.measured??={},t.measured.width=e.dimensions.width,t.measured.height=e.dimensions.height,e.setAttributes&&(t.width=e.dimensions.width,t.height=e.dimensions.height)),"boolean"==typeof e.resizing&&(t.resizing=e.resizing)}}function Xa(e,t){return Ka(e,t)}function Ya(e,t){return Ka(e,t)}function Qa(e,t){return{id:e,type:"select",selected:t}}function Za(e,t=new Set,n=!1){const r=[];for(const[i,o]of e){const e=t.has(i);(void 0!==o.selected||e)&&o.selected!==e&&(n&&(o.selected=e),r.push(Qa(o.id,e)))}return r}function es({items:e=[],lookup:t}){const n=[],r=new Map(e.map((e=>[e.id,e])));for(const[r,i]of e.entries()){const e=t.get(i.id),o=e?.internals?.userNode??e;void 0!==o&&o!==i&&n.push({id:i.id,item:i,type:"replace"}),void 0===o&&n.push({item:i,type:"add",index:r})}for(const[e]of t)void 0===r.get(e)&&n.push({id:e,type:"remove"});return n}function ts(e){return{id:e.id,type:"remove"}}const ns=e=>(e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e))(e),rs=e=>ii(e);function is(e){return(0,s.forwardRef)(e)}const os=typeof window<"u"?s.useLayoutEffect:s.useEffect;function as(e){const[t,n]=(0,s.useState)(BigInt(0)),[r]=(0,s.useState)((()=>function(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}((()=>n((e=>e+BigInt(1)))))));return os((()=>{const t=r.get();t.length&&(e(t),r.reset())}),[t]),r}const ss=(0,s.createContext)(null);function cs({children:e}){const t=wa(),n=as((0,s.useCallback)((e=>{const{nodes:n=[],setNodes:r,hasDefaultNodes:i,onNodesChange:o,nodeLookup:a}=t.getState();let s=n;for(const t of e)s="function"==typeof t?t(s):t;i?r(s):o&&o(es({items:s,lookup:a}))}),[])),i=as((0,s.useCallback)((e=>{const{edges:n=[],setEdges:r,hasDefaultEdges:i,onEdgesChange:o,edgeLookup:a}=t.getState();let s=n;for(const t of e)s="function"==typeof t?t(s):t;i?r(s):o&&o(es({items:s,lookup:a}))}),[])),o=(0,s.useMemo)((()=>({nodeQueue:n,edgeQueue:i})),[]);return(0,r.jsx)(ss.Provider,{value:o,children:e})}const us=e=>!!e.panZoom;function ls(){const e=Va(),t=wa(),n=function(){const e=(0,s.useContext)(ss);if(!e)throw new Error("useBatchContext must be used within a BatchProvider");return e}(),r=ma(us),i=(0,s.useMemo)((()=>{const e=e=>t.getState().nodeLookup.get(e),r=e=>{n.nodeQueue.push(e)},i=e=>{n.edgeQueue.push(e)},o=e=>{const{nodeLookup:n,nodeOrigin:r}=t.getState(),i=ns(e)?e:n.get(e.id),o=i.parentId?Ni(i.position,i.measured,i.parentId,n,r):i.position,a={...i,position:o,width:i.measured?.width??i.width,height:i.measured?.height??i.height};return yi(a)},a=(e,t,n={replace:!1})=>{r((r=>r.map((r=>{if(r.id===e){const e="function"==typeof t?t(r):t;return n.replace&&ns(e)?e:{...r,...e}}return r}))))},s=(e,t,n={replace:!1})=>{i((r=>r.map((r=>{if(r.id===e){const e="function"==typeof t?t(r):t;return n.replace&&rs(e)?e:{...r,...e}}return r}))))};return{getNodes:()=>t.getState().nodes.map((e=>({...e}))),getNode:t=>e(t)?.internals.userNode,getInternalNode:e,getEdges:()=>{const{edges:e=[]}=t.getState();return e.map((e=>({...e})))},getEdge:e=>t.getState().edgeLookup.get(e),setNodes:r,setEdges:i,addNodes:e=>{const t=Array.isArray(e)?e:[e];n.nodeQueue.push((e=>[...e,...t]))},addEdges:e=>{const t=Array.isArray(e)?e:[e];n.edgeQueue.push((e=>[...e,...t]))},toObject:()=>{const{nodes:e=[],edges:n=[],transform:r}=t.getState(),[i,o,a]=r;return{nodes:e.map((e=>({...e}))),edges:n.map((e=>({...e}))),viewport:{x:i,y:o,zoom:a}}},deleteElements:async({nodes:e=[],edges:n=[]})=>{const{nodes:r,edges:i,onNodesDelete:o,onEdgesDelete:a,triggerNodeChanges:s,triggerEdgeChanges:c,onDelete:u,onBeforeDelete:l}=t.getState(),{nodes:h,edges:f}=await async function({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:i}){const o=new Set(e.map((e=>e.id))),a=[];for(const e of n){if(!1===e.deletable)continue;const t=o.has(e.id),n=!t&&e.parentId&&a.find((t=>t.id===e.parentId));(t||n)&&a.push(e)}const s=new Set(t.map((e=>e.id))),c=r.filter((e=>!1!==e.deletable)),u=li(a,c);for(const e of c)s.has(e.id)&&!u.find((t=>t.id===e.id))&&u.push(e);if(!i)return{edges:u,nodes:a};const l=await i({nodes:a,edges:u});return"boolean"==typeof l?l?{edges:u,nodes:a}:{edges:[],nodes:[]}:l}({nodesToRemove:e,edgesToRemove:n,nodes:r,edges:i,onBeforeDelete:l}),d=f.length>0,g=h.length>0;if(d){const e=f.map(ts);a?.(f),c(e)}if(g){const e=h.map(ts);o?.(h),s(e)}return(g||d)&&u?.({nodes:h,edges:f}),{deletedNodes:h,deletedEdges:f}},getIntersectingNodes:(e,n=!0,r)=>{const i=xi(e),a=i?e:o(e),s=void 0!==r;return a?(r||t.getState().nodes).filter((r=>{const o=t.getState().nodeLookup.get(r.id);if(o&&!i&&(r.id===e.id||!o.internals.positionAbsolute))return!1;const c=yi(s?r:o),u=Ei(c,a);return n&&u>0||u>=a.width*a.height})):[]},isNodeIntersecting:(e,t,n=!0)=>{const r=xi(e)?e:o(e);if(!r)return!1;const i=Ei(r,t);return n&&i>0||i>=r.width*r.height},updateNode:a,updateNodeData:(e,t,n={replace:!1})=>{a(e,(e=>{const r="function"==typeof t?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}}),n)},updateEdge:s,updateEdgeData:(e,t,n={replace:!1})=>{s(e,(e=>{const r="function"==typeof t?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}}),n)},getNodesBounds:e=>{const{nodeLookup:n,nodeOrigin:r}=t.getState();return si(e,{nodeLookup:n,nodeOrigin:r})},getHandleConnections:({type:e,id:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}-${e}${n?`-${n}`:""}`)?.values()??[]),getNodeConnections:({type:e,handleId:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}${e?n?`-${e}-${n}`:`-${e}`:""}`)?.values()??[]),fitView:async e=>{const r=t.getState().fitViewResolver??Promise.withResolvers();return t.setState({fitViewQueued:!0,fitViewOptions:e,fitViewResolver:r}),n.nodeQueue.push((e=>[...e])),r.promise}}}),[]);return(0,s.useMemo)((()=>({...i,...e,viewportInitialized:r})),[r])}const hs=e=>e.selected,fs={actInsideInputWithModifier:!1},ds=typeof window<"u"?window:void 0,gs={position:"absolute",width:"100%",height:"100%",top:0,left:0},ps=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib});function bs({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:i=!1,panOnScrollSpeed:o=.5,panOnScrollMode:a=Xr.Free,zoomOnDoubleClick:c=!0,panOnDrag:u=!0,defaultViewport:l,translateExtent:h,minZoom:f,maxZoom:d,zoomActivationKeyCode:g,preventScrolling:p=!0,children:b,noWheelClassName:m,noPanClassName:w,onViewportChange:v,isControlledViewport:y,paneClickDistance:S}){const k=wa(),E=(0,s.useRef)(null),{userSelectionActive:x,lib:M}=ma(ps,da),T=Ha(g),C=(0,s.useRef)();!function(e){const t=wa();(0,s.useEffect)((()=>{const n=()=>{if(!e.current)return!1;const n=Fi(e.current);(0===n.height||0===n.width)&&t.getState().onError?.("004",Jr.error004()),t.setState({width:n.width||500,height:n.height||500})};if(e.current){n(),window.addEventListener("resize",n);const t=new ResizeObserver((()=>n()));return t.observe(e.current),()=>{window.removeEventListener("resize",n),t&&e.current&&t.unobserve(e.current)}}}),[])}(E);const _=(0,s.useCallback)((e=>{v?.({x:e[0],y:e[1],zoom:e[2]}),y||k.setState({transform:e})}),[v,y]);return(0,s.useEffect)((()=>{if(E.current){C.current=function({domNode:e,minZoom:t,maxZoom:n,paneClickDistance:r,translateExtent:i,viewport:o,onPanZoom:a,onPanZoomStart:s,onPanZoomEnd:c,onDraggingChange:u}){const l={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{x:0,y:0,zoom:0},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},h=e.getBoundingClientRect(),f=Hr().clickDistance(!Mi(r)||r<0?0:r).scaleExtent([t,n]).translateExtent(i),d=wt(e).call(f);w({x:o.x,y:o.y,zoom:fi(o.zoom,t,n)},[[0,0],[h.width,h.height]],i);const g=d.on("wheel.zoom"),p=d.on("dblclick.zoom");function b(e,t){return d?new Promise((n=>{f?.transform(jo(d,t?.duration,(()=>n(!0))),e)})):Promise.resolve(!1)}function m(){f.on("zoom",null)}async function w(e,t,n){const r=Io(e),i=f?.constrain()(r,t,n);return i&&await b(i),new Promise((e=>e(i)))}return f.wheelDelta($o),{update:function({noWheelClassName:e,noPanClassName:t,onPaneContextMenu:n,userSelectionActive:r,panOnScroll:i,panOnDrag:o,panOnScrollMode:h,panOnScrollSpeed:b,preventScrolling:w,zoomOnPinch:v,zoomOnScroll:y,zoomOnDoubleClick:S,zoomActivationKeyPressed:k,lib:E,onTransformChange:x}){r&&!l.isZoomingOrPanning&&m();const M=!i||k||r?function({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,i){if(!t&&"wheel"===r.type&&!r.ctrlKey||Ao(r,e))return null;r.preventDefault(),n.call(this,r,i)}}({noWheelClassName:e,preventScrolling:w,d3ZoomHandler:g}):function({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:i,panOnScrollSpeed:o,zoomOnPinch:a,onPanZoomStart:s,onPanZoom:c,onPanZoomEnd:u}){return l=>{if(Ao(l,t))return!1;l.preventDefault(),l.stopImmediatePropagation();const h=n.property("__zoom").k||1;if(l.ctrlKey&&a){const e=vt(l),t=$o(l),i=h*Math.pow(2,t);return void r.scaleTo(n,i,e,l)}const f=1===l.deltaMode?20:1;let d=i===Xr.Vertical?0:l.deltaX*f,g=i===Xr.Horizontal?0:l.deltaY*f;!Oi()&&l.shiftKey&&i!==Xr.Vertical&&(d=l.deltaY*f,g=0),r.translateBy(n,-d/h*o,-g/h*o,{internal:!0});const p=Po(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling||(e.isPanScrolling=!0,s?.(l,p)),e.isPanScrolling&&(c?.(l,p),e.panScrollTimeout=setTimeout((()=>{u?.(l,p),e.isPanScrolling=!1}),150))}}({zoomPanValues:l,noWheelClassName:e,d3Selection:d,d3Zoom:f,panOnScrollMode:h,panOnScrollSpeed:b,zoomOnPinch:v,onPanZoomStart:s,onPanZoom:a,onPanZoomEnd:c});if(d.on("wheel.zoom",M,{passive:!1}),!r){const e=function({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const i=Po(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=i,"mousedown"===r.sourceEvent?.type&&t(!0),n&&n?.(r.sourceEvent,i)}}({zoomPanValues:l,onDraggingChange:u,onPanZoomStart:s});f.on("start",e);const t=function({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:i}){return o=>{e.usedRightMouseButton=!(!n||!Oo(t,e.mouseButton??0)),o.sourceEvent?.sync||r([o.transform.x,o.transform.y,o.transform.k]),i&&!o.sourceEvent?.internal&&i?.(o.sourceEvent,Po(o.transform))}}({zoomPanValues:l,panOnDrag:o,onPaneContextMenu:!!n,onPanZoom:a,onTransformChange:x});f.on("zoom",t);const r=function({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:i,onPaneContextMenu:o}){return a=>{if(!a.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,o&&Oo(t,e.mouseButton??0)&&!e.usedRightMouseButton&&a.sourceEvent&&o(a.sourceEvent),e.usedRightMouseButton=!1,r(!1),i&&_o(e.prevViewport,a.transform))){const t=Po(a.transform);e.prevViewport=t,clearTimeout(e.timerId),e.timerId=setTimeout((()=>{i?.(a.sourceEvent,t)}),n?150:0)}}}({zoomPanValues:l,panOnDrag:o,panOnScroll:i,onPaneContextMenu:n,onPanZoomEnd:c,onDraggingChange:u});f.on("end",r)}const T=function({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:i,zoomOnDoubleClick:o,userSelectionActive:a,noWheelClassName:s,noPanClassName:c,lib:u}){return l=>{const h=e||t,f=n&&l.ctrlKey;if(1===l.button&&"mousedown"===l.type&&(Ao(l,`${u}-flow__node`)||Ao(l,`${u}-flow__edge`)))return!0;if(!r&&!h&&!i&&!o&&!n||a||Ao(l,s)&&"wheel"===l.type||Ao(l,c)&&("wheel"!==l.type||i&&"wheel"===l.type&&!e)||!n&&l.ctrlKey&&"wheel"===l.type)return!1;if(!n&&"touchstart"===l.type&&l.touches?.length>1)return l.preventDefault(),!1;if(!h&&!i&&!f&&"wheel"===l.type||!r&&("mousedown"===l.type||"touchstart"===l.type)||Array.isArray(r)&&!r.includes(l.button)&&"mousedown"===l.type)return!1;const d=Array.isArray(r)&&r.includes(l.button)||!l.button||l.button<=1;return(!l.ctrlKey||"wheel"===l.type)&&d}}({zoomActivationKeyPressed:k,panOnDrag:o,zoomOnScroll:y,panOnScroll:i,zoomOnDoubleClick:S,zoomOnPinch:v,userSelectionActive:r,noPanClassName:t,noWheelClassName:e,lib:E});f.filter(T),S?d.on("dblclick.zoom",p):d.on("dblclick.zoom",null)},destroy:m,setViewport:async function(e,t){const n=Io(e);return await b(n,t),new Promise((e=>e(n)))},setViewportConstrained:w,getViewport:function(){const e=d?Rr(d.node()):{x:0,y:0,k:1};return{x:e.x,y:e.y,zoom:e.k}},scaleTo:function(e,t){return d?new Promise((n=>{f?.scaleTo(jo(d,t?.duration,(()=>n(!0))),e)})):Promise.resolve(!1)},scaleBy:function(e,t){return d?new Promise((n=>{f?.scaleBy(jo(d,t?.duration,(()=>n(!0))),e)})):Promise.resolve(!1)},setScaleExtent:function(e){f?.scaleExtent(e)},setTranslateExtent:function(e){f?.translateExtent(e)},syncViewport:function(e){if(d){const t=Io(e),n=d.property("__zoom");(n.k!==e.zoom||n.x!==e.x||n.y!==e.y)&&f?.transform(d,t,null,{sync:!0})}},setClickDistance:function(e){const t=!Mi(e)||e<0?0:e;f?.clickDistance(t)}}}({domNode:E.current,minZoom:f,maxZoom:d,translateExtent:h,viewport:l,paneClickDistance:S,onDraggingChange:e=>k.setState({paneDragging:e}),onPanZoomStart:(e,t)=>{const{onViewportChangeStart:n,onMoveStart:r}=k.getState();r?.(e,t),n?.(t)},onPanZoom:(e,t)=>{const{onViewportChange:n,onMove:r}=k.getState();r?.(e,t),n?.(t)},onPanZoomEnd:(e,t)=>{const{onViewportChangeEnd:n,onMoveEnd:r}=k.getState();r?.(e,t),n?.(t)}});const{x:e,y:t,zoom:n}=C.current.getViewport();return k.setState({panZoom:C.current,transform:[e,t,n],domNode:E.current.closest(".react-flow")}),()=>{C.current?.destroy()}}}),[]),(0,s.useEffect)((()=>{C.current?.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:i,panOnScrollSpeed:o,panOnScrollMode:a,zoomOnDoubleClick:c,panOnDrag:u,zoomActivationKeyPressed:T,preventScrolling:p,noPanClassName:w,userSelectionActive:x,noWheelClassName:m,lib:M,onTransformChange:_})}),[e,t,n,i,o,a,c,u,T,p,w,x,m,M,_]),(0,r.jsx)("div",{className:"react-flow__renderer",ref:E,style:gs,children:b})}const ms=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function ws(){const{userSelectionActive:e,userSelectionRect:t}=ma(ms,da);return e&&t?(0,r.jsx)("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}const vs=(e,t)=>n=>{n.target===t.current&&e?.(n)},ys=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function Ss({isSelecting:e,selectionKeyPressed:t,selectionMode:n=Yr.Full,panOnDrag:i,selectionOnDrag:o,onSelectionStart:a,onSelectionEnd:c,onPaneClick:u,onPaneContextMenu:l,onPaneScroll:h,onPaneMouseEnter:f,onPaneMouseMove:d,onPaneMouseLeave:g,children:p}){const b=wa(),{userSelectionActive:m,elementsSelectable:w,dragging:v,connectionInProgress:y}=ma(ys,da),S=w&&(e||m),k=(0,s.useRef)(null),E=(0,s.useRef)(),x=(0,s.useRef)(new Set),M=(0,s.useRef)(new Set),T=(0,s.useRef)(!1),C=(0,s.useRef)(!1),_=e=>{T.current||y?T.current=!1:(u?.(e),b.getState().resetSelectedElements(),b.setState({nodesSelectionActive:!1}))},P=h?e=>h(e):void 0,I=!0===i||Array.isArray(i)&&i.includes(0);return(0,r.jsxs)("div",{className:te(["react-flow__pane",{draggable:I,dragging:v,selection:e}]),onClick:S?void 0:vs(_,k),onContextMenu:vs((e=>{Array.isArray(i)&&i?.includes(2)?e.preventDefault():l?.(e)}),k),onWheel:vs(P,k),onPointerEnter:S?void 0:f,onPointerDown:S?t=>{const{resetSelectedElements:n,domNode:r}=b.getState();if(E.current=r?.getBoundingClientRect(),!w||!e||0!==t.button||t.target!==k.current||!E.current)return;t.target?.setPointerCapture?.(t.pointerId),C.current=!0,T.current=!1;const{x:i,y:o}=Hi(t.nativeEvent,E.current);n(),b.setState({userSelectionRect:{width:0,height:0,startX:i,startY:o,x:i,y:o}}),a?.(t)}:d,onPointerMove:S?e=>{const{userSelectionRect:t,transform:r,nodeLookup:i,edgeLookup:o,connectionLookup:a,triggerNodeChanges:s,triggerEdgeChanges:c,defaultEdgeOptions:u}=b.getState();if(!E.current||!t)return;T.current=!0;const{x:l,y:h}=Hi(e.nativeEvent,E.current),{startX:f,startY:d}=t,g={startX:f,startY:d,x:l<f?l:f,y:h<d?h:d,width:Math.abs(l-f),height:Math.abs(h-d)},p=x.current,m=M.current;x.current=new Set(ui(i,g,r,n===Yr.Partial,!0).map((e=>e.id))),M.current=new Set;const w=u?.selectable??!0;for(const e of x.current){const t=a.get(e);if(t)for(const{edgeId:e}of t.values()){const t=o.get(e);t&&(t.selectable??w)&&M.current.add(e)}}Li(p,x.current)||s(Za(i,x.current,!0)),Li(m,M.current)||c(Za(o,M.current)),b.setState({userSelectionRect:g,userSelectionActive:!0,nodesSelectionActive:!1})}:d,onPointerUp:S?e=>{if(0!==e.button||!C.current)return;e.target?.releasePointerCapture?.(e.pointerId);const{userSelectionRect:n}=b.getState();!m&&n&&e.target===k.current&&_?.(e),b.setState({userSelectionActive:!1,userSelectionRect:null,nodesSelectionActive:x.current.size>0}),c?.(e),(t||o)&&(T.current=!1),C.current=!1}:void 0,onPointerLeave:g,ref:k,style:gs,children:[p,(0,r.jsx)(ws,{})]})}function ks({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:i,unselectNodesAndEdges:o,multiSelectionActive:a,nodeLookup:s,onError:c}=t.getState(),u=s.get(e);u?(t.setState({nodesSelectionActive:!1}),u.selected?(n||u.selected&&a)&&(o({nodes:[u],edges:[]}),requestAnimationFrame((()=>r?.current?.blur()))):i([e])):c?.("012",Jr.error012(e))}function Es({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:i,isSelectable:o,nodeClickDistance:a}){const c=wa(),[u,l]=(0,s.useState)(!1),h=(0,s.useRef)();return(0,s.useEffect)((()=>{h.current=function({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:i}){let o={x:null,y:null},a=0,s=new Map,c=!1,u={x:0,y:0},l=null,h=!1,f=null,d=!1;return{update:function({noDragClassName:g,handleSelector:p,domNode:b,isSelectable:m,nodeId:w,nodeClickDistance:v=0}){function y({x:e,y:n},i){const{nodeLookup:a,nodeExtent:c,snapGrid:u,snapToGrid:l,nodeOrigin:h,onNodeDrag:f,onSelectionDrag:d,onError:g,updateNodePositions:p}=t();o={x:e,y:n};let b=!1,m={x:0,y:0,x2:0,y2:0};if(s.size>1&&c){const e=ci(s);m=wi(e)}for(const[t,r]of s){if(!a.has(t))continue;let i={x:e-r.distance.x,y:n-r.distance.y};l&&(i=Ci(i,u));let o=[[c[0][0],c[0][1]],[c[1][0],c[1][1]]];if(s.size>1&&c&&!r.extent){const{positionAbsolute:e}=r.internals,t=e.x-m.x+c[0][0],n=e.x+r.measured.width-m.x2+c[1][0];o=[[t,e.y-m.y+c[0][1]],[n,e.y+r.measured.height-m.y2+c[1][1]]]}const{position:f,positionAbsolute:d}=hi({nodeId:t,nextPosition:i,nodeLookup:a,nodeExtent:o,nodeOrigin:h,onError:g});b=b||r.position.x!==f.x||r.position.y!==f.y,r.position=f,r.internals.positionAbsolute=d}if(b&&(p(s,!0),i&&(r||f||!w&&d))){const[e,t]=ko({nodeId:w,dragItems:s,nodeLookup:a});r?.(i,s,e,t),f?.(i,e,t),w||d?.(i,t)}}async function S(){if(!l)return;const{transform:e,panBy:n,autoPanSpeed:r,autoPanOnNodeDrag:i}=t();if(!i)return c=!1,void cancelAnimationFrame(a);const[s,h]=bi(u,l,r);(0!==s||0!==h)&&(o.x=(o.x??0)-s/e[2],o.y=(o.y??0)-h/e[2],await n({x:s,y:h})&&y(o,null)),a=requestAnimationFrame(S)}function k(r){const{nodeLookup:i,multiSelectionActive:a,nodesDraggable:c,transform:u,snapGrid:f,snapToGrid:d,selectNodesOnDrag:g,onNodeDragStart:p,onSelectionDragStart:b,unselectNodesAndEdges:v}=t();h=!0,(!g||!m)&&!a&&w&&(i.get(w)?.selected||v()),m&&g&&w&&e?.(w);const y=Di(r.sourceEvent,{transform:u,snapGrid:f,snapToGrid:d,containerBounds:l});if(o=y,s=function(e,t,n,r){const i=new Map;for(const[o,a]of e)if((a.selected||a.id===r)&&(!a.parentId||!yo(a,e))&&(a.draggable||t&&typeof a.draggable>"u")){const t=e.get(o);t&&i.set(o,{id:o,position:t.position||{x:0,y:0},distance:{x:n.x-t.internals.positionAbsolute.x,y:n.y-t.internals.positionAbsolute.y},extent:t.extent,parentId:t.parentId,origin:t.origin,expandParent:t.expandParent,internals:{positionAbsolute:t.internals.positionAbsolute||{x:0,y:0}},measured:{width:t.measured.width??0,height:t.measured.height??0}})}return i}(i,c,y,w),s.size>0&&(n||p||!w&&b)){const[e,t]=ko({nodeId:w,dragItems:s,nodeLookup:i});n?.(r.sourceEvent,s,e,t),p?.(r.sourceEvent,e,t),w||b?.(r.sourceEvent,t)}}f=wt(b);const E=Ot().clickDistance(v).on("start",(e=>{const{domNode:n,nodeDragThreshold:r,transform:i,snapGrid:a,snapToGrid:s}=t();l=n?.getBoundingClientRect()||null,d=!1,0===r&&k(e),o=Di(e.sourceEvent,{transform:i,snapGrid:a,snapToGrid:s,containerBounds:l}),u=Hi(e.sourceEvent,l)})).on("drag",(e=>{const{autoPanOnNodeDrag:n,transform:r,snapGrid:i,snapToGrid:a,nodeDragThreshold:f,nodeLookup:g}=t(),p=Di(e.sourceEvent,{transform:r,snapGrid:i,snapToGrid:a,containerBounds:l});if(("touchmove"===e.sourceEvent.type&&e.sourceEvent.touches.length>1||w&&!g.has(w))&&(d=!0),!d){if(!c&&n&&h&&(c=!0,S()),!h){const t=p.xSnapped-(o.x??0),n=p.ySnapped-(o.y??0);Math.sqrt(t*t+n*n)>f&&k(e)}(o.x!==p.xSnapped||o.y!==p.ySnapped)&&s&&h&&(u=Hi(e.sourceEvent,l),y(p,e.sourceEvent))}})).on("end",(e=>{if(h&&!d&&(c=!1,h=!1,cancelAnimationFrame(a),s.size>0)){const{nodeLookup:n,updateNodePositions:r,onNodeDragStop:o,onSelectionDragStop:a}=t();if(r(s,!1),i||o||!w&&a){const[t,r]=ko({nodeId:w,dragItems:s,nodeLookup:n,dragging:!1});i?.(e.sourceEvent,s,t,r),o?.(e.sourceEvent,t,r),w||a?.(e.sourceEvent,r)}}})).filter((e=>{const t=e.target;return!e.button&&(!g||!So(t,`.${g}`,b))&&(!p||So(t,p,b))}));f.call(E)},destroy:function(){f?.on(".drag",null)}}}({getStoreItems:()=>c.getState(),onNodeMouseDown:t=>{ks({id:t,store:c,nodeRef:e})},onDragStart:()=>{l(!0)},onDragStop:()=>{l(!1)}})}),[]),(0,s.useEffect)((()=>{if(t)h.current?.destroy();else if(e.current)return h.current?.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:o,nodeId:i,nodeClickDistance:a}),()=>{h.current?.destroy()}}),[n,r,t,o,e,i]),u}const xs=e=>t=>t.selected&&(t.draggable||e&&typeof t.draggable>"u");function Ms(){const e=wa();return(0,s.useCallback)((t=>{const{nodeExtent:n,snapToGrid:r,snapGrid:i,nodesDraggable:o,onError:a,updateNodePositions:s,nodeLookup:c,nodeOrigin:u}=e.getState(),l=new Map,h=xs(o),f=r?i[0]:5,d=r?i[1]:5,g=t.direction.x*f*t.factor,p=t.direction.y*d*t.factor;for(const[,e]of c){if(!h(e))continue;let t={x:e.internals.positionAbsolute.x+g,y:e.internals.positionAbsolute.y+p};r&&(t=Ci(t,i));const{position:o,positionAbsolute:s}=hi({nodeId:e.id,nextPosition:t,nodeLookup:c,nodeExtent:n,nodeOrigin:u,onError:a});e.position=o,e.internals.positionAbsolute=s,l.set(e.id,e)}s(l)}),[])}const Ts=(0,s.createContext)(null),Cs=Ts.Provider;Ts.Consumer;const _s=()=>(0,s.useContext)(Ts),Ps=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),Is=(0,s.memo)(is((function({type:e="source",position:t=ti.Top,isValidConnection:n,isConnectable:i=!0,isConnectableStart:o=!0,isConnectableEnd:a=!0,id:s,onConnect:c,children:u,className:l,onMouseDown:h,onTouchStart:f,...d},g){const p=s||null,b="target"===e,m=wa(),w=_s(),{connectOnClick:v,noPanClassName:y,rfId:S}=ma(Ps,da),{connectingFrom:k,connectingTo:E,clickConnecting:x,isPossibleEndHandle:M,connectionInProcess:T,clickConnectionInProcess:C,valid:_}=ma(((e,t,n)=>r=>{const{connectionClickStartHandle:i,connectionMode:o,connection:a}=r,{fromHandle:s,toHandle:c,isValid:u}=a,l=c?.nodeId===e&&c?.id===t&&c?.type===n;return{connectingFrom:s?.nodeId===e&&s?.id===t&&s?.type===n,connectingTo:l,clickConnecting:i?.nodeId===e&&i?.id===t&&i?.type===n,isPossibleEndHandle:o===Kr.Strict?s?.type!==n:e!==s?.nodeId||t!==s?.id,connectionInProcess:!!s,clickConnectionInProcess:!!i,valid:l&&u}})(w,p,e),da);w||m.getState().onError?.("010",Jr.error010());const P=e=>{const{defaultEdgeOptions:t,onConnect:n,hasDefaultEdges:r}=m.getState(),i={...t,...e};if(r){const{edges:e,setEdges:t}=m.getState();t(((e,t)=>{if(!e.source||!e.target)return Ti("006",Jr.error006()),t;let n;return n=ii(e)?{...e}:{...e,id:Zi(e)},((e,t)=>t.some((t=>!(t.source!==e.source||t.target!==e.target||t.sourceHandle!==e.sourceHandle&&(t.sourceHandle||e.sourceHandle)||t.targetHandle!==e.targetHandle&&(t.targetHandle||e.targetHandle)))))(n,t)?t:(null===n.sourceHandle&&delete n.sourceHandle,null===n.targetHandle&&delete n.targetHandle,t.concat(n))})(i,e))}n?.(i),c?.(i)},I=e=>{if(!w)return;const t=qi(e.nativeEvent);if(o&&(t&&0===e.button||!t)){const t=m.getState();Co.onPointerDown(e.nativeEvent,{autoPanOnConnect:t.autoPanOnConnect,connectionMode:t.connectionMode,connectionRadius:t.connectionRadius,domNode:t.domNode,nodeLookup:t.nodeLookup,lib:t.lib,isTarget:b,handleId:p,nodeId:w,flowId:t.rfId,panBy:t.panBy,cancelConnection:t.cancelConnection,onConnectStart:t.onConnectStart,onConnectEnd:t.onConnectEnd,updateConnection:t.updateConnection,onConnect:P,isValidConnection:n||t.isValidConnection,getTransform:()=>m.getState().transform,getFromHandle:()=>m.getState().connection.fromHandle,autoPanSpeed:t.autoPanSpeed})}t?h?.(e):f?.(e)};return(0,r.jsx)("div",{"data-handleid":p,"data-nodeid":w,"data-handlepos":t,"data-id":`${S}-${w}-${p}-${e}`,className:te(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",y,l,{source:!b,target:b,connectable:i,connectablestart:o,connectableend:a,clickconnecting:x,connectingfrom:k,connectingto:E,valid:_,connectionindicator:i&&(!T||M)&&(T||C?a:o)}]),onMouseDown:I,onTouchStart:I,onClick:v?t=>{const{onClickConnectStart:r,onClickConnectEnd:i,connectionClickStartHandle:a,connectionMode:s,isValidConnection:c,lib:u,rfId:l,nodeLookup:h,connection:f}=m.getState();if(!w||!a&&!o)return;if(!a)return r?.(t.nativeEvent,{nodeId:w,handleId:p,handleType:e}),void m.setState({connectionClickStartHandle:{nodeId:w,type:e,id:p}});const d=Bi(t.target),g=n||c,{connection:b,isValid:v}=Co.isValid(t.nativeEvent,{handle:{nodeId:w,id:p,type:e},connectionMode:s,fromNodeId:a.nodeId,fromHandleId:a.id||null,fromType:a.type,isValidConnection:g,flowId:l,doc:d,lib:u,nodeLookup:h});v&&b&&P(b);const y=structuredClone(f);delete y.inProgress,y.toPosition=y.toHandle?y.toHandle.position:null,i?.(t,y),m.setState({connectionClickStartHandle:null})}:void 0,ref:g,...d,children:u})}))),As={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},Os={input:function({data:e,isConnectable:t,sourcePosition:n=ti.Bottom}){return(0,r.jsxs)(r.Fragment,{children:[e?.label,(0,r.jsx)(Is,{type:"source",position:n,isConnectable:t})]})},default:function({data:e,isConnectable:t,targetPosition:n=ti.Top,sourcePosition:i=ti.Bottom}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(Is,{type:"target",position:n,isConnectable:t}),e?.label,(0,r.jsx)(Is,{type:"source",position:i,isConnectable:t})]})},output:function({data:e,isConnectable:t,targetPosition:n=ti.Top}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(Is,{type:"target",position:n,isConnectable:t}),e?.label]})},group:function(){return null}},js=e=>{const{width:t,height:n,x:r,y:i}=ci(e.nodeLookup,{filter:e=>!!e.selected});return{width:Mi(t)?t:null,height:Mi(n)?n:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${r}px,${i}px)`}};function $s({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const i=wa(),{width:o,height:a,transformString:c,userSelectionActive:u}=ma(js,da),l=Ms(),h=(0,s.useRef)(null);if((0,s.useEffect)((()=>{n||h.current?.focus({preventScroll:!0})}),[n]),Es({nodeRef:h}),u||!o||!a)return null;const f=e?t=>{const n=i.getState().nodes.filter((e=>e.selected));e(t,n)}:void 0;return(0,r.jsx)("div",{className:te(["react-flow__nodesselection","react-flow__container",t]),style:{transform:c},children:(0,r.jsx)("div",{ref:h,className:"react-flow__nodesselection-rect",onContextMenu:f,tabIndex:n?void 0:-1,onKeyDown:n?void 0:e=>{Object.prototype.hasOwnProperty.call(As,e.key)&&(e.preventDefault(),l({direction:As[e.key],factor:e.shiftKey?4:1}))},style:{width:o,height:a}})})}const Rs=typeof window<"u"?window:void 0,Ns=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function Ls({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:i,onPaneMouseLeave:o,onPaneContextMenu:a,onPaneScroll:c,paneClickDistance:u,deleteKeyCode:l,selectionKeyCode:h,selectionOnDrag:f,selectionMode:d,onSelectionStart:g,onSelectionEnd:p,multiSelectionKeyCode:b,panActivationKeyCode:m,zoomActivationKeyCode:w,elementsSelectable:v,zoomOnScroll:y,zoomOnPinch:S,panOnScroll:k,panOnScrollSpeed:E,panOnScrollMode:x,zoomOnDoubleClick:M,panOnDrag:T,defaultViewport:C,translateExtent:_,minZoom:P,maxZoom:I,preventScrolling:A,onSelectionContextMenu:O,noWheelClassName:j,noPanClassName:$,disableKeyboardA11y:R,onViewportChange:N,isControlledViewport:L}){const{nodesSelectionActive:D,userSelectionActive:F}=ma(Ns),B=Ha(h,{target:Rs}),z=Ha(m,{target:Rs}),U=z||T,q=z||k,H=f&&!0!==U,J=B||F||H;return function({deleteKeyCode:e,multiSelectionKeyCode:t}){const n=wa(),{deleteElements:r}=ls(),i=Ha(e,fs),o=Ha(t,{target:ds});(0,s.useEffect)((()=>{if(i){const{edges:e,nodes:t}=n.getState();r({nodes:t.filter(hs),edges:e.filter(hs)}),n.setState({nodesSelectionActive:!1})}}),[i]),(0,s.useEffect)((()=>{n.setState({multiSelectionActive:o})}),[o])}({deleteKeyCode:l,multiSelectionKeyCode:b}),(0,r.jsx)(bs,{onPaneContextMenu:a,elementsSelectable:v,zoomOnScroll:y,zoomOnPinch:S,panOnScroll:q,panOnScrollSpeed:E,panOnScrollMode:x,zoomOnDoubleClick:M,panOnDrag:!B&&U,defaultViewport:C,translateExtent:_,minZoom:P,maxZoom:I,zoomActivationKeyCode:w,preventScrolling:A,noWheelClassName:j,noPanClassName:$,onViewportChange:N,isControlledViewport:L,paneClickDistance:u,children:(0,r.jsxs)(Ss,{onSelectionStart:g,onSelectionEnd:p,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:i,onPaneMouseLeave:o,onPaneContextMenu:a,onPaneScroll:c,panOnDrag:U,isSelecting:!!J,selectionMode:d,selectionKeyPressed:B,selectionOnDrag:H,children:[e,D&&(0,r.jsx)($s,{onSelectionContextMenu:O,noPanClassName:$,disableKeyboardA11y:R})]})})}Ls.displayName="FlowRenderer";const Ds=(0,s.memo)(Ls),Fs=e=>e.updateNodeInternals;function Bs({id:e,onClick:t,onMouseEnter:n,onMouseMove:i,onMouseLeave:o,onContextMenu:a,onDoubleClick:c,nodesDraggable:u,elementsSelectable:l,nodesConnectable:h,nodesFocusable:f,resizeObserver:d,noDragClassName:g,noPanClassName:p,disableKeyboardA11y:b,rfId:m,nodeTypes:w,nodeClickDistance:v,onError:y}){const{node:S,internals:k,isParent:E}=ma((t=>{const n=t.nodeLookup.get(e),r=t.parentLookup.has(e);return{node:n,internals:n.internals,isParent:r}}),da);let x=S.type||"default",M=w?.[x]||Os[x];void 0===M&&(y?.("003",Jr.error003(x)),x="default",M=Os.default);const T=!!(S.draggable||u&&typeof S.draggable>"u"),C=!!(S.selectable||l&&typeof S.selectable>"u"),_=!!(S.connectable||h&&typeof S.connectable>"u"),P=!!(S.focusable||f&&typeof S.focusable>"u"),I=wa(),A=Ri(S),O=function({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){const i=wa(),o=(0,s.useRef)(null),a=(0,s.useRef)(null),c=(0,s.useRef)(e.sourcePosition),u=(0,s.useRef)(e.targetPosition),l=(0,s.useRef)(t),h=n&&!!e.internals.handleBounds;return(0,s.useEffect)((()=>{o.current&&!e.hidden&&(!h||a.current!==o.current)&&(a.current&&r?.unobserve(a.current),r?.observe(o.current),a.current=o.current)}),[h,e.hidden]),(0,s.useEffect)((()=>()=>{a.current&&(r?.unobserve(a.current),a.current=null)}),[]),(0,s.useEffect)((()=>{if(o.current){const n=l.current!==t,r=c.current!==e.sourcePosition,a=u.current!==e.targetPosition;(n||r||a)&&(l.current=t,c.current=e.sourcePosition,u.current=e.targetPosition,i.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:o.current,force:!0}]])))}}),[e.id,t,e.sourcePosition,e.targetPosition]),o}({node:S,nodeType:x,hasDimensions:A,resizeObserver:d}),j=Es({nodeRef:O,disabled:S.hidden||!T,noDragClassName:g,handleSelector:S.dragHandle,nodeId:e,isSelectable:C,nodeClickDistance:v}),$=Ms();if(S.hidden)return null;const R=$i(S),N=function(e){return void 0===e.internals.handleBounds?{width:e.width??e.initialWidth??e.style?.width,height:e.height??e.initialHeight??e.style?.height}:{width:e.width??e.style?.width,height:e.height??e.style?.height}}(S),L=C||T||t||n||i||o,D=n?e=>n(e,{...k.userNode}):void 0,F=i?e=>i(e,{...k.userNode}):void 0,B=o?e=>o(e,{...k.userNode}):void 0,z=a?e=>a(e,{...k.userNode}):void 0,U=c?e=>c(e,{...k.userNode}):void 0;return(0,r.jsx)("div",{className:te(["react-flow__node",`react-flow__node-${x}`,{[p]:T},S.className,{selected:S.selected,selectable:C,parent:E,draggable:T,dragging:j}]),ref:O,style:{zIndex:k.z,transform:`translate(${k.positionAbsolute.x}px,${k.positionAbsolute.y}px)`,pointerEvents:L?"all":"none",visibility:A?"visible":"hidden",...S.style,...N},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:D,onMouseMove:F,onMouseLeave:B,onContextMenu:z,onClick:n=>{const{selectNodesOnDrag:r,nodeDragThreshold:i}=I.getState();C&&(!r||!T||i>0)&&ks({id:e,store:I,nodeRef:O}),t&&t(n,{...k.userNode})},onDoubleClick:U,onKeyDown:P?t=>{if(!Ui(t.nativeEvent)&&!b)if(Vr.includes(t.key)&&C){const n="Escape"===t.key;ks({id:e,store:I,unselect:n,nodeRef:O})}else T&&S.selected&&Object.prototype.hasOwnProperty.call(As,t.key)&&(t.preventDefault(),I.setState({ariaLiveMessage:`Moved selected node ${t.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~k.positionAbsolute.x}, y: ${~~k.positionAbsolute.y}`}),$({direction:As[t.key],factor:t.shiftKey?4:1}))}:void 0,tabIndex:P?0:void 0,role:P?"button":void 0,"aria-describedby":b?void 0:`${Sa}-${m}`,"aria-label":S.ariaLabel,children:(0,r.jsx)(Cs,{value:e,children:(0,r.jsx)(M,{id:e,data:S.data,type:x,positionAbsoluteX:k.positionAbsolute.x,positionAbsoluteY:k.positionAbsolute.y,selected:S.selected??!1,selectable:C,draggable:T,deletable:S.deletable??!0,isConnectable:_,sourcePosition:S.sourcePosition,targetPosition:S.targetPosition,dragging:j,dragHandle:S.dragHandle,zIndex:k.z,parentId:S.parentId,...R})})})}const zs=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function Us(e){const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:i,elementsSelectable:o,onError:a}=ma(zs,da),c=function(e){return ma((0,s.useCallback)((e=>t=>e?ui(t.nodeLookup,{x:0,y:0,width:t.width,height:t.height},t.transform,!0).map((e=>e.id)):Array.from(t.nodeLookup.keys()))(e),[e]),da)}(e.onlyRenderVisibleElements),u=function(){const e=ma(Fs),[t]=(0,s.useState)((()=>typeof ResizeObserver>"u"?null:new ResizeObserver((t=>{const n=new Map;t.forEach((e=>{const t=e.target.getAttribute("data-id");n.set(t,{id:t,nodeElement:e.target,force:!0})})),e(n)}))));return(0,s.useEffect)((()=>()=>{t?.disconnect()}),[t]),t}();return(0,r.jsx)("div",{className:"react-flow__nodes",style:gs,children:c.map((s=>(0,r.jsx)(Bs,{id:s,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:u,nodesDraggable:t,nodesConnectable:n,nodesFocusable:i,elementsSelectable:o,nodeClickDistance:e.nodeClickDistance,onError:a},s)))})}Us.displayName="NodeRenderer";const qs=(0,s.memo)(Us),Hs={[ei.Arrow]:({color:e="none",strokeWidth:t=1})=>(0,r.jsx)("polyline",{style:{stroke:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",fill:"none",points:"-5,-4 0,0 -5,4"}),[ei.ArrowClosed]:({color:e="none",strokeWidth:t=1})=>(0,r.jsx)("polyline",{style:{stroke:e,fill:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},Js=({id:e,type:t,color:n,width:i=12.5,height:o=12.5,markerUnits:a="strokeWidth",strokeWidth:c,orient:u="auto-start-reverse"})=>{const l=function(e){const t=wa();return(0,s.useMemo)((()=>Object.prototype.hasOwnProperty.call(Hs,e)?Hs[e]:(t.getState().onError?.("009",Jr.error009(e)),null)),[e])}(t);return l?(0,r.jsx)("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${i}`,markerHeight:`${o}`,viewBox:"-10 -10 20 20",markerUnits:a,orient:u,refX:"0",refY:"0",children:(0,r.jsx)(l,{color:n,strokeWidth:c})}):null},Gs=({defaultColor:e,rfId:t})=>{const n=ma((e=>e.edges)),i=ma((e=>e.defaultEdgeOptions)),o=(0,s.useMemo)((()=>function(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:i}){const o=new Set;return e.reduce(((e,a)=>([a.markerStart||r,a.markerEnd||i].forEach((r=>{if(r&&"object"==typeof r){const i=uo(r,t);o.has(i)||(e.push({id:i,color:r.color||n,...r}),o.add(i))}})),e)),[]).sort(((e,t)=>e.id.localeCompare(t.id)))}(n,{id:t,defaultColor:e,defaultMarkerStart:i?.markerStart,defaultMarkerEnd:i?.markerEnd})),[n,i,t,e]);return o.length?(0,r.jsx)("svg",{className:"react-flow__marker",children:(0,r.jsx)("defs",{children:o.map((e=>(0,r.jsx)(Js,{id:e.id,type:e.type,color:e.color,width:e.width,height:e.height,markerUnits:e.markerUnits,strokeWidth:e.strokeWidth,orient:e.orient},e.id)))})}):null};Gs.displayName="MarkerDefinitions";var Vs=(0,s.memo)(Gs);function Ks({x:e,y:t,label:n,labelStyle:i,labelShowBg:o=!0,labelBgStyle:a,labelBgPadding:c=[2,4],labelBgBorderRadius:u=2,children:l,className:h,...f}){const[d,g]=(0,s.useState)({x:1,y:0,width:0,height:0}),p=te(["react-flow__edge-textwrapper",h]),b=(0,s.useRef)(null);return(0,s.useEffect)((()=>{if(b.current){const e=b.current.getBBox();g({x:e.x,y:e.y,width:e.width,height:e.height})}}),[n]),n?(0,r.jsxs)("g",{transform:`translate(${e-d.width/2} ${t-d.height/2})`,className:p,visibility:d.width?"visible":"hidden",...f,children:[o&&(0,r.jsx)("rect",{width:d.width+2*c[0],x:-c[0],y:-c[1],height:d.height+2*c[1],className:"react-flow__edge-textbg",style:a,rx:u,ry:u}),(0,r.jsx)("text",{className:"react-flow__edge-text",y:d.height/2,dy:"0.3em",ref:b,style:i,children:n}),l]}):null}Ks.displayName="EdgeText";const Ws=(0,s.memo)(Ks);function Xs({path:e,labelX:t,labelY:n,label:i,labelStyle:o,labelShowBg:a,labelBgStyle:s,labelBgPadding:c,labelBgBorderRadius:u,interactionWidth:l=20,...h}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{...h,d:e,fill:"none",className:te(["react-flow__edge-path",h.className])}),l&&(0,r.jsx)("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:l,className:"react-flow__edge-interaction"}),i&&Mi(t)&&Mi(n)?(0,r.jsx)(Ws,{x:t,y:n,label:i,labelStyle:o,labelShowBg:a,labelBgStyle:s,labelBgPadding:c,labelBgBorderRadius:u}):null]})}function Ys({pos:e,x1:t,y1:n,x2:r,y2:i}){return e===ti.Left||e===ti.Right?[.5*(t+r),n]:[t,.5*(n+i)]}function Qs({sourceX:e,sourceY:t,sourcePosition:n=ti.Bottom,targetX:r,targetY:i,targetPosition:o=ti.Top}){const[a,s]=Ys({pos:n,x1:e,y1:t,x2:r,y2:i}),[c,u]=Ys({pos:o,x1:r,y1:i,x2:e,y2:t}),[l,h,f,d]=Gi({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:a,sourceControlY:s,targetControlX:c,targetControlY:u});return[`M${e},${t} C${a},${s} ${c},${u} ${r},${i}`,l,h,f,d]}function Zs(e){return(0,s.memo)((({id:t,sourceX:n,sourceY:i,targetX:o,targetY:a,sourcePosition:s=ti.Bottom,targetPosition:c=ti.Top,label:u,labelStyle:l,labelShowBg:h,labelBgStyle:f,labelBgPadding:d,labelBgBorderRadius:g,style:p,markerEnd:b,markerStart:m,interactionWidth:w})=>{const[v,y,S]=Qs({sourceX:n,sourceY:i,sourcePosition:s,targetX:o,targetY:a,targetPosition:c}),k=e.isInternal?void 0:t;return(0,r.jsx)(Xs,{id:k,path:v,labelX:y,labelY:S,label:u,labelStyle:l,labelShowBg:h,labelBgStyle:f,labelBgPadding:d,labelBgBorderRadius:g,style:p,markerEnd:b,markerStart:m,interactionWidth:w})}))}const ec=Zs({isInternal:!1}),tc=Zs({isInternal:!0});function nc(e){return(0,s.memo)((({id:t,sourceX:n,sourceY:i,targetX:o,targetY:a,label:s,labelStyle:c,labelShowBg:u,labelBgStyle:l,labelBgPadding:h,labelBgBorderRadius:f,style:d,sourcePosition:g=ti.Bottom,targetPosition:p=ti.Top,markerEnd:b,markerStart:m,pathOptions:w,interactionWidth:v})=>{const[y,S,k]=io({sourceX:n,sourceY:i,sourcePosition:g,targetX:o,targetY:a,targetPosition:p,borderRadius:w?.borderRadius,offset:w?.offset}),E=e.isInternal?void 0:t;return(0,r.jsx)(Xs,{id:E,path:y,labelX:S,labelY:k,label:s,labelStyle:c,labelShowBg:u,labelBgStyle:l,labelBgPadding:h,labelBgBorderRadius:f,style:d,markerEnd:b,markerStart:m,interactionWidth:v})}))}ec.displayName="SimpleBezierEdge",tc.displayName="SimpleBezierEdgeInternal";const rc=nc({isInternal:!1}),ic=nc({isInternal:!0});function oc(e){return(0,s.memo)((({id:t,...n})=>{const i=e.isInternal?void 0:t;return(0,r.jsx)(rc,{...n,id:i,pathOptions:(0,s.useMemo)((()=>({borderRadius:0,offset:n.pathOptions?.offset})),[n.pathOptions?.offset])})}))}rc.displayName="SmoothStepEdge",ic.displayName="SmoothStepEdgeInternal";const ac=oc({isInternal:!1}),sc=oc({isInternal:!0});function cc(e){return(0,s.memo)((({id:t,sourceX:n,sourceY:i,targetX:o,targetY:a,label:s,labelStyle:c,labelShowBg:u,labelBgStyle:l,labelBgPadding:h,labelBgBorderRadius:f,style:d,markerEnd:g,markerStart:p,interactionWidth:b})=>{const[m,w,v]=eo({sourceX:n,sourceY:i,targetX:o,targetY:a}),y=e.isInternal?void 0:t;return(0,r.jsx)(Xs,{id:y,path:m,labelX:w,labelY:v,label:s,labelStyle:c,labelShowBg:u,labelBgStyle:l,labelBgPadding:h,labelBgBorderRadius:f,style:d,markerEnd:g,markerStart:p,interactionWidth:b})}))}ac.displayName="StepEdge",sc.displayName="StepEdgeInternal";const uc=cc({isInternal:!1}),lc=cc({isInternal:!0});function hc(e){return(0,s.memo)((({id:t,sourceX:n,sourceY:i,targetX:o,targetY:a,sourcePosition:s=ti.Bottom,targetPosition:c=ti.Top,label:u,labelStyle:l,labelShowBg:h,labelBgStyle:f,labelBgPadding:d,labelBgBorderRadius:g,style:p,markerEnd:b,markerStart:m,pathOptions:w,interactionWidth:v})=>{const[y,S,k]=Wi({sourceX:n,sourceY:i,sourcePosition:s,targetX:o,targetY:a,targetPosition:c,curvature:w?.curvature}),E=e.isInternal?void 0:t;return(0,r.jsx)(Xs,{id:E,path:y,labelX:S,labelY:k,label:u,labelStyle:l,labelShowBg:h,labelBgStyle:f,labelBgPadding:d,labelBgBorderRadius:g,style:p,markerEnd:b,markerStart:m,interactionWidth:v})}))}uc.displayName="StraightEdge",lc.displayName="StraightEdgeInternal";const fc=hc({isInternal:!1}),dc=hc({isInternal:!0});fc.displayName="BezierEdge",dc.displayName="BezierEdgeInternal";const gc={default:dc,straight:lc,step:sc,smoothstep:ic,simplebezier:tc},pc={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},bc=(e,t,n)=>n===ti.Left?e-t:n===ti.Right?e+t:e,mc=(e,t,n)=>n===ti.Top?e-t:n===ti.Bottom?e+t:e,wc="react-flow__edgeupdater";function vc({position:e,centerX:t,centerY:n,radius:i=10,onMouseDown:o,onMouseEnter:a,onMouseOut:s,type:c}){return(0,r.jsx)("circle",{onMouseDown:o,onMouseEnter:a,onMouseOut:s,className:te([wc,`${wc}-${c}`]),cx:bc(t,i,e),cy:mc(n,i,e),r:i,stroke:"transparent",fill:"transparent"})}function yc({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:i,sourceY:o,targetX:a,targetY:s,sourcePosition:c,targetPosition:u,onReconnect:l,onReconnectStart:h,onReconnectEnd:f,setReconnecting:d,setUpdateHover:g}){const p=wa(),b=(e,t)=>{if(0!==e.button)return;const{autoPanOnConnect:r,domNode:i,isValidConnection:o,connectionMode:a,connectionRadius:s,lib:c,onConnectStart:u,onConnectEnd:g,cancelConnection:b,nodeLookup:m,rfId:w,panBy:v,updateConnection:y}=p.getState(),S="target"===t.type;d(!0),h?.(e,n,t.type),Co.onPointerDown(e.nativeEvent,{autoPanOnConnect:r,connectionMode:a,connectionRadius:s,domNode:i,handleId:t.id,nodeId:t.nodeId,nodeLookup:m,isTarget:S,edgeUpdaterType:t.type,lib:c,flowId:w,cancelConnection:b,panBy:v,isValidConnection:o,onConnect:e=>l?.(n,e),onConnectStart:u,onConnectEnd:g,onReconnectEnd:(e,r)=>{d(!1),f?.(e,n,t.type,r)},updateConnection:y,getTransform:()=>p.getState().transform,getFromHandle:()=>p.getState().connection.fromHandle})},m=()=>g(!0),w=()=>g(!1);return(0,r.jsxs)(r.Fragment,{children:[(!0===e||"source"===e)&&(0,r.jsx)(vc,{position:c,centerX:i,centerY:o,radius:t,onMouseDown:e=>b(e,{nodeId:n.target,id:n.targetHandle??null,type:"target"}),onMouseEnter:m,onMouseOut:w,type:"source"}),(!0===e||"target"===e)&&(0,r.jsx)(vc,{position:u,centerX:a,centerY:s,radius:t,onMouseDown:e=>b(e,{nodeId:n.source,id:n.sourceHandle??null,type:"source"}),onMouseEnter:m,onMouseOut:w,type:"target"})]})}function Sc({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:i,onClick:o,onDoubleClick:a,onContextMenu:c,onMouseEnter:u,onMouseMove:l,onMouseLeave:h,reconnectRadius:f,onReconnect:d,onReconnectStart:g,onReconnectEnd:p,rfId:b,edgeTypes:m,noPanClassName:w,onError:v,disableKeyboardA11y:y}){let S=ma((t=>t.edgeLookup.get(e)));const k=ma((e=>e.defaultEdgeOptions));S=k?{...k,...S}:S;let E=S.type||"default",x=m?.[E]||gc[E];void 0===x&&(v?.("011",Jr.error011(E)),E="default",x=gc.default);const M=!!(S.focusable||t&&typeof S.focusable>"u"),T=typeof d<"u"&&(S.reconnectable||n&&typeof S.reconnectable>"u"),C=!!(S.selectable||i&&typeof S.selectable>"u"),_=(0,s.useRef)(null),[P,I]=(0,s.useState)(!1),[A,O]=(0,s.useState)(!1),j=wa(),{zIndex:$,sourceX:R,sourceY:N,targetX:L,targetY:D,sourcePosition:F,targetPosition:B}=ma((0,s.useCallback)((t=>{const n=t.nodeLookup.get(S.source),r=t.nodeLookup.get(S.target);if(!n||!r)return{zIndex:S.zIndex,...pc};const i=function(e){const{sourceNode:t,targetNode:n}=e;if(!oo(t)||!oo(n))return null;const r=t.internals.handleBounds||ao(t.handles),i=n.internals.handleBounds||ao(n.handles),o=co(r?.source??[],e.sourceHandle),a=co(e.connectionMode===Kr.Strict?i?.target??[]:(i?.target??[]).concat(i?.source??[]),e.targetHandle);if(!o||!a)return e.onError?.("008",Jr.error008(o?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const s=o?.position||ti.Bottom,c=a?.position||ti.Top,u=so(t,o,s),l=so(n,a,c);return{sourceX:u.x,sourceY:u.y,targetX:l.x,targetY:l.y,sourcePosition:s,targetPosition:c}}({id:e,sourceNode:n,targetNode:r,sourceHandle:S.sourceHandle||null,targetHandle:S.targetHandle||null,connectionMode:t.connectionMode,onError:v});return{zIndex:Yi({selected:S.selected,zIndex:S.zIndex,sourceNode:n,targetNode:r,elevateOnSelect:t.elevateEdgesOnSelect}),...i||pc}}),[S.source,S.target,S.sourceHandle,S.targetHandle,S.selected,S.zIndex]),da),z=(0,s.useMemo)((()=>S.markerStart?`url('#${uo(S.markerStart,b)}')`:void 0),[S.markerStart,b]),U=(0,s.useMemo)((()=>S.markerEnd?`url('#${uo(S.markerEnd,b)}')`:void 0),[S.markerEnd,b]);if(S.hidden||null===R||null===N||null===L||null===D)return null;const q=a?e=>{a(e,{...S})}:void 0,H=c?e=>{c(e,{...S})}:void 0,J=u?e=>{u(e,{...S})}:void 0,G=l?e=>{l(e,{...S})}:void 0,V=h?e=>{h(e,{...S})}:void 0;return(0,r.jsx)("svg",{style:{zIndex:$},children:(0,r.jsxs)("g",{className:te(["react-flow__edge",`react-flow__edge-${E}`,S.className,w,{selected:S.selected,animated:S.animated,inactive:!C&&!o,updating:P,selectable:C}]),onClick:t=>{const{addSelectedEdges:n,unselectNodesAndEdges:r,multiSelectionActive:i}=j.getState();C&&(j.setState({nodesSelectionActive:!1}),S.selected&&i?(r({nodes:[],edges:[S]}),_.current?.blur()):n([e])),o&&o(t,S)},onDoubleClick:q,onContextMenu:H,onMouseEnter:J,onMouseMove:G,onMouseLeave:V,onKeyDown:M?t=>{if(!y&&Vr.includes(t.key)&&C){const{unselectNodesAndEdges:n,addSelectedEdges:r}=j.getState();"Escape"===t.key?(_.current?.blur(),n({edges:[S]})):r([e])}}:void 0,tabIndex:M?0:void 0,role:M?"button":"img","data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":null===S.ariaLabel?void 0:S.ariaLabel||`Edge from ${S.source} to ${S.target}`,"aria-describedby":M?`${ka}-${b}`:void 0,ref:_,children:[!A&&(0,r.jsx)(x,{id:e,source:S.source,target:S.target,type:S.type,selected:S.selected,animated:S.animated,selectable:C,deletable:S.deletable??!0,label:S.label,labelStyle:S.labelStyle,labelShowBg:S.labelShowBg,labelBgStyle:S.labelBgStyle,labelBgPadding:S.labelBgPadding,labelBgBorderRadius:S.labelBgBorderRadius,sourceX:R,sourceY:N,targetX:L,targetY:D,sourcePosition:F,targetPosition:B,data:S.data,style:S.style,sourceHandleId:S.sourceHandle,targetHandleId:S.targetHandle,markerStart:z,markerEnd:U,pathOptions:"pathOptions"in S?S.pathOptions:void 0,interactionWidth:S.interactionWidth}),T&&(0,r.jsx)(yc,{edge:S,isReconnectable:T,reconnectRadius:f,onReconnect:d,onReconnectStart:g,onReconnectEnd:p,sourceX:R,sourceY:N,targetX:L,targetY:D,sourcePosition:F,targetPosition:B,setUpdateHover:I,setReconnecting:O})]})})}const kc=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function Ec({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:i,noPanClassName:o,onReconnect:a,onEdgeContextMenu:c,onEdgeMouseEnter:u,onEdgeMouseMove:l,onEdgeMouseLeave:h,onEdgeClick:f,reconnectRadius:d,onEdgeDoubleClick:g,onReconnectStart:p,onReconnectEnd:b,disableKeyboardA11y:m}){const{edgesFocusable:w,edgesReconnectable:v,elementsSelectable:y,onError:S}=ma(kc,da),k=function(e){return ma((0,s.useCallback)((t=>{if(!e)return t.edges.map((e=>e.id));const n=[];if(t.width&&t.height)for(const e of t.edges){const r=t.nodeLookup.get(e.source),i=t.nodeLookup.get(e.target);r&&i&&Qi({sourceNode:r,targetNode:i,width:t.width,height:t.height,transform:t.transform})&&n.push(e.id)}return n}),[e]),da)}(t);return(0,r.jsxs)("div",{className:"react-flow__edges",children:[(0,r.jsx)(Vs,{defaultColor:e,rfId:n}),k.map((e=>(0,r.jsx)(Sc,{id:e,edgesFocusable:w,edgesReconnectable:v,elementsSelectable:y,noPanClassName:o,onReconnect:a,onContextMenu:c,onMouseEnter:u,onMouseMove:l,onMouseLeave:h,onClick:f,reconnectRadius:d,onDoubleClick:g,onReconnectStart:p,onReconnectEnd:b,rfId:n,onError:S,edgeTypes:i,disableKeyboardA11y:m},e)))]})}Ec.displayName="EdgeRenderer";const xc=(0,s.memo)(Ec),Mc=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function Tc({children:e}){const t=ma(Mc);return(0,r.jsx)("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:t},children:e})}const Cc=e=>e.panZoom?.syncViewport;function _c(e){return e.connection.inProgress?{...e.connection,to:_i(e.connection.to,e.transform)}:{...e.connection}}const Pc=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function Ic({containerStyle:e,style:t,type:n,component:i}){const{nodesConnectable:o,width:a,height:s,isValid:c,inProgress:u}=ma(Pc,da);return a&&o&&u?(0,r.jsx)("svg",{style:e,width:a,height:s,className:"react-flow__connectionline react-flow__container",children:(0,r.jsx)("g",{className:te(["react-flow__connection",ri(c)]),children:(0,r.jsx)(Ac,{style:t,type:n,CustomComponent:i,isValid:c})})}):null}const Ac=({style:e,type:t=Zr.Bezier,CustomComponent:n,isValid:i})=>{const{inProgress:o,from:a,fromNode:s,fromHandle:c,fromPosition:u,to:l,toNode:h,toHandle:f,toPosition:d}=ma(_c,da);if(!o)return;if(n)return(0,r.jsx)(n,{connectionLineType:t,connectionLineStyle:e,fromNode:s,fromHandle:c,fromX:a.x,fromY:a.y,toX:l.x,toY:l.y,fromPosition:u,toPosition:d,connectionStatus:ri(i),toNode:h,toHandle:f});let g="";const p={sourceX:a.x,sourceY:a.y,sourcePosition:u,targetX:l.x,targetY:l.y,targetPosition:d};switch(t){case Zr.Bezier:[g]=Wi(p);break;case Zr.SimpleBezier:[g]=Qs(p);break;case Zr.Step:[g]=io({...p,borderRadius:0});break;case Zr.SmoothStep:[g]=io(p);break;default:[g]=eo(p)}return(0,r.jsx)("path",{d:g,fill:"none",className:"react-flow__connection-path",style:e})};Ac.displayName="ConnectionLine";const Oc={};function jc(e=Oc){const t=(0,s.useRef)(e),n=wa();(0,s.useEffect)((()=>{if("development"===ee.env.NODE_ENV){const r=new Set([...Object.keys(t.current),...Object.keys(e)]);for(const i of r)if(t.current[i]!==e[i]){n.getState().onError?.("002",Jr.error002());break}t.current=e}}),[e])}function $c({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:i,onEdgeClick:o,onNodeDoubleClick:a,onEdgeDoubleClick:c,onNodeMouseEnter:u,onNodeMouseMove:l,onNodeMouseLeave:h,onNodeContextMenu:f,onSelectionContextMenu:d,onSelectionStart:g,onSelectionEnd:p,connectionLineType:b,connectionLineStyle:m,connectionLineComponent:w,connectionLineContainerStyle:v,selectionKeyCode:y,selectionOnDrag:S,selectionMode:k,multiSelectionKeyCode:E,panActivationKeyCode:x,zoomActivationKeyCode:M,deleteKeyCode:T,onlyRenderVisibleElements:C,elementsSelectable:_,defaultViewport:P,translateExtent:I,minZoom:A,maxZoom:O,preventScrolling:j,defaultMarkerColor:$,zoomOnScroll:R,zoomOnPinch:N,panOnScroll:L,panOnScrollSpeed:D,panOnScrollMode:F,zoomOnDoubleClick:B,panOnDrag:z,onPaneClick:U,onPaneMouseEnter:q,onPaneMouseMove:H,onPaneMouseLeave:J,onPaneScroll:G,onPaneContextMenu:V,paneClickDistance:K,nodeClickDistance:W,onEdgeContextMenu:X,onEdgeMouseEnter:Y,onEdgeMouseMove:Q,onEdgeMouseLeave:Z,reconnectRadius:te,onReconnect:ne,onReconnectStart:re,onReconnectEnd:ie,noDragClassName:oe,noWheelClassName:ae,noPanClassName:se,disableKeyboardA11y:ce,nodeExtent:ue,rfId:le,viewport:he,onViewportChange:fe}){return jc(e),jc(t),function(){const e=wa(),t=(0,s.useRef)(!1);(0,s.useEffect)((()=>{if("development"===ee.env.NODE_ENV&&!t.current){const n=document.querySelector(".react-flow__pane");n&&"1"!==window.getComputedStyle(n).zIndex&&e.getState().onError?.("013",Jr.error013("react")),t.current=!0}}),[])}(),function(e){const t=ls(),n=(0,s.useRef)(!1);(0,s.useEffect)((()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout((()=>e(t)),1),n.current=!0)}),[e,t.viewportInitialized])}(n),function(e){const t=ma(Cc),n=wa();(0,s.useEffect)((()=>{e&&(t?.(e),n.setState({transform:[e.x,e.y,e.zoom]}))}),[e,t])}(he),(0,r.jsx)(Ds,{onPaneClick:U,onPaneMouseEnter:q,onPaneMouseMove:H,onPaneMouseLeave:J,onPaneContextMenu:V,onPaneScroll:G,paneClickDistance:K,deleteKeyCode:T,selectionKeyCode:y,selectionOnDrag:S,selectionMode:k,onSelectionStart:g,onSelectionEnd:p,multiSelectionKeyCode:E,panActivationKeyCode:x,zoomActivationKeyCode:M,elementsSelectable:_,zoomOnScroll:R,zoomOnPinch:N,zoomOnDoubleClick:B,panOnScroll:L,panOnScrollSpeed:D,panOnScrollMode:F,panOnDrag:z,defaultViewport:P,translateExtent:I,minZoom:A,maxZoom:O,onSelectionContextMenu:d,preventScrolling:j,noDragClassName:oe,noWheelClassName:ae,noPanClassName:se,disableKeyboardA11y:ce,onViewportChange:fe,isControlledViewport:!!he,children:(0,r.jsxs)(Tc,{children:[(0,r.jsx)(xc,{edgeTypes:t,onEdgeClick:o,onEdgeDoubleClick:c,onReconnect:ne,onReconnectStart:re,onReconnectEnd:ie,onlyRenderVisibleElements:C,onEdgeContextMenu:X,onEdgeMouseEnter:Y,onEdgeMouseMove:Q,onEdgeMouseLeave:Z,reconnectRadius:te,defaultMarkerColor:$,noPanClassName:se,disableKeyboardA11y:ce,rfId:le}),(0,r.jsx)(Ic,{style:m,type:b,component:w,containerStyle:v}),(0,r.jsx)("div",{className:"react-flow__edgelabel-renderer"}),(0,r.jsx)(qs,{nodeTypes:e,onNodeClick:i,onNodeDoubleClick:a,onNodeMouseEnter:u,onNodeMouseMove:l,onNodeMouseLeave:h,onNodeContextMenu:f,nodeClickDistance:W,onlyRenderVisibleElements:C,noPanClassName:se,noDragClassName:oe,disableKeyboardA11y:ce,nodeExtent:ue,rfId:le}),(0,r.jsx)("div",{className:"react-flow__viewport-portal"})]})})}$c.displayName="GraphView";const Rc=(0,s.memo)($c),Nc=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:o,fitView:a,nodeOrigin:s,nodeExtent:c}={})=>{const u=new Map,l=new Map,h=new Map,f=new Map,d=r??t??[],g=n??e??[],p=s??[0,0],b=c??Gr;vo(h,f,d),go(g,u,l,{nodeOrigin:p,nodeExtent:b,elevateNodesOnSelect:!1});let m=[0,0,1];if(a&&i&&o){const e=ci(u,{filter:e=>!(!e.width&&!e.initialWidth||!e.height&&!e.initialHeight)}),{x:t,y:n,zoom:r}=Ai(e,i,o,.5,2,.1);m=[t,n,r]}return{rfId:"1",width:0,height:0,transform:m,nodes:g,nodeLookup:u,parentLookup:l,edges:d,edgeLookup:f,connectionLookup:h,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:void 0!==n,hasDefaultEdges:void 0!==r,panZoom:null,minZoom:.5,maxZoom:2,translateExtent:Gr,nodeExtent:b,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:Kr.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:p,nodeDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!1,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:a??!1,fitViewOptions:void 0,fitViewResolver:null,connection:{...Qr},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanSpeed:15,connectionRadius:20,onError:Ti,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1}},Lc=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:o,fitView:a,nodeOrigin:s,nodeExtent:c})=>((e,t)=>e?fa(e,t):fa)(((u,l)=>{async function h(){const{nodeLookup:e,panZoom:t,fitViewOptions:n,fitViewResolver:r,width:i,height:o,minZoom:a,maxZoom:s}=l();t&&(await async function({nodes:e,width:t,height:n,panZoom:r,minZoom:i,maxZoom:o},a){if(0===e.size)return Promise.resolve(!0);const s=function(e,t){const n=new Map,r=t?.nodes?new Set(t.nodes.map((e=>e.id))):null;return e.forEach((e=>{e.measured.width&&e.measured.height&&(t?.includeHiddenNodes||!e.hidden)&&(!r||r.has(e.id))&&n.set(e.id,e)})),n}(e,a),c=ci(s),u=Ai(c,t,n,a?.minZoom??i,a?.maxZoom??o,a?.padding??.1);return await r.setViewport(u,{duration:a?.duration}),Promise.resolve(!0)}({nodes:e,width:i,height:o,panZoom:t,minZoom:a,maxZoom:s},n),r?.resolve(!0),u({fitViewResolver:null}))}return{...Nc({nodes:e,edges:t,width:i,height:o,fitView:a,nodeOrigin:s,nodeExtent:c,defaultNodes:n,defaultEdges:r}),setNodes:e=>{const{nodeLookup:t,parentLookup:n,nodeOrigin:r,elevateNodesOnSelect:i,fitViewQueued:o}=l(),a=go(e,t,n,{nodeOrigin:r,nodeExtent:c,elevateNodesOnSelect:i,checkEquality:!0});o&&a?(h(),u({nodes:e,fitViewQueued:!1,fitViewOptions:void 0})):u({nodes:e})},setEdges:e=>{const{connectionLookup:t,edgeLookup:n}=l();vo(t,n,e),u({edges:e})},setDefaultNodesAndEdges:(e,t)=>{if(e){const{setNodes:t}=l();t(e),u({hasDefaultNodes:!0})}if(t){const{setEdges:e}=l();e(t),u({hasDefaultEdges:!0})}},updateNodeInternals:e=>{const{triggerNodeChanges:t,nodeLookup:n,parentLookup:r,domNode:i,nodeOrigin:o,nodeExtent:a,debug:s,fitViewQueued:c}=l(),{changes:f,updatedInternals:d}=function(e,t,n,r,i,o){const a=r?.querySelector(".xyflow__viewport");let s=!1;if(!a)return{changes:[],updatedInternals:s};const c=[],u=window.getComputedStyle(a),{m22:l}=new window.DOMMatrixReadOnly(u.transform),h=[];for(const r of e.values()){const e=t.get(r.id);if(!e)continue;if(e.hidden){t.set(e.id,{...e,internals:{...e.internals,handleBounds:void 0}}),s=!0;continue}const a=Fi(r.nodeElement),u=e.measured.width!==a.width||e.measured.height!==a.height;if(a.width&&a.height&&(u||!e.internals.handleBounds||r.force)){const f=r.nodeElement.getBoundingClientRect(),d=ji(e.extent)?e.extent:o;let{positionAbsolute:g}=e.internals;e.parentId&&"parent"===e.extent?g=gi(g,a,t.get(e.parentId)):d&&(g=di(g,d,a));const p={...e,measured:a,internals:{...e.internals,positionAbsolute:g,handleBounds:{source:Ji("source",r.nodeElement,f,l,e.id),target:Ji("target",r.nodeElement,f,l,e.id)}}};t.set(e.id,p),e.parentId&&po(p,t,n,{nodeOrigin:i}),s=!0,u&&(c.push({id:e.id,type:"dimensions",dimensions:a}),e.expandParent&&e.parentId&&h.push({id:e.id,parentId:e.parentId,rect:yi(p,i)}))}}if(h.length>0){const e=mo(h,t,n,i);c.push(...e)}return{changes:c,updatedInternals:s}}(e,n,r,i,o,a);d&&(function(e,t,n){const r=fo(lo,n);for(const n of e.values())if(n.parentId)po(n,e,t,r);else{const e=ai(n,r.nodeOrigin),t=ji(n.extent)?n.extent:r.nodeExtent,i=di(e,t,$i(n));n.internals.positionAbsolute=i}}(n,r,{nodeOrigin:o,nodeExtent:a}),c?(h(),u({fitViewQueued:!1,fitViewOptions:void 0})):u({}),f?.length>0&&(s&&console.log("React Flow: trigger node changes",f),t?.(f)))},updateNodePositions:(e,t=!1)=>{const n=[],r=[],{nodeLookup:i,triggerNodeChanges:o}=l();for(const[o,a]of e){const e=i.get(o),s=!!(e?.expandParent&&e?.parentId&&a?.position),c={id:o,type:"position",position:s?{x:Math.max(0,a.position.x),y:Math.max(0,a.position.y)}:a.position,dragging:t};s&&e.parentId&&n.push({id:o,parentId:e.parentId,rect:{...a.internals.positionAbsolute,width:a.measured.width??0,height:a.measured.height??0}}),r.push(c)}if(n.length>0){const{parentLookup:e,nodeOrigin:t}=l(),o=mo(n,i,e,t);r.push(...o)}o(r)},triggerNodeChanges:e=>{const{onNodesChange:t,setNodes:n,nodes:r,hasDefaultNodes:i,debug:o}=l();e?.length&&(i&&n(Xa(e,r)),o&&console.log("React Flow: trigger node changes",e),t?.(e))},triggerEdgeChanges:e=>{const{onEdgesChange:t,setEdges:n,edges:r,hasDefaultEdges:i,debug:o}=l();e?.length&&(i&&n(Ya(e,r)),o&&console.log("React Flow: trigger edge changes",e),t?.(e))},addSelectedNodes:e=>{const{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:o}=l();t?i(e.map((e=>Qa(e,!0)))):(i(Za(r,new Set([...e]),!0)),o(Za(n)))},addSelectedEdges:e=>{const{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:o}=l();t?o(e.map((e=>Qa(e,!0)))):(o(Za(n,new Set([...e]))),i(Za(r,new Set,!0)))},unselectNodesAndEdges:({nodes:e,edges:t}={})=>{const{edges:n,nodes:r,nodeLookup:i,triggerNodeChanges:o,triggerEdgeChanges:a}=l(),s=t||n,c=(e||r).map((e=>{const t=i.get(e.id);return t&&(t.selected=!1),Qa(e.id,!1)})),u=s.map((e=>Qa(e.id,!1)));o(c),a(u)},setMinZoom:e=>{const{panZoom:t,maxZoom:n}=l();t?.setScaleExtent([e,n]),u({minZoom:e})},setMaxZoom:e=>{const{panZoom:t,minZoom:n}=l();t?.setScaleExtent([n,e]),u({maxZoom:e})},setTranslateExtent:e=>{l().panZoom?.setTranslateExtent(e),u({translateExtent:e})},setPaneClickDistance:e=>{l().panZoom?.setClickDistance(e)},resetSelectedElements:()=>{const{edges:e,nodes:t,triggerNodeChanges:n,triggerEdgeChanges:r}=l(),i=t.reduce(((e,t)=>t.selected?[...e,Qa(t.id,!1)]:e),[]),o=e.reduce(((e,t)=>t.selected?[...e,Qa(t.id,!1)]:e),[]);n(i),r(o)},setNodeExtent:e=>{const{nodes:t,nodeLookup:n,parentLookup:r,nodeOrigin:i,elevateNodesOnSelect:o,nodeExtent:a}=l();e[0][0]===a[0][0]&&e[0][1]===a[0][1]&&e[1][0]===a[1][0]&&e[1][1]===a[1][1]||(go(t,n,r,{nodeOrigin:i,nodeExtent:e,elevateNodesOnSelect:o,checkEquality:!1}),u({nodeExtent:e}))},panBy:e=>{const{transform:t,width:n,height:r,panZoom:i,translateExtent:o}=l();return async function({delta:e,panZoom:t,transform:n,translateExtent:r,width:i,height:o}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const a=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[i,o]],r),s=!!a&&(a.x!==n[0]||a.y!==n[1]||a.k!==n[2]);return Promise.resolve(s)}({delta:e,panZoom:i,transform:t,translateExtent:o,width:n,height:r})},cancelConnection:()=>{u({connection:{...Qr}})},updateConnection:e=>{u({connection:e})},reset:()=>u({...Nc()})}}),Object.is);function Dc({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:i,initialWidth:o,initialHeight:a,fitView:c,nodeOrigin:u,nodeExtent:l,children:h}){const[f]=(0,s.useState)((()=>Lc({nodes:e,edges:t,defaultNodes:n,defaultEdges:i,width:o,height:a,fitView:c,nodeOrigin:u,nodeExtent:l})));return(0,r.jsx)(pa,{value:f,children:(0,r.jsx)(cs,{children:h})})}function Fc({children:e,nodes:t,edges:n,defaultNodes:i,defaultEdges:o,width:a,height:c,fitView:u,nodeOrigin:l,nodeExtent:h}){return(0,s.useContext)(ga)?(0,r.jsx)(r.Fragment,{children:e}):(0,r.jsx)(Dc,{initialNodes:t,initialEdges:n,defaultNodes:i,defaultEdges:o,initialWidth:a,initialHeight:c,fitView:u,nodeOrigin:l,nodeExtent:h,children:e})}const Bc={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};var zc=is((function({nodes:e,edges:t,defaultNodes:n,defaultEdges:i,className:o,nodeTypes:a,edgeTypes:c,onNodeClick:u,onEdgeClick:l,onInit:h,onMove:f,onMoveStart:d,onMoveEnd:g,onConnect:p,onConnectStart:b,onConnectEnd:m,onClickConnectStart:w,onClickConnectEnd:v,onNodeMouseEnter:y,onNodeMouseMove:S,onNodeMouseLeave:k,onNodeContextMenu:E,onNodeDoubleClick:x,onNodeDragStart:M,onNodeDrag:T,onNodeDragStop:C,onNodesDelete:_,onEdgesDelete:P,onDelete:I,onSelectionChange:A,onSelectionDragStart:O,onSelectionDrag:j,onSelectionDragStop:$,onSelectionContextMenu:R,onSelectionStart:N,onSelectionEnd:L,onBeforeDelete:D,connectionMode:F,connectionLineType:B=Zr.Bezier,connectionLineStyle:z,connectionLineComponent:U,connectionLineContainerStyle:q,deleteKeyCode:H="Backspace",selectionKeyCode:J="Shift",selectionOnDrag:G=!1,selectionMode:V=Yr.Full,panActivationKeyCode:K="Space",multiSelectionKeyCode:W=(Oi()?"Meta":"Control"),zoomActivationKeyCode:X=(Oi()?"Meta":"Control"),snapToGrid:Y,snapGrid:Q,onlyRenderVisibleElements:Z=!1,selectNodesOnDrag:ee,nodesDraggable:ne,nodesConnectable:re,nodesFocusable:ie,nodeOrigin:oe=Na,edgesFocusable:ae,edgesReconnectable:se,elementsSelectable:ce=!0,defaultViewport:ue=La,minZoom:le=.5,maxZoom:he=2,translateExtent:fe=Gr,preventScrolling:de=!0,nodeExtent:ge,defaultMarkerColor:pe="#b1b1b7",zoomOnScroll:be=!0,zoomOnPinch:me=!0,panOnScroll:we=!1,panOnScrollSpeed:ve=.5,panOnScrollMode:ye=Xr.Free,zoomOnDoubleClick:Se=!0,panOnDrag:ke=!0,onPaneClick:Ee,onPaneMouseEnter:xe,onPaneMouseMove:Me,onPaneMouseLeave:Te,onPaneScroll:Ce,onPaneContextMenu:_e,paneClickDistance:Pe=0,nodeClickDistance:Ie=0,children:Ae,onReconnect:Oe,onReconnectStart:je,onReconnectEnd:$e,onEdgeContextMenu:Re,onEdgeDoubleClick:Ne,onEdgeMouseEnter:Le,onEdgeMouseMove:De,onEdgeMouseLeave:Fe,reconnectRadius:Be=10,onNodesChange:ze,onEdgesChange:Ue,noDragClassName:qe="nodrag",noWheelClassName:He="nowheel",noPanClassName:Je="nopan",fitView:Ge,fitViewOptions:Ve,connectOnClick:Ke,attributionPosition:We,proOptions:Xe,defaultEdgeOptions:Ye,elevateNodesOnSelect:Qe,elevateEdgesOnSelect:Ze,disableKeyboardA11y:et=!1,autoPanOnConnect:tt,autoPanOnNodeDrag:nt,autoPanSpeed:rt,connectionRadius:it,isValidConnection:ot,onError:at,style:st,id:ct,nodeDragThreshold:ut,viewport:lt,onViewportChange:ht,width:ft,height:dt,colorMode:gt="light",debug:pt,onScroll:bt,...mt},wt){const vt=ct||"1",yt=function(e){const[t,n]=(0,s.useState)("system"===e?null:e);return(0,s.useEffect)((()=>{if("system"!==e)return void n(e);const t=Ua(),r=()=>n(t?.matches?"dark":"light");return r(),t?.addEventListener("change",r),()=>{t?.removeEventListener("change",r)}}),[e]),null!==t?t:Ua()?.matches?"dark":"light"}(gt),St=(0,s.useCallback)((e=>{e.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),bt?.(e)}),[bt]);return(0,r.jsx)("div",{"data-testid":"rf__wrapper",...mt,onScroll:St,style:{...st,...Bc},ref:wt,className:te(["react-flow",o,yt]),id:ct,children:(0,r.jsxs)(Fc,{nodes:e,edges:t,width:ft,height:dt,fitView:Ge,nodeOrigin:oe,nodeExtent:ge,children:[(0,r.jsx)(Rc,{onInit:h,onNodeClick:u,onEdgeClick:l,onNodeMouseEnter:y,onNodeMouseMove:S,onNodeMouseLeave:k,onNodeContextMenu:E,onNodeDoubleClick:x,nodeTypes:a,edgeTypes:c,connectionLineType:B,connectionLineStyle:z,connectionLineComponent:U,connectionLineContainerStyle:q,selectionKeyCode:J,selectionOnDrag:G,selectionMode:V,deleteKeyCode:H,multiSelectionKeyCode:W,panActivationKeyCode:K,zoomActivationKeyCode:X,onlyRenderVisibleElements:Z,defaultViewport:ue,translateExtent:fe,minZoom:le,maxZoom:he,preventScrolling:de,zoomOnScroll:be,zoomOnPinch:me,zoomOnDoubleClick:Se,panOnScroll:we,panOnScrollSpeed:ve,panOnScrollMode:ye,panOnDrag:ke,onPaneClick:Ee,onPaneMouseEnter:xe,onPaneMouseMove:Me,onPaneMouseLeave:Te,onPaneScroll:Ce,onPaneContextMenu:_e,paneClickDistance:Pe,nodeClickDistance:Ie,onSelectionContextMenu:R,onSelectionStart:N,onSelectionEnd:L,onReconnect:Oe,onReconnectStart:je,onReconnectEnd:$e,onEdgeContextMenu:Re,onEdgeDoubleClick:Ne,onEdgeMouseEnter:Le,onEdgeMouseMove:De,onEdgeMouseLeave:Fe,reconnectRadius:Be,defaultMarkerColor:pe,noDragClassName:qe,noWheelClassName:He,noPanClassName:Je,rfId:vt,disableKeyboardA11y:et,nodeExtent:ge,viewport:lt,onViewportChange:ht}),(0,r.jsx)(za,{nodes:e,edges:t,defaultNodes:n,defaultEdges:i,onConnect:p,onConnectStart:b,onConnectEnd:m,onClickConnectStart:w,onClickConnectEnd:v,nodesDraggable:ne,nodesConnectable:re,nodesFocusable:ie,edgesFocusable:ae,edgesReconnectable:se,elementsSelectable:ce,elevateNodesOnSelect:Qe,elevateEdgesOnSelect:Ze,minZoom:le,maxZoom:he,nodeExtent:ge,onNodesChange:ze,onEdgesChange:Ue,snapToGrid:Y,snapGrid:Q,connectionMode:F,translateExtent:fe,connectOnClick:Ke,defaultEdgeOptions:Ye,fitView:Ge,fitViewOptions:Ve,onNodesDelete:_,onEdgesDelete:P,onDelete:I,onNodeDragStart:M,onNodeDrag:T,onNodeDragStop:C,onSelectionDrag:j,onSelectionDragStart:O,onSelectionDragStop:$,onMove:f,onMoveStart:d,onMoveEnd:g,noPanClassName:Je,nodeOrigin:oe,rfId:vt,autoPanOnConnect:tt,autoPanOnNodeDrag:nt,autoPanSpeed:rt,onError:at,connectionRadius:it,isValidConnection:ot,selectNodesOnDrag:ee,nodeDragThreshold:ut,onBeforeDelete:D,paneClickDistance:Pe,debug:pt}),(0,r.jsx)(Ra,{onSelectionChange:A}),Ae,(0,r.jsx)(Pa,{proOptions:Xe,position:We}),(0,r.jsx)(Ta,{rfId:vt,disableKeyboardA11y:et})]})})}));const Uc=e=>e.nodes;function qc(){return ma(Uc,da)}const Hc=e=>({x:e.transform[0],y:e.transform[1],zoom:e.transform[2]});function Jc(){return ma(Hc,da)}function Gc({dimensions:e,lineWidth:t,variant:n,className:i}){return(0,r.jsx)("path",{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:te(["react-flow__background-pattern",n,i])})}function Vc({radius:e,className:t}){return(0,r.jsx)("circle",{cx:e,cy:e,r:e,className:te(["react-flow__background-pattern","dots",t])})}var Kc;!function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"}(Kc||(Kc={}));const Wc={[Kc.Dots]:1,[Kc.Lines]:1,[Kc.Cross]:6},Xc=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Yc({id:e,variant:t=Kc.Dots,gap:n=20,size:i,lineWidth:o=1,offset:a=0,color:c,bgColor:u,style:l,className:h,patternClassName:f}){const d=(0,s.useRef)(null),{transform:g,patternId:p}=ma(Xc,da),b=i||Wc[t],m=t===Kc.Dots,w=t===Kc.Cross,v=Array.isArray(n)?n:[n,n],y=[v[0]*g[2]||1,v[1]*g[2]||1],S=b*g[2],k=Array.isArray(a)?a:[a,a],E=w?[S,S]:y,x=[k[0]*g[2]||1+E[0]/2,k[1]*g[2]||1+E[1]/2],M=`${p}${e||""}`;return(0,r.jsxs)("svg",{className:te(["react-flow__background",h]),style:{...l,...gs,"--xy-background-color-props":u,"--xy-background-pattern-color-props":c},ref:d,"data-testid":"rf__background",children:[(0,r.jsx)("pattern",{id:M,x:g[0]%y[0],y:g[1]%y[1],width:y[0],height:y[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${x[0]},-${x[1]})`,children:m?(0,r.jsx)(Vc,{radius:S/2,className:f}):(0,r.jsx)(Gc,{dimensions:E,lineWidth:o,variant:t,className:f})}),(0,r.jsx)("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${M})`})]})}Yc.displayName="Background";const Qc=(0,s.memo)(Yc);function Zc(){return(0,r.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:(0,r.jsx)("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function eu(){return(0,r.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:(0,r.jsx)("path",{d:"M0 0h32v4.2H0z"})})}function tu(){return(0,r.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:(0,r.jsx)("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"})})}function nu(){return(0,r.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:(0,r.jsx)("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"})})}function ru(){return(0,r.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:(0,r.jsx)("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"})})}function iu({children:e,className:t,...n}){return(0,r.jsx)("button",{type:"button",className:te(["react-flow__controls-button",t]),...n,children:e})}const ou=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom});function au({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:i=!0,fitViewOptions:o,onZoomIn:a,onZoomOut:s,onFitView:c,onInteractiveChange:u,className:l,children:h,position:f="bottom-left",orientation:d="vertical","aria-label":g="React Flow controls"}){const p=wa(),{isInteractive:b,minZoomReached:m,maxZoomReached:w}=ma(ou,da),{zoomIn:v,zoomOut:y,fitView:S}=ls();return(0,r.jsxs)(_a,{className:te(["react-flow__controls","horizontal"===d?"horizontal":"vertical",l]),position:f,style:e,"data-testid":"rf__controls","aria-label":g,children:[t&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(iu,{onClick:()=>{v(),a?.()},className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:w,children:(0,r.jsx)(Zc,{})}),(0,r.jsx)(iu,{onClick:()=>{y(),s?.()},className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:m,children:(0,r.jsx)(eu,{})})]}),n&&(0,r.jsx)(iu,{className:"react-flow__controls-fitview",onClick:()=>{S(o),c?.()},title:"fit view","aria-label":"fit view",children:(0,r.jsx)(tu,{})}),i&&(0,r.jsx)(iu,{className:"react-flow__controls-interactive",onClick:()=>{p.setState({nodesDraggable:!b,nodesConnectable:!b,elementsSelectable:!b}),u?.(!b)},title:"toggle interactivity","aria-label":"toggle interactivity",children:b?(0,r.jsx)(ru,{}):(0,r.jsx)(nu,{})}),h]})}au.displayName="Controls";const su=(0,s.memo)(au),cu=(0,s.memo)((function({id:e,x:t,y:n,width:i,height:o,style:a,color:s,strokeColor:c,strokeWidth:u,className:l,borderRadius:h,shapeRendering:f,selected:d,onClick:g}){const{background:p,backgroundColor:b}=a||{},m=s||p||b;return(0,r.jsx)("rect",{className:te(["react-flow__minimap-node",{selected:d},l]),x:t,y:n,rx:h,ry:h,width:i,height:o,style:{fill:m,stroke:c,strokeWidth:u},shapeRendering:f,onClick:g?t=>g(t,e):void 0})})),uu=e=>e.nodes.map((e=>e.id)),lu=e=>e instanceof Function?e:()=>e,hu=(0,s.memo)((function({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:i,nodeBorderRadius:o,nodeStrokeWidth:a,shapeRendering:s,NodeComponent:c,onClick:u}){const{node:l,x:h,y:f,width:d,height:g}=ma((t=>{const n=t.nodeLookup.get(e),{x:r,y:i}=n.internals.positionAbsolute,{width:o,height:a}=$i(n);return{node:n,x:r,y:i,width:o,height:a}}),da);return l&&!l.hidden&&Ri(l)?(0,r.jsx)(c,{x:h,y:f,width:d,height:g,style:l.style,selected:!!l.selected,className:i(l),color:t(l),borderRadius:o,strokeColor:n(l),strokeWidth:a,shapeRendering:s,onClick:u,id:l.id}):null}));var fu=(0,s.memo)((function({nodeStrokeColor:e,nodeColor:t,nodeClassName:n="",nodeBorderRadius:i=5,nodeStrokeWidth:o,nodeComponent:a=cu,onClick:s}){const c=ma(uu,da),u=lu(t),l=lu(e),h=lu(n),f=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return(0,r.jsx)(r.Fragment,{children:c.map((e=>(0,r.jsx)(hu,{id:e,nodeColorFunc:u,nodeStrokeColorFunc:l,nodeClassNameFunc:h,nodeBorderRadius:i,nodeStrokeWidth:o,NodeComponent:a,onClick:s,shapeRendering:f},e)))})}));const du=e=>!e.hidden,gu=e=>{const t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};return{viewBB:t,boundingRect:e.nodeLookup.size>0?ki(ci(e.nodeLookup,{filter:du}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height}};function pu({style:e,className:t,nodeStrokeColor:n,nodeColor:i,nodeClassName:o="",nodeBorderRadius:a=5,nodeStrokeWidth:c,nodeComponent:u,bgColor:l,maskColor:h,maskStrokeColor:f,maskStrokeWidth:d,position:g="bottom-right",onClick:p,onNodeClick:b,pannable:m=!1,zoomable:w=!1,ariaLabel:v="React Flow mini map",inversePan:y,zoomStep:S=10,offsetScale:k=5}){const E=wa(),x=(0,s.useRef)(null),{boundingRect:M,viewBB:T,rfId:C,panZoom:_,translateExtent:P,flowWidth:I,flowHeight:A}=ma(gu,da),O=e?.width??200,j=e?.height??150,$=M.width/O,R=M.height/j,N=Math.max($,R),L=N*O,D=N*j,F=k*N,B=M.x-(L-M.width)/2-F,z=M.y-(D-M.height)/2-F,U=L+2*F,q=D+2*F,H=`react-flow__minimap-desc-${C}`,J=(0,s.useRef)(0),G=(0,s.useRef)();J.current=N,(0,s.useEffect)((()=>{if(x.current&&_)return G.current=function({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const i=wt(e);return{update:function({translateExtent:e,width:o,height:a,zoomStep:s=10,pannable:c=!0,zoomable:u=!0,inversePan:l=!1}){let h=[0,0];const f=Hr().on("start",(e=>{("mousedown"===e.sourceEvent.type||"touchstart"===e.sourceEvent.type)&&(h=[e.sourceEvent.clientX??e.sourceEvent.touches[0].clientX,e.sourceEvent.clientY??e.sourceEvent.touches[0].clientY])})).on("zoom",c?i=>{const s=n();if("mousemove"!==i.sourceEvent.type&&"touchmove"!==i.sourceEvent.type||!t)return;const c=[i.sourceEvent.clientX??i.sourceEvent.touches[0].clientX,i.sourceEvent.clientY??i.sourceEvent.touches[0].clientY],u=[c[0]-h[0],c[1]-h[1]];h=c;const f=r()*Math.max(s[2],Math.log(s[2]))*(l?-1:1),d={x:s[0]-u[0]*f,y:s[1]-u[1]*f},g=[[0,0],[o,a]];t.setViewportConstrained({x:d.x,y:d.y,zoom:s[2]},g,e)}:null).on("zoom.wheel",u?e=>{const r=n();if("wheel"!==e.sourceEvent.type||!t)return;const i=-e.sourceEvent.deltaY*(1===e.sourceEvent.deltaMode?.05:e.sourceEvent.deltaMode?1:.002)*s,o=r[2]*Math.pow(2,i);t.scaleTo(o)}:null);i.call(f,{})},destroy:function(){i.on("zoom",null)},pointer:vt}}({domNode:x.current,panZoom:_,getTransform:()=>E.getState().transform,getViewScale:()=>J.current}),()=>{G.current?.destroy()}}),[_]),(0,s.useEffect)((()=>{G.current?.update({translateExtent:P,width:I,height:A,inversePan:y,pannable:m,zoomStep:S,zoomable:w})}),[m,w,y,S,P,I,A]);const V=p?e=>{const[t,n]=G.current?.pointer(e)||[0,0];p(e,{x:t,y:n})}:void 0,K=b?(0,s.useCallback)(((e,t)=>{const n=E.getState().nodeLookup.get(t);b(e,n)}),[]):void 0;return(0,r.jsx)(_a,{position:g,style:{...e,"--xy-minimap-background-color-props":"string"==typeof l?l:void 0,"--xy-minimap-mask-background-color-props":"string"==typeof h?h:void 0,"--xy-minimap-mask-stroke-color-props":"string"==typeof f?f:void 0,"--xy-minimap-mask-stroke-width-props":"number"==typeof d?d*N:void 0,"--xy-minimap-node-background-color-props":"string"==typeof i?i:void 0,"--xy-minimap-node-stroke-color-props":"string"==typeof n?n:void 0,"--xy-minimap-node-stroke-width-props":"string"==typeof c?c:void 0},className:te(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:(0,r.jsxs)("svg",{width:O,height:j,viewBox:`${B} ${z} ${U} ${q}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":H,ref:x,onClick:V,children:[v&&(0,r.jsx)("title",{id:H,children:v}),(0,r.jsx)(fu,{onClick:K,nodeColor:i,nodeStrokeColor:n,nodeBorderRadius:a,nodeClassName:o,nodeStrokeWidth:c,nodeComponent:u}),(0,r.jsx)("path",{className:"react-flow__minimap-mask",d:`M${B-F},${z-F}h${U+2*F}v${q+2*F}h${-U-2*F}z\n M${T.x},${T.y}h${T.width}v${T.height}h${-T.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}pu.displayName="MiniMap";const bu=(0,s.memo)(pu);(0,s.memo)((function({nodeId:e,position:t,variant:n=Ro.Handle,className:i,style:o={},children:a,color:c,minWidth:u=10,minHeight:l=10,maxWidth:h=Number.MAX_VALUE,maxHeight:f=Number.MAX_VALUE,keepAspectRatio:d=!1,shouldResize:g,onResizeStart:p,onResize:b,onResizeEnd:m}){const w=_s(),v="string"==typeof e?e:w,y=wa(),S=(0,s.useRef)(null),k=n===Ro.Line?"right":"bottom-right",E=t??k,x=(0,s.useRef)(null);(0,s.useEffect)((()=>{if(S.current&&v)return x.current||(x.current=function({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:i}){const o=wt(e);return{update:function({controlPosition:e,boundaries:a,keepAspectRatio:s,onResizeStart:c,onResize:u,onResizeEnd:l,shouldResize:h}){let f={...Bo},d={...zo};const g=function(e){return{isHorizontal:e.includes("right")||e.includes("left"),isVertical:e.includes("bottom")||e.includes("top"),affectsX:e.includes("left"),affectsY:e.includes("top")}}(e);let p,b,m,w,v=null,y=[];const S=Ot().on("start",(e=>{const{nodeLookup:r,transform:i,snapGrid:o,snapToGrid:a,nodeOrigin:s,paneDomNode:u}=n();if(p=r.get(t),!p)return;v=u?.getBoundingClientRect()??null;const{xSnapped:l,ySnapped:h}=Di(e.sourceEvent,{transform:i,snapGrid:o,snapToGrid:a,containerBounds:v});f={width:p.measured.width??0,height:p.measured.height??0,x:p.position.x??0,y:p.position.y??0},d={...f,pointerX:l,pointerY:h,aspectRatio:f.width/f.height},b=void 0,p.parentId&&("parent"===p.extent||p.expandParent)&&(b=r.get(p.parentId),m=b&&"parent"===p.extent?function(e){return[[0,0],[e.measured.width,e.measured.height]]}(b):void 0),y=[],w=void 0;for(const[e,n]of r)if(n.parentId===t&&(y.push({id:e,position:{...n.position},extent:n.extent}),"parent"===n.extent||n.expandParent)){const e=Uo(n,p,n.origin??s);w=w?[[Math.min(e[0][0],w[0][0]),Math.min(e[0][1],w[0][1])],[Math.max(e[1][0],w[1][0]),Math.max(e[1][1],w[1][1])]]:e}c?.(e,{...f})})).on("drag",(e=>{const{transform:t,snapGrid:i,snapToGrid:o,nodeOrigin:c}=n(),l=Di(e.sourceEvent,{transform:t,snapGrid:i,snapToGrid:o,containerBounds:v}),S=[];if(!p)return;const{x:k,y:E,width:x,height:M}=f,T={},C=p.origin??c,{width:_,height:P,x:I,y:A}=function(e,t,n,r,i,o,a,s){let{affectsX:c,affectsY:u}=t;const{isHorizontal:l,isVertical:h}=t,f=l&&h,{xSnapped:d,ySnapped:g}=n,{minWidth:p,maxWidth:b,minHeight:m,maxHeight:w}=r,{x:v,y,width:S,height:k,aspectRatio:E}=e;let x=Math.floor(l?d-e.pointerX:0),M=Math.floor(h?g-e.pointerY:0);const T=S+(c?-x:x),C=k+(u?-M:M),_=-o[0]*S,P=-o[1]*k;let I=Do(T,p,b),A=Do(C,m,w);if(a){let e=0,t=0;c&&x<0?e=No(v+x+_,a[0][0]):!c&&x>0&&(e=Lo(v+T+_,a[1][0])),u&&M<0?t=No(y+M+P,a[0][1]):!u&&M>0&&(t=Lo(y+C+P,a[1][1])),I=Math.max(I,e),A=Math.max(A,t)}if(s){let e=0,t=0;c&&x>0?e=Lo(v+x,s[0][0]):!c&&x<0&&(e=No(v+T,s[1][0])),u&&M>0?t=Lo(y+M,s[0][1]):!u&&M<0&&(t=No(y+C,s[1][1])),I=Math.max(I,e),A=Math.max(A,t)}if(i){if(l){const e=Do(T/E,m,w)*E;if(I=Math.max(I,e),a){let e=0;e=!c&&!u||c&&!u&&f?Lo(y+P+T/E,a[1][1])*E:No(y+P+(c?x:-x)/E,a[0][1])*E,I=Math.max(I,e)}if(s){let e=0;e=!c&&!u||c&&!u&&f?No(y+T/E,s[1][1])*E:Lo(y+(c?x:-x)/E,s[0][1])*E,I=Math.max(I,e)}}if(h){const e=Do(C*E,p,b)/E;if(A=Math.max(A,e),a){let e=0;e=!c&&!u||u&&!c&&f?Lo(v+C*E+_,a[1][0])/E:No(v+(u?M:-M)*E+_,a[0][0])/E,A=Math.max(A,e)}if(s){let e=0;e=!c&&!u||u&&!c&&f?No(v+C*E,s[1][0])/E:Lo(v+(u?M:-M)*E,s[0][0])/E,A=Math.max(A,e)}}}M+=M<0?A:-A,x+=x<0?I:-I,i&&(f?T>C*E?M=(Fo(c,u)?-x:x)/E:x=(Fo(c,u)?-M:M)*E:l?(M=x/E,u=c):(x=M*E,c=u));const O=c?v+x:v,j=u?y+M:y;return{width:S+(c?-x:x),height:k+(u?-M:M),x:o[0]*x*(c?-1:1)+O,y:o[1]*M*(u?-1:1)+j}}(d,g,l,a,s,C,m,w),O=_!==x,j=P!==M,$=I!==k&&O,R=A!==E&&j;if(!($||R||O||j))return;if(($||R||1===C[0]||1===C[1])&&(T.x=$?I:f.x,T.y=R?A:f.y,f.x=T.x,f.y=T.y,y.length>0)){const e=I-k,t=A-E;for(const n of y)n.position={x:n.position.x-e+C[0]*(_-x),y:n.position.y-t+C[1]*(P-M)},S.push(n)}if((O||j)&&(T.width=O?_:f.width,T.height=j?P:f.height,f.width=T.width,f.height=T.height),b&&p.expandParent){const e=C[0]*(T.width??0);T.x&&T.x<e&&(f.x=e,d.x=d.x-(T.x-e));const t=C[1]*(T.height??0);T.y&&T.y<t&&(f.y=t,d.y=d.y-(T.y-t))}const N=function({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:i,affectsY:o}){const a=e-t,s=n-r,c=[a>0?1:a<0?-1:0,s>0?1:s<0?-1:0];return a&&i&&(c[0]=-1*c[0]),s&&o&&(c[1]=-1*c[1]),c}({width:f.width,prevWidth:x,height:f.height,prevHeight:M,affectsX:g.affectsX,affectsY:g.affectsY}),L={...f,direction:N};!1!==h?.(e,L)&&(u?.(e,L),r(T,S))})).on("end",(e=>{l?.(e,{...f}),i?.()}));o.call(S)},destroy:function(){o.on(".drag",null)}}}({domNode:S.current,nodeId:v,getStoreItems:()=>{const{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,domNode:o}=y.getState();return{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,paneDomNode:o}},onChange:(e,t)=>{const{triggerNodeChanges:n,nodeLookup:r,parentLookup:i,nodeOrigin:o}=y.getState(),a=[],s={x:e.x,y:e.y},c=r.get(v);if(c&&c.expandParent&&c.parentId){const t=c.origin??o,n=e.width??c.measured.width??0,u=e.height??c.measured.height??0,l=mo([{id:c.id,parentId:c.parentId,rect:{width:n,height:u,...Ni({x:e.x??c.position.x,y:e.y??c.position.y},{width:n,height:u},c.parentId,r,t)}}],r,i,o);a.push(...l),s.x=e.x?Math.max(t[0]*n,e.x):void 0,s.y=e.y?Math.max(t[1]*u,e.y):void 0}if(void 0!==s.x&&void 0!==s.y){const e={id:v,type:"position",position:{...s}};a.push(e)}if(void 0!==e.width&&void 0!==e.height){const t={id:v,type:"dimensions",resizing:!0,setAttributes:!0,dimensions:{width:e.width,height:e.height}};a.push(t)}for(const e of t){const t={...e,type:"position"};a.push(t)}n(a)},onEnd:()=>{const e={id:v,type:"dimensions",resizing:!1};y.getState().triggerNodeChanges([e])}})),x.current.update({controlPosition:E,boundaries:{minWidth:u,minHeight:l,maxWidth:h,maxHeight:f},keepAspectRatio:d,onResizeStart:p,onResize:b,onResizeEnd:m,shouldResize:g}),()=>{x.current?.destroy()}}),[E,u,l,h,f,d,p,b,m,g]);const M=E.split("-"),T=n===Ro.Line?"borderColor":"backgroundColor",C=c?{...o,[T]:c}:o;return(0,r.jsx)("div",{className:te(["react-flow__resize-control","nodrag",...M,n,i]),ref:S,style:C,children:a})}));const mu=()=>{const e=(0,o.u)();return(0,r.jsx)(bu,{maskColor:e.minimap.mask,nodeColor:e.minimap.node,style:{width:200,height:100,background:e.minimap.selectionArea}})},wu=e=>{const{data:t,...n}=e;return{...n,...t,fields:t.fields.map((({isVisible:e,hasChildren:t,...n})=>n)),type:e.type}},vu=e=>e.map((e=>wu(e)));function yu(e,t,n){const r=e.depth??0,i=n.length>t+1?n[t+1]:null;return!!i&&void 0!==i.depth&&i.depth>r}function Su(e){let t=!1,n=1;return e.map(((r,i)=>{const o=r.depth??0,a=o<=n,s=!t||a;return a&&(n=o,t=!1===r.expanded),{...r,hasChildren:yu(r,i,e),isVisible:s}}))}const ku=e=>e.map((e=>(e=>{const{title:t,fields:n,borderVariant:r,disabled:i,connectable:o,variant:a,...s}=e;return{...s,connectable:o??!1,data:{title:t,disabled:i,fields:Su(n),borderVariant:r,variant:a}}})(e))),Eu=e=>{const{markerStart:t,markerEnd:n,type:r,data:i,...o}=e;return{...o,markerStart:t?.replace(/^start-/,""),markerEnd:n?.replace(/^end-/,""),...void 0!==i?.sourceFieldId?{sourceFieldId:i?.sourceFieldId}:{},...void 0!==i?.targetFieldId?{targetFieldId:i?.targetFieldId}:{}}},xu=e=>e.map((e=>Eu(e))),Mu=e=>e.map((e=>(e=>{const{sourceFieldId:t,targetFieldId:n,...r}=e;return{...r,markerStart:`start-${e.markerStart}`,markerEnd:`end-${e.markerEnd}`,type:e.source===e.target?"selfReferencingEdge":void 0!==t&&void 0!==n?"fieldEdge":"floatingEdge",data:{...void 0!==t?{sourceFieldId:t}:{},...void 0!==n?{targetFieldId:n}:{}}}})(e)));function Tu(){const e=ls();return{...e,getNode:t=>{const n=e.getNode(t);if(n)return wu(n)},getNodes:()=>{const t=e.getNodes();return vu(t)},addNodes:t=>{const n=ku(t);e.addNodes(n)},setNodes:t=>{const n=ku(t);e.setNodes(n)},getEdge:t=>{const n=e.getEdge(t);if(n)return Eu(n)},getEdges:()=>e.getEdges().map(Eu),addEdges:t=>{const n=Mu(t);e.addEdges(n)},setEdges:t=>{const n=Mu(t);e.setEdges(n)}}}const Cu={duration:500},_u=L(su)`
5
+ || ${s} === "boolean" || ${i} === null`).assign(c,a._`[${i}]`)}}r.else(),g(e),r.endIf(),r.if(a._`${c} !== undefined`,(()=>{r.assign(i,c),function({gen:e,parentData:t,parentDataProperty:n},r){e.if(a._`${t} !== undefined`,(()=>e.assign(a._`${t}[${n}]`,r)))}(e,c)}))}(e,t,s):g(e)}))}return u};const l=new Set(["string","number","integer","boolean","null"]);function h(e,t,n,r=c.Correct){const i=r===c.Correct?a.operators.EQ:a.operators.NEQ;let o;switch(e){case"null":return a._`${t} ${i} null`;case"array":o=a._`Array.isArray(${t})`;break;case"object":o=a._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=s(a._`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=s();break;default:return a._`typeof ${t} ${i} ${e}`}return r===c.Correct?o:(0,a.not)(o);function s(e=a.nil){return(0,a.and)(a._`typeof ${t} == "number"`,e,n?a._`isFinite(${t})`:a.nil)}}function f(e,t,n,r){if(1===e.length)return h(e[0],t,n,r);let i;const o=(0,s.toHash)(e);if(o.array&&o.object){const e=a._`typeof ${t} != "object"`;i=o.null?e:a._`!${t} || ${e}`,delete o.null,delete o.array,delete o.object}else i=a.nil;o.number&&delete o.integer;for(const e in o)i=(0,a.and)(i,h(e,t,n,r));return i}t.checkDataType=h,t.checkDataTypes=f;const d={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?a._`{type: ${e}}`:a._`{type: ${t}}`};function g(e){const t=function(e){const{gen:t,data:n,schema:r}=e,i=(0,s.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}(e);(0,o.reportError)(t,d)}t.reportTypeError=g},20999:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getDefaultRoleFromConfig=function(e){return e.readOnly||e.disabledTools.includes("create")&&e.disabledTools.includes("update")&&e.disabledTools.includes("delete")?r:n};const n={roleName:"readWriteAnyDatabase",databaseName:"admin"},r={roleName:"readAnyDatabase",databaseName:"admin"}},21247:function(e,t,n){var r=n(65994).process,i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.detectContainerEnv=async function(){return void 0!==a||(a=await async function(){return"linux"===r.platform&&(!!r.env.container||(await Promise.all(["/.dockerenv","/run/.containerenv","/var/run/.containerenv"].map((async e=>{try{return await o.default.access(e),!0}catch{return!1}})))).includes(!0))}()),a};const o=i(n(65981));let a},21511:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(78249),i={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxItems"===e?"more":"fewer";return r.str`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>r._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:i}=e,o="maxItems"===t?r.operators.GT:r.operators.LT;e.fail$data(r._`${n}.length ${o} ${i}`)}};t.default=i},21570:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CollectionSchemaTool=void 0;const i=n(58203),o=n(77710),a=n(33168),s=r(n(69761)),c=n(18253),u=n(92639),l=n(33532);class h extends i.MongoDBToolBase{constructor(){super(...arguments),this.name="collection-schema",this.description="Describe the schema for a collection",this.argsShape={...i.DbOperationArgs,sampleSize:s.default.number().optional().default(50).describe("Number of documents to sample for schema inference"),responseBytesLimit:s.default.number().optional().default(c.ONE_MB).describe("The maximum number of bytes to return in the response. This value is capped by the server's configured maxBytesPerQuery and cannot be exceeded.")}}async execute({database:e,collection:t,sampleSize:n,responseBytesLimit:r},{signal:i}){const s=(await this.ensureConnected()).aggregate(e,t,[{$sample:{size:Math.min(n,5e4)}}],{signal:i}),{cappedBy:c,documents:h}=await(0,u.collectCursorUntilMaxBytesLimit)({cursor:s,configuredMaxBytesPerQuery:this.config.maxBytesPerQuery,toolResponseBytesLimit:r,abortSignal:i}),f=await(0,a.getSimplifiedSchema)(h);if((0,l.isObjectEmpty)(f))return{content:[{text:`Could not deduce the schema for "${e}.${t}". This may be because it doesn't exist or is empty.`,type:"text"}]};const d=`Found ${Object.keys(f).length} fields in the schema for "${e}.${t}"`,g=void 0!==c?`\nThe schema was inferred from a subset of documents due to the response size limit. (${c})`:"";return{content:(0,o.formatUntrustedData)(`${d}${g}`,JSON.stringify(f))}}}t.CollectionSchemaTool=h,h.operationType="metadata"},22010:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UriTemplate=void 0;const n=1e6,r=1e6;class i{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,n){if(e.length>t)throw new Error(`${n} exceeds maximum length of ${t} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap((e=>"string"==typeof e?[]:e.names))}constructor(e){i.validateLength(e,n,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){const t=[];let n="",o=0,a=0;for(;o<e.length;)if("{"===e[o]){n&&(t.push(n),n="");const s=e.indexOf("}",o);if(-1===s)throw new Error("Unclosed template expression");if(a++,a>1e4)throw new Error("Template contains too many expressions (max 10000)");const c=e.slice(o+1,s),u=this.getOperator(c),l=c.includes("*"),h=this.getNames(c),f=h[0];for(const e of h)i.validateLength(e,r,"Variable name");t.push({name:f,operator:u,names:h,exploded:l}),o=s+1}else n+=e[o],o++;return n&&t.push(n),t}getOperator(e){return["+","#",".","/","?","&"].find((t=>e.startsWith(t)))||""}getNames(e){const t=this.getOperator(e);return e.slice(t.length).split(",").map((e=>e.replace("*","").trim())).filter((e=>e.length>0))}encodeValue(e,t){return i.validateLength(e,r,"Variable value"),"+"===t||"#"===t?encodeURI(e):encodeURIComponent(e)}expandPart(e,t){if("?"===e.operator||"&"===e.operator){const n=e.names.map((n=>{const r=t[n];return void 0===r?"":`${n}=${Array.isArray(r)?r.map((t=>this.encodeValue(t,e.operator))).join(","):this.encodeValue(r.toString(),e.operator)}`})).filter((e=>e.length>0));return 0===n.length?"":("?"===e.operator?"?":"&")+n.join("&")}if(e.names.length>1){const n=e.names.map((e=>t[e])).filter((e=>void 0!==e));return 0===n.length?"":n.map((e=>Array.isArray(e)?e[0]:e)).join(",")}const n=t[e.name];if(void 0===n)return"";const r=(Array.isArray(n)?n:[n]).map((t=>this.encodeValue(t,e.operator)));switch(e.operator){case"":case"+":default:return r.join(",");case"#":return"#"+r.join(",");case".":return"."+r.join(".");case"/":return"/"+r.join("/")}}expand(e){let t="",n=!1;for(const r of this.parts){if("string"==typeof r){t+=r;continue}const i=this.expandPart(r,e);i&&("?"!==r.operator&&"&"!==r.operator||!n?t+=i:t+=i.replace("?","&"),"?"!==r.operator&&"&"!==r.operator||(n=!0))}return t}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){const t=[];for(const t of e.names)i.validateLength(t,r,"Variable name");if("?"===e.operator||"&"===e.operator){for(let n=0;n<e.names.length;n++){const r=e.names[n],i=0===n?"\\"+e.operator:"&";t.push({pattern:i+this.escapeRegExp(r)+"=([^&]+)",name:r})}return t}let n;const o=e.name;switch(e.operator){case"":n=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return t.push({pattern:n,name:o}),t}match(e){i.validateLength(e,n,"URI");let t="^";const r=[];for(const e of this.parts)if("string"==typeof e)t+=this.escapeRegExp(e);else{const n=this.partToRegExp(e);for(const{pattern:i,name:o}of n)t+=i,r.push({name:o,exploded:e.exploded})}t+="$",i.validateLength(t,1e6,"Generated regex pattern");const o=new RegExp(t),a=e.match(o);if(!a)return null;const s={};for(let e=0;e<r.length;e++){const{name:t,exploded:n}=r[e],i=a[e+1],o=t.replace("*","");n&&i.includes(",")?s[o]=i.split(","):s[o]=i}return s}}t.UriTemplate=i},22384:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRandomUUID=function(){try{return n(27348).randomUUID()}catch{return"undefined"!=typeof globalThis&&globalThis.crypto&&"function"==typeof globalThis.crypto.randomUUID?globalThis.crypto.randomUUID():(new r.UUID).toString()}};const r=n(62444)},22880:(e,t,n)=>{var r=n(65994).process;Object.defineProperty(t,"__esModule",{value:!0}),t.LRUCache=void 0;const i="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,o=new Set,a="object"==typeof r&&r?r:{},s=(e,t,n,r)=>{"function"==typeof a.emitWarning?a.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)};let c=globalThis.AbortController,u=globalThis.AbortSignal;if(void 0===c){u=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},c=class{constructor(){t()}signal=new u;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==a.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,s("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}Symbol("type");const l=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),h=e=>l(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?f:null:null;class f extends Array{constructor(e){super(e),this.fill(0)}}class d{heap;length;static#e=!1;static create(e){const t=h(e);if(!t)return[];d.#e=!0;const n=new d(e,t);return d.#e=!1,n}constructor(e,t){if(!d.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class g{#t;#n;#r;#i;#o;#a;#s;#c;get perf(){return this.#c}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#u;#l;#h;#f;#d;#g;#p;#b;#m;#w;#v;#y;#S;#k;#E;#x;#M;#T;#C;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#k,autopurgeTimers:e.#E,sizes:e.#y,keyMap:e.#h,keyList:e.#f,valList:e.#d,next:e.#g,prev:e.#p,get head(){return e.#b},get tail(){return e.#m},free:e.#w,isBackgroundFetch:t=>e.#_(t),backgroundFetch:(t,n,r,i)=>e.#P(t,n,r,i),moveToTail:t=>e.#I(t),indexes:t=>e.#A(t),rindexes:t=>e.#O(t),isStale:t=>e.#j(t)}}get max(){return this.#t}get maxSize(){return this.#n}get calculatedSize(){return this.#l}get size(){return this.#u}get fetchMethod(){return this.#a}get memoMethod(){return this.#s}get dispose(){return this.#r}get onInsert(){return this.#i}get disposeAfter(){return this.#o}constructor(e){const{max:t=0,ttl:n,ttlResolution:r=1,ttlAutopurge:a,updateAgeOnGet:c,updateAgeOnHas:u,allowStale:f,dispose:p,onInsert:b,disposeAfter:m,noDisposeOnSet:w,noUpdateTTL:v,maxSize:y=0,maxEntrySize:S=0,sizeCalculation:k,fetchMethod:E,memoMethod:x,noDeleteOnFetchRejection:M,noDeleteOnStaleGet:T,allowStaleOnFetchRejection:C,allowStaleOnFetchAbort:_,ignoreFetchAbort:P,perf:I}=e;if(void 0!==I&&"function"!=typeof I?.now)throw new TypeError("perf option must have a now() method if specified");if(this.#c=I??i,0!==t&&!l(t))throw new TypeError("max option must be a nonnegative integer");const A=t?h(t):Array;if(!A)throw new Error("invalid max value: "+t);if(this.#t=t,this.#n=y,this.maxEntrySize=S||this.#n,this.sizeCalculation=k,this.sizeCalculation){if(!this.#n&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==x&&"function"!=typeof x)throw new TypeError("memoMethod must be a function if defined");if(this.#s=x,void 0!==E&&"function"!=typeof E)throw new TypeError("fetchMethod must be a function if specified");if(this.#a=E,this.#M=!!E,this.#h=new Map,this.#f=new Array(t).fill(void 0),this.#d=new Array(t).fill(void 0),this.#g=new A(t),this.#p=new A(t),this.#b=0,this.#m=0,this.#w=d.create(t),this.#u=0,this.#l=0,"function"==typeof p&&(this.#r=p),"function"==typeof b&&(this.#i=b),"function"==typeof m?(this.#o=m,this.#v=[]):(this.#o=void 0,this.#v=void 0),this.#x=!!this.#r,this.#C=!!this.#i,this.#T=!!this.#o,this.noDisposeOnSet=!!w,this.noUpdateTTL=!!v,this.noDeleteOnFetchRejection=!!M,this.allowStaleOnFetchRejection=!!C,this.allowStaleOnFetchAbort=!!_,this.ignoreFetchAbort=!!P,0!==this.maxEntrySize){if(0!==this.#n&&!l(this.#n))throw new TypeError("maxSize must be a positive integer if specified");if(!l(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!f,this.noDeleteOnStaleGet=!!T,this.updateAgeOnGet=!!c,this.updateAgeOnHas=!!u,this.ttlResolution=l(r)||0===r?r:1,this.ttlAutopurge=!!a,this.ttl=n||0,this.ttl){if(!l(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#R()}if(0===this.#t&&0===this.ttl&&0===this.#n)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#n){const e="LRU_CACHE_UNBOUNDED";(e=>!o.has(e))(e)&&(o.add(e),s("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,g))}}getRemainingTTL(e){return this.#h.has(e)?1/0:0}#R(){const e=new f(this.#t),t=new f(this.#t);this.#k=e,this.#S=t;const n=this.ttlAutopurge?new Array(this.#t):void 0;this.#E=n,this.#N=(r,i,o=this.#c.now())=>{if(t[r]=0!==i?o:0,e[r]=i,n?.[r]&&(clearTimeout(n[r]),n[r]=void 0),0!==i&&n){const e=setTimeout((()=>{this.#j(r)&&this.#L(this.#f[r],"expire")}),i+1);e.unref&&e.unref(),n[r]=e}},this.#D=n=>{t[n]=0!==e[n]?this.#c.now():0},this.#F=(n,o)=>{if(e[o]){const a=e[o],s=t[o];if(!a||!s)return;n.ttl=a,n.start=s,n.now=r||i();const c=n.now-s;n.remainingTTL=a-c}};let r=0;const i=()=>{const e=this.#c.now();if(this.ttlResolution>0){r=e;const t=setTimeout((()=>r=0),this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=n=>{const o=this.#h.get(n);if(void 0===o)return 0;const a=e[o],s=t[o];return a&&s?a-((r||i())-s):1/0},this.#j=n=>{const o=t[n],a=e[n];return!!a&&!!o&&(r||i())-o>a}}#D=()=>{};#F=()=>{};#N=()=>{};#j=()=>!1;#$(){const e=new f(this.#t);this.#l=0,this.#y=e,this.#B=t=>{this.#l-=e[t],e[t]=0},this.#z=(e,t,n,r)=>{if(this.#_(t))return 0;if(!l(n)){if(!r)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof r)throw new TypeError("sizeCalculation must be a function");if(n=r(t,e),!l(n))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return n},this.#U=(t,n,r)=>{if(e[t]=n,this.#n){const n=this.#n-e[t];for(;this.#l>n;)this.#q(!0)}this.#l+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#l)}}#B=e=>{};#U=(e,t,n)=>{};#z=(e,t,n,r)=>{if(n||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:e=this.allowStale}={}){if(this.#u)for(let t=this.#m;this.#H(t)&&(!e&&this.#j(t)||(yield t),t!==this.#b);)t=this.#p[t]}*#O({allowStale:e=this.allowStale}={}){if(this.#u)for(let t=this.#b;this.#H(t)&&(!e&&this.#j(t)||(yield t),t!==this.#m);)t=this.#g[t]}#H(e){return void 0!==e&&this.#h.get(this.#f[e])===e}*entries(){for(const e of this.#A())void 0===this.#d[e]||void 0===this.#f[e]||this.#_(this.#d[e])||(yield[this.#f[e],this.#d[e]])}*rentries(){for(const e of this.#O())void 0===this.#d[e]||void 0===this.#f[e]||this.#_(this.#d[e])||(yield[this.#f[e],this.#d[e]])}*keys(){for(const e of this.#A()){const t=this.#f[e];void 0===t||this.#_(this.#d[e])||(yield t)}}*rkeys(){for(const e of this.#O()){const t=this.#f[e];void 0===t||this.#_(this.#d[e])||(yield t)}}*values(){for(const e of this.#A())void 0===this.#d[e]||this.#_(this.#d[e])||(yield this.#d[e])}*rvalues(){for(const e of this.#O())void 0===this.#d[e]||this.#_(this.#d[e])||(yield this.#d[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const n of this.#A()){const r=this.#d[n],i=this.#_(r)?r.__staleWhileFetching:r;if(void 0!==i&&e(i,this.#f[n],this))return this.get(this.#f[n],t)}}forEach(e,t=this){for(const n of this.#A()){const r=this.#d[n],i=this.#_(r)?r.__staleWhileFetching:r;void 0!==i&&e.call(t,i,this.#f[n],this)}}rforEach(e,t=this){for(const n of this.#O()){const r=this.#d[n],i=this.#_(r)?r.__staleWhileFetching:r;void 0!==i&&e.call(t,i,this.#f[n],this)}}purgeStale(){let e=!1;for(const t of this.#O({allowStale:!0}))this.#j(t)&&(this.#L(this.#f[t],"expire"),e=!0);return e}info(e){const t=this.#h.get(e);if(void 0===t)return;const n=this.#d[t],r=this.#_(n)?n.__staleWhileFetching:n;if(void 0===r)return;const i={value:r};if(this.#k&&this.#S){const e=this.#k[t],n=this.#S[t];if(e&&n){const t=e-(this.#c.now()-n);i.ttl=t,i.start=Date.now()}}return this.#y&&(i.size=this.#y[t]),i}dump(){const e=[];for(const t of this.#A({allowStale:!0})){const n=this.#f[t],r=this.#d[t],i=this.#_(r)?r.__staleWhileFetching:r;if(void 0===i||void 0===n)continue;const o={value:i};if(this.#k&&this.#S){o.ttl=this.#k[t];const e=this.#c.now()-this.#S[t];o.start=Math.floor(Date.now()-e)}this.#y&&(o.size=this.#y[t]),e.unshift([n,o])}return e}load(e){this.clear();for(const[t,n]of e){if(n.start){const e=Date.now()-n.start;n.start=this.#c.now()-e}this.set(t,n.value,n)}}set(e,t,n={}){if(void 0===t)return this.delete(e),this;const{ttl:r=this.ttl,start:i,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:s}=n;let{noUpdateTTL:c=this.noUpdateTTL}=n;const u=this.#z(e,t,n.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return s&&(s.set="miss",s.maxEntrySizeExceeded=!0),this.#L(e,"set"),this;let l=0===this.#u?void 0:this.#h.get(e);if(void 0===l)l=0===this.#u?this.#m:0!==this.#w.length?this.#w.pop():this.#u===this.#t?this.#q(!1):this.#u,this.#f[l]=e,this.#d[l]=t,this.#h.set(e,l),this.#g[this.#m]=l,this.#p[l]=this.#m,this.#m=l,this.#u++,this.#U(l,u,s),s&&(s.set="add"),c=!1,this.#C&&this.#i?.(t,e,"add");else{this.#I(l);const n=this.#d[l];if(t!==n){if(this.#M&&this.#_(n)){n.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=n;void 0===t||o||(this.#x&&this.#r?.(t,e,"set"),this.#T&&this.#v?.push([t,e,"set"]))}else o||(this.#x&&this.#r?.(n,e,"set"),this.#T&&this.#v?.push([n,e,"set"]));if(this.#B(l),this.#U(l,u,s),this.#d[l]=t,s){s.set="replace";const e=n&&this.#_(n)?n.__staleWhileFetching:n;void 0!==e&&(s.oldValue=e)}}else s&&(s.set="update");this.#C&&this.onInsert?.(t,e,t===n?"update":"replace")}if(0===r||this.#k||this.#R(),this.#k&&(c||this.#N(l,r,i),s&&this.#F(s,l)),!o&&this.#T&&this.#v){const e=this.#v;let t;for(;t=e?.shift();)this.#o?.(...t)}return this}pop(){try{for(;this.#u;){const e=this.#d[this.#b];if(this.#q(!0),this.#_(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#T&&this.#v){const e=this.#v;let t;for(;t=e?.shift();)this.#o?.(...t)}}}#q(e){const t=this.#b,n=this.#f[t],r=this.#d[t];return this.#M&&this.#_(r)?r.__abortController.abort(new Error("evicted")):(this.#x||this.#T)&&(this.#x&&this.#r?.(r,n,"evict"),this.#T&&this.#v?.push([r,n,"evict"])),this.#B(t),this.#E?.[t]&&(clearTimeout(this.#E[t]),this.#E[t]=void 0),e&&(this.#f[t]=void 0,this.#d[t]=void 0,this.#w.push(t)),1===this.#u?(this.#b=this.#m=0,this.#w.length=0):this.#b=this.#g[t],this.#h.delete(n),this.#u--,t}has(e,t={}){const{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#h.get(e);if(void 0!==i){const e=this.#d[i];if(this.#_(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#j(i))return n&&this.#D(i),r&&(r.has="hit",this.#F(r,i)),!0;r&&(r.has="stale",this.#F(r,i))}else r&&(r.has="miss");return!1}peek(e,t={}){const{allowStale:n=this.allowStale}=t,r=this.#h.get(e);if(void 0===r||!n&&this.#j(r))return;const i=this.#d[r];return this.#_(i)?i.__staleWhileFetching:i}#P(e,t,n,r){const i=void 0===t?void 0:this.#d[t];if(this.#_(i))return i;const o=new c,{signal:a}=n;a?.addEventListener("abort",(()=>o.abort(a.reason)),{signal:o.signal});const s={signal:o.signal,options:n,context:r},u=(r,i=!1)=>{const{aborted:a}=o.signal,c=n.ignoreFetchAbort&&void 0!==r;if(n.status&&(a&&!i?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,c&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),a&&!c&&!i)return l(o.signal.reason);const u=h,f=this.#d[t];return(f===h||c&&i&&void 0===f)&&(void 0===r?void 0!==u.__staleWhileFetching?this.#d[t]=u.__staleWhileFetching:this.#L(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,r,s.options))),r},l=r=>{const{aborted:i}=o.signal,a=i&&n.allowStaleOnFetchAbort,s=a||n.allowStaleOnFetchRejection,c=s||n.noDeleteOnFetchRejection,u=h;if(this.#d[t]===h&&(c&&void 0!==u.__staleWhileFetching?a||(this.#d[t]=u.__staleWhileFetching):this.#L(e,"fetch")),s)return n.status&&void 0!==u.__staleWhileFetching&&(n.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw r};n.status&&(n.status.fetchDispatched=!0);const h=new Promise(((t,r)=>{const a=this.#a?.(e,i,s);a&&a instanceof Promise&&a.then((e=>t(void 0===e?void 0:e)),r),o.signal.addEventListener("abort",(()=>{n.ignoreFetchAbort&&!n.allowStaleOnFetchAbort||(t(void 0),n.allowStaleOnFetchAbort&&(t=e=>u(e,!0)))}))})).then(u,(e=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=e),l(e)))),f=Object.assign(h,{__abortController:o,__staleWhileFetching:i,__returned:void 0});return void 0===t?(this.set(e,f,{...s.options,status:void 0}),t=this.#h.get(e)):this.#d[t]=f,f}#_(e){if(!this.#M)return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof c}async fetch(e,t={}){const{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:s=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:h=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:d=this.allowStaleOnFetchAbort,context:g,forceRefresh:p=!1,status:b,signal:m}=t;if(!this.#M)return b&&(b.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:b});const w={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:o,noDisposeOnSet:a,size:s,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:h,allowStaleOnFetchAbort:d,ignoreFetchAbort:f,status:b,signal:m};let v=this.#h.get(e);if(void 0===v){b&&(b.fetch="miss");const t=this.#P(e,v,w,g);return t.__returned=t}{const t=this.#d[v];if(this.#_(t)){const e=n&&void 0!==t.__staleWhileFetching;return b&&(b.fetch="inflight",e&&(b.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const i=this.#j(v);if(!p&&!i)return b&&(b.fetch="hit"),this.#I(v),r&&this.#D(v),b&&this.#F(b,v),t;const o=this.#P(e,v,w,g),a=void 0!==o.__staleWhileFetching&&n;return b&&(b.fetch=i?"stale":"refresh",a&&i&&(b.returnedStale=!0)),a?o.__staleWhileFetching:o.__returned=o}}async forceFetch(e,t={}){const n=await this.fetch(e,t);if(void 0===n)throw new Error("fetch() returned undefined");return n}memo(e,t={}){const n=this.#s;if(!n)throw new Error("no memoMethod provided to constructor");const{context:r,forceRefresh:i,...o}=t,a=this.get(e,o);if(!i&&void 0!==a)return a;const s=n(e,a,{options:o,context:r});return this.set(e,s,o),s}get(e,t={}){const{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:o}=t,a=this.#h.get(e);if(void 0!==a){const t=this.#d[a],s=this.#_(t);return o&&this.#F(o,a),this.#j(a)?(o&&(o.get="stale"),s?(o&&n&&void 0!==t.__staleWhileFetching&&(o.returnedStale=!0),n?t.__staleWhileFetching:void 0):(i||this.#L(e,"expire"),o&&n&&(o.returnedStale=!0),n?t:void 0)):(o&&(o.get="hit"),s?t.__staleWhileFetching:(this.#I(a),r&&this.#D(a),t))}o&&(o.get="miss")}#J(e,t){this.#p[t]=e,this.#g[e]=t}#I(e){e!==this.#m&&(e===this.#b?this.#b=this.#g[e]:this.#J(this.#p[e],this.#g[e]),this.#J(this.#m,e),this.#m=e)}delete(e){return this.#L(e,"delete")}#L(e,t){let n=!1;if(0!==this.#u){const r=this.#h.get(e);if(void 0!==r)if(this.#E?.[r]&&(clearTimeout(this.#E?.[r]),this.#E[r]=void 0),n=!0,1===this.#u)this.#G(t);else{this.#B(r);const n=this.#d[r];if(this.#_(n)?n.__abortController.abort(new Error("deleted")):(this.#x||this.#T)&&(this.#x&&this.#r?.(n,e,t),this.#T&&this.#v?.push([n,e,t])),this.#h.delete(e),this.#f[r]=void 0,this.#d[r]=void 0,r===this.#m)this.#m=this.#p[r];else if(r===this.#b)this.#b=this.#g[r];else{const e=this.#p[r];this.#g[e]=this.#g[r];const t=this.#g[r];this.#p[t]=this.#p[r]}this.#u--,this.#w.push(r)}}if(this.#T&&this.#v?.length){const e=this.#v;let t;for(;t=e?.shift();)this.#o?.(...t)}return n}clear(){return this.#G("delete")}#G(e){for(const t of this.#O({allowStale:!0})){const n=this.#d[t];if(this.#_(n))n.__abortController.abort(new Error("deleted"));else{const r=this.#f[t];this.#x&&this.#r?.(n,r,e),this.#T&&this.#v?.push([n,r,e])}}if(this.#h.clear(),this.#d.fill(void 0),this.#f.fill(void 0),this.#k&&this.#S){this.#k.fill(0),this.#S.fill(0);for(const e of this.#E??[])void 0!==e&&clearTimeout(e);this.#E?.fill(void 0)}if(this.#y&&this.#y.fill(0),this.#b=0,this.#m=0,this.#w.length=0,this.#l=0,this.#u=0,this.#T&&this.#v){const e=this.#v;let t;for(;t=e?.shift();)this.#o?.(...t)}}}t.LRUCache=g},23319:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.redactConnectionString=t.shouldRedactCommand=void 0,t.redact=a;const r=n(94424),i=n(53442),o=n(20530);function a(e,t=void 0){if((0,i.isPlainObject)(e)){const n=Object.fromEntries(Object.entries(e).map((([e,n])=>[e,a(n,t)])));return Object.setPrototypeOf(n,Object.getPrototypeOf(e))}if(Array.isArray(e))return e.map((e=>a(e,t)));if("string"!=typeof e)return e;t&&(e=(0,o.redactSecretsOnString)(e,t));for(const[t,n]of r.regexes)e=e.replace(t,n);return e}var s=n(97872);Object.defineProperty(t,"shouldRedactCommand",{enumerable:!0,get:function(){return s.shouldRedactCommand}});var c=n(48777);Object.defineProperty(t,"redactConnectionString",{enumerable:!0,get:function(){return c.redactConnectionString}}),t.default=a},24609:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SLOW_QUERY_LOGS_COPY=t.SUGGESTED_INDEXES_COPY=t.DEFAULT_SLOW_QUERY_LOGS_LIMIT=void 0,t.getSuggestedIndexes=async function(e,t,n){try{return{suggestedIndexes:(await e.listClusterSuggestedIndexes({params:{path:{groupId:t,clusterName:n}}})).content.suggestedIndexes??[]}}catch(t){throw e.logger.debug({id:r.LogId.atlasPaSuggestedIndexesFailure,context:"performanceAdvisorUtils",message:`Failed to list suggested indexes: ${t instanceof Error?t.message:String(t)}`}),new Error(`Failed to list suggested indexes: ${t instanceof Error?t.message:String(t)}`)}},t.getDropIndexSuggestions=async function(e,t,n){try{const r=await e.listDropIndexSuggestions({params:{path:{groupId:t,clusterName:n}}});return{hiddenIndexes:r.content.hiddenIndexes??[],redundantIndexes:r.content.redundantIndexes??[],unusedIndexes:r.content.unusedIndexes??[]}}catch(t){throw e.logger.debug({id:r.LogId.atlasPaDropIndexSuggestionsFailure,context:"performanceAdvisorUtils",message:`Failed to list drop index suggestions: ${t instanceof Error?t.message:String(t)}`}),new Error(`Failed to list drop index suggestions: ${t instanceof Error?t.message:String(t)}`)}},t.getSchemaAdvice=async function(e,t,n){try{return{recommendations:(await e.listSchemaAdvice({params:{path:{groupId:t,clusterName:n}}})).content.recommendations??[]}}catch(t){throw e.logger.debug({id:r.LogId.atlasPaSchemaAdviceFailure,context:"performanceAdvisorUtils",message:`Failed to list schema advice: ${t instanceof Error?t.message:String(t)}`}),new Error(`Failed to list schema advice: ${t instanceof Error?t.message:String(t)}`)}},t.getSlowQueries=async function(e,n,o,a,s){try{const r=await(0,i.getProcessIdsFromCluster)(e,n,o);if(0===r.length)return{slowQueryLogs:[]};const c=r.map((r=>e.listSlowQueryLogs({params:{path:{groupId:n,processId:r},query:{...a&&{since:a.getTime()},...s&&{namespaces:s},nLogs:t.DEFAULT_SLOW_QUERY_LOGS_LIMIT}}})));return{slowQueryLogs:(await Promise.allSettled(c)).reduce(((e,t)=>e.concat("fulfilled"===t.status?t.value.slowQueries??[]:[])),[])}}catch(t){throw e.logger.debug({id:r.LogId.atlasPaSlowQueryLogsFailure,context:"performanceAdvisorUtils",message:`Failed to list slow query logs: ${t instanceof Error?t.message:String(t)}`}),new Error(`Failed to list slow query logs: ${t instanceof Error?t.message:String(t)}`)}};const r=n(45584),i=n(30084);t.DEFAULT_SLOW_QUERY_LOGS_LIMIT=50,t.SUGGESTED_INDEXES_COPY='Note: The "Weight" field is measured in bytes, and represents the estimated number of bytes saved in disk reads per executed read query that would be saved by implementing an index suggestion. Please convert this to MB or GB for easier readability.',t.SLOW_QUERY_LOGS_COPY=`Please notify the user that the MCP server tool limits slow query logs to the most recent ${t.DEFAULT_SLOW_QUERY_LOGS_LIMIT} slow query logs. This is a limitation of the MCP server tool only. More slow query logs and performance suggestions can be seen in the Atlas UI. Please give to the user the following docs about the performance advisor: https://www.mongodb.com/docs/atlas/performance-advisor/.`},25056:(e,t,n)=>{var r=n(65994).process;Object.defineProperty(t,"__esModule",{value:!0}),t.TransportRunnerBase=void 0;const i=n(60842),o=n(74171),a=n(84998),s=n(72389),c=n(3476),u=n(45584),l=n(35902),h=n(41654),f=n(4060),d=n(67645),g=n(98846),p=n(6467),b=n(87226),m=n(83671),w=n(50598),v=n(71777);class y{constructor({userConfig:e,createConnectionManager:t=d.createMCPConnectionManager,connectionErrorHandler:n=g.connectionErrorHandler,createAtlasLocalClient:i=b.defaultCreateAtlasLocalClient,additionalLoggers:o=[],telemetryProperties:a={},tools:s,createSessionConfig:c,createApiClient:l=v.createAtlasApiClient}){this.userConfig=e,this.createConnectionManager=t,this.connectionErrorHandler=n,this.createAtlasLocalClient=i,this.telemetryProperties=a,this.tools=s,this.createSessionConfig=c,this.createApiClient=l;const p=[...o];this.userConfig.loggers.includes("stderr")&&p.push(new u.ConsoleLogger(f.Keychain.root)),this.userConfig.loggers.includes("disk")&&p.push(new u.DiskLogger(this.userConfig.logPath,(e=>{console.error("Error initializing disk logger:",e),r.exit(1)}),f.Keychain.root)),this.logger=new u.CompositeLogger(...p),this.deviceId=h.DeviceId.create(this.logger)}async setupServer(e){let t=this.userConfig;t=this.createSessionConfig?await this.createSessionConfig({userConfig:t,request:e}):(0,w.applyConfigOverrides)({baseConfig:this.userConfig,request:e});const n=new c.McpServer({name:i.packageInfo.mcpServerName,version:i.packageInfo.version},{instructions:y.getInstructions(t)}),r=new u.CompositeLogger(this.logger),h=l.ExportsManager.init(t,r),d=await this.createConnectionManager({logger:r,userConfig:t,deviceId:this.deviceId});let g;t.apiClientId&&t.apiClientSecret&&(g=this.createApiClient({baseUrl:t.apiBaseUrl,credentials:{clientId:t.apiClientId,clientSecret:t.apiClientSecret},requestContext:e},r));const b=new a.Session({userConfig:t,atlasLocalClient:await this.createAtlasLocalClient({logger:r}),logger:r,exportsManager:h,connectionManager:d,keychain:f.Keychain.root,vectorSearchEmbeddingsManager:new m.VectorSearchEmbeddingsManager(t,d),apiClient:g}),v=s.Telemetry.create(b,t,this.deviceId,{commonProperties:this.telemetryProperties}),S=new p.Elicitation({server:n.server}),k=new o.Server({mcpServer:n,session:b,telemetry:v,userConfig:t,connectionErrorHandler:this.connectionErrorHandler,elicitation:S,tools:this.tools});return t.loggers.includes("mcp")&&r.addLogger(new u.McpLogger(k,f.Keychain.root)),k}async close(){try{await this.closeTransport()}finally{this.deviceId.close()}}static getInstructions(e){let t="\n This is the MongoDB MCP server.\n ";return e.connectionString&&(t+="\n This MCP server was configured with a MongoDB connection string, and you can assume that you are connected to a MongoDB cluster.\n "),e.apiClientId&&e.apiClientSecret&&(t+="\n This MCP server was configured with MongoDB Atlas API credentials."),t}}t.TransportRunnerBase=y},25181:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:n(89689).validateUnion,error:{message:"must match a schema in anyOf"}};t.default=r},25182:function(e,t,n){var r,i=n(9606).URL,o=n(67787).Buffer,a=n(9606).URLSearchParams,s=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),c=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),u=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=r(e),i=0;i<n.length;i++)"default"!==n[i]&&s(t,e,n[i]);return c(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.ClientCredentialsAuthProvider=void 0;const l=u(n(54617)),h=n(45584),f=n(79587);t.ClientCredentialsAuthProvider=class{constructor(e,t){this.options=e,this.logger=t,this.oauth2Issuer={issuer:e.baseUrl,token_endpoint:new i("/api/oauth/token",e.baseUrl).toString(),revocation_endpoint:new i("/api/oauth/revoke",e.baseUrl).toString(),token_endpoint_auth_methods_supported:["client_secret_basic"],grant_types_supported:["client_credentials"]},this.customFetch=(0,f.createFetch)({useEnvironmentVariableProxies:!0})}async getAuthHeaders(){const e=await this.getAccessToken();return e?{Authorization:`Bearer ${e}`}:void 0}isAccessTokenValid(){return!!(this.accessToken&&void 0!==this.accessToken.expires_at&&this.accessToken.expires_at>Date.now())}getOauthClientAuth(){const e=this.options.clientSecret,t=this.options.clientId;return{client:{client_id:t},clientAuth:(n,r,i,a)=>{const s=o.from(`${t}:${e}`).toString("base64");a.set("Authorization",`Basic ${s}`)}}}async getNewAccessToken(){if(!this.oauth2Issuer)return;const{client:e,clientAuth:t}=this.getOauthClientAuth();if(e&&t){try{const n=await l.clientCredentialsGrantRequest(this.oauth2Issuer,e,t,new a,{[l.customFetch]:this.customFetch,headers:{"User-Agent":this.options.userAgent}}),r=await l.processClientCredentialsResponse(this.oauth2Issuer,e,n);this.accessToken={access_token:r.access_token,expires_at:Date.now()+1e3*(r.expires_in??0)}}catch(e){const t=e instanceof Error?e:new Error(String(e));this.logger.error({id:h.LogId.atlasConnectFailure,context:"clientCredentialsAuth",message:`Failed to request access token: ${t.message}`})}return this.accessToken}}async getAccessToken(){return this.isAccessTokenValid()||(this.accessToken=await this.getNewAccessToken()),this.accessToken?.access_token}async validate(){return!!await this.getAccessToken()}async revoke(){const{client:e,clientAuth:t}=this.getOauthClientAuth();try{this.oauth2Issuer&&this.accessToken&&e&&t&&await l.revocationRequest(this.oauth2Issuer,e,t,this.accessToken.access_token)}catch(e){const t=e instanceof Error?e:new Error(String(e));this.logger.error({id:h.LogId.atlasApiRevokeFailure,context:"clientCredentialsAuth",message:`Failed to revoke access token: ${t.message}`})}this.accessToken=void 0}}},25220:(e,t,n)=>{n.d(t,{Ay:()=>i});var r=n(12453);const i=r;r.MAX_DATABASE_NAME_LENGTH,r.sort},25364:function(e,t,n){var r,i=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=r(e),a=0;a<n.length;a++)"default"!==n[a]&&i(t,e,n[a]);return o(t,e),t}),s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_HINT=t.DEFAULT_MAX_TIME_MS=t.DEFAULT_COLLATION=t.DEFAULT_PROJECT=t.DEFAULT_SKIP=t.DEFAULT_LIMIT=t.DEFAULT_SORT=t.DEFAULT_FILTER=t.toJSString=t.stringify=void 0,t.parseSort=T,t.parseFilter=function(e){return k(e)?g:_(e)},t.parseCollation=function(e){return k(e)?v:M(e)},t.isFilterValid=P,t.isCollationValid=I,t.parseProject=function(e){return k(e)?w:x(e)},t.isProjectValid=O,t.isSortValid=N,t.isHintValid=L,t.isMaxTimeMSValid=D,t.isSkipValid=F,t.isLimitValid=B,t.validate=function(e,t){const n=z[`is${u.default.upperFirst(e)}Valid`];return n?n(t):(d("Do not know how to validate `%s`. Returning false.",e),!1)},t.default=function(e,t=w){return 1===arguments.length&&u.default.isString(e)?_(e):{filter:_(e),project:t!==w?x(t):t}};const c=a(n(9651)),u=s(n(20990)),l=s(n(46696)),h=n(79193),f=n(60313);Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return f.stringify}}),Object.defineProperty(t,"toJSString",{enumerable:!0,get:function(){return f.toJSString}});const d=(0,l.default)("mongodb-query-parser"),g={};t.DEFAULT_FILTER=g;const p=null;t.DEFAULT_SORT=p;const b=0;t.DEFAULT_LIMIT=b;const m=0;t.DEFAULT_SKIP=m;const w=null;t.DEFAULT_PROJECT=w;const v=null;t.DEFAULT_COLLATION=v;const y=6e4;t.DEFAULT_MAX_TIME_MS=y;const S=null;function k(e){if(null==e)return!0;const t=u.default.trim("number"==typeof e?`${e}`:e);return"{}"===t||u.default.isEmpty(t)}function E(e){return k(e)?0:!!/^\d+$/.test(`${e}`)&&parseInt(`${e}`,10)}function x(e){return(0,c.default)(e,{mode:c.ParseMode.Loose})}function M(e){return(0,c.default)(e,{mode:c.ParseMode.Loose})}function T(e){return k(e)?p:(0,c.default)(e,{mode:c.ParseMode.Loose})}function C(){return!0}function _(e){return(0,c.default)(e,{mode:c.ParseMode.Loose,allowMethods:!0})}function P(e){if(k(e))return g;try{return _(e)}catch(t){return d('Filter "%s" is invalid',e,t),!1}}function I(e){if(k(e))return v;try{return function(e){for(const[t,n]of Object.entries(e)){if(!h.COLLATION_OPTIONS[t])return d('Collation "%s" is invalid bc of its keys',e),!1;if(!1===h.COLLATION_OPTIONS[t].includes(n))return d('Collation "%s" is invalid bc of its values',e),!1}return e}(M(e))}catch(t){return d('Collation "%s" is invalid',e,t),!1}}function A(){return!0}function O(e){if(k(e))return w;try{const t=x(e);return u.default.isObject(t)?u.default.every(t,A)?t:(d('Project "%s" is invalid bc of its values',e),!1):(d('Project "%s" is invalid. Only documents are allowed',e),!1)}catch(t){return d('Project "%s" is invalid',e,t),!1}}t.DEFAULT_HINT=S;const j=[1,-1,"asc","desc"];function $(e){return u.default.includes(j,e)||!(!u.default.isObject(e)||!e.$meta)}function R(e){return u.default.isArray(e)&&2===e.length&&u.default.isString(e[0])&&$(e[1])}function N(e){try{const t=T(e);return k(t)?p:u.default.isArray(t)&&u.default.every(t,R)||u.default.isObject(t)&&!u.default.isArray(t)&&u.default.every(t,$)?t:(d('Sort "%s" is invalid bc of its values',e),!1)}catch(t){return d('Sort "%s" is invalid',e,t),!1}}function L(e){if(k(e))return S;try{const t=function(e){return(0,c.default)(e,{mode:c.ParseMode.Loose})}(e);return u.default.isString(t)?t:u.default.isArray(t)||!u.default.isObject(t)?(d('Hint "%s" is invalid. Only strings or documents are allowed',e),!1):u.default.every(t,C)?t:(d('Hint "%s" is invalid bc of its values',e),!1)}catch(t){return d('Hint "%s" is invalid',e,t),!1}}function D(e){return k(e)?y:E(e)}function F(e){return k(e)?m:E(e)}function B(e){return k(e)?b:E(e)}const z={isMaxTimeMSValid:D,isFilterValid:P,isProjectValid:O,isSortValid:N,isLimitValid:B,isSkipValid:F,isCollationValid:I,isNumberValid:E,isHintValid:L}},25539:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultParserOptions=void 0,t.parseUserConfig=function({args:e,overrides:n,parserOptions:l=t.defaultParserOptions}){const h=n?c.z.object({...a.UserConfigSchema.shape,...n}):a.UserConfigSchema,{error:f,warnings:d,parsed:g}=function({args:e,schema:t=a.UserConfigSchema,parserOptions:n}){let r,i;try{const{parsed:o,deprecated:a}=(0,s.parseArgsWithCliOptions)({args:e,schema:t,parserOptions:n});r=o,i=a,delete r.fileNames}catch(e){let t;if(e instanceof s.UnknownArgumentError){const n=(0,o.matchingConfigKey)(e.argument.replace(/^(--)/,""));t=n?`Error: Invalid command line argument '${e.argument}'. Did you mean '--${n}'?`:`Error: Invalid command line argument '${e.argument}'.`}return{error:t,warnings:[],parsed:{}}}return{error:void 0,warnings:[...u(r,e),...Object.entries(i).map((([e,t])=>`Warning: The --${e} argument is deprecated. Use --${t} instead.`))],parsed:r}}({args:e,schema:h,parserOptions:l});if(f)return{error:f,warnings:d,parsed:void 0};if(g.nodb)return{error:"Error: The --nodb argument is not supported in the MCP Server. Please remove it from your configuration.",warnings:d,parsed:void 0};const{connectionSpecifier:p}=g;if(p){const e=(0,r.generateConnectionInfoFromCliArgs)({...g,connectionSpecifier:p});g.connectionString=e.connectionString}const b=h.safeParse(g),m=s.CliOptionsSchema.safeParse(g),w=b.error||m.error;if(w)return{error:`Invalid configuration for the following fields:\n${w.issues.map((e=>`${e.path.join(".")} - ${e.message}`)).join("\n")}`,warnings:d,parsed:void 0};const v={...g,...b.data};return function(e){const t=i.Keychain.root,n=(e,n)=>{e&&t.register(e,n)};n(e.apiClientId,"user"),n(e.apiClientSecret,"password"),n(e.awsAccessKeyId,"password"),n(e.awsIamSessionToken,"password"),n(e.awsSecretAccessKey,"password"),n(e.awsSessionToken,"password"),n(e.password,"password"),n(e.tlsCAFile,"url"),n(e.tlsCRLFile,"url"),n(e.tlsCertificateKeyFile,"url"),n(e.tlsCertificateKeyFilePassword,"password"),n(e.username,"user")}(v),{parsed:v,warnings:d,error:void 0}};const r=n(91841),i=n(4060),o=n(60466),a=n(59300),s=n(47645),c=n(19844);function u(e,t){const n=[];t.find((e=>e.startsWith("--connectionString")))&&n.push("Warning: The --connectionString argument is deprecated. Prefer using the MDB_MCP_CONNECTION_STRING environment variable or the first positional argument for the connection string.");const r=e.previewFeatures?.includes("search"),i=!!e.voyageApiKey;return r&&!i&&n.push("Warning: Vector search is enabled but no embeddings provider is configured.\n- Set an embeddings provider configuration option to enable auto-embeddings during document insertion and text-based queries with $vectorSearch."),!r&&i&&n.push("Warning: An embeddings provider is configured but the 'search' preview feature is not enabled.\n- Enable vector search by adding 'search' to the 'previewFeatures' configuration option, or remove the embeddings provider configuration if not needed."),n}t.defaultParserOptions={config:"config",envPrefix:"MDB_MCP_",configuration:{...s.defaultParserOptions.configuration,"populate--":!0}}},27293:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(78249),i={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>r.str`must match format "${e}"`,params:({schemaCode:e})=>r._`{format: ${e}}`},code(e,t){const{gen:n,data:i,$data:o,schema:a,schemaCode:s,it:c}=e,{opts:u,errSchemaPath:l,schemaEnv:h,self:f}=c;u.validateFormats&&(o?function(){const o=n.scopeValue("formats",{ref:f.formats,code:u.code.formats}),a=n.const("fDef",r._`${o}[${s}]`),c=n.let("fType"),l=n.let("format");n.if(r._`typeof ${a} == "object" && !(${a} instanceof RegExp)`,(()=>n.assign(c,r._`${a}.type || "string"`).assign(l,r._`${a}.validate`)),(()=>n.assign(c,r._`"string"`).assign(l,a))),e.fail$data((0,r.or)(!1===u.strictSchema?r.nil:r._`${s} && !${l}`,function(){const e=h.$async?r._`(${a}.async ? await ${l}(${i}) : ${l}(${i}))`:r._`${l}(${i})`,n=r._`(typeof ${l} == "function" ? ${e} : ${l}.test(${i}))`;return r._`${l} && ${l} !== true && ${c} === ${t} && !${n}`}()))}():function(){const o=f.formats[a];if(!o)return void function(){if(!1!==u.strictSchema)throw new Error(e());function e(){return`unknown format "${a}" ignored in schema at path "${l}"`}f.logger.warn(e())}();if(!0===o)return;const[s,c,d]=function(e){const t=e instanceof RegExp?(0,r.regexpCode)(e):u.code.formats?r._`${u.code.formats}${(0,r.getProperty)(a)}`:void 0,i=n.scopeValue("formats",{key:a,ref:e,code:t});return"object"!=typeof e||e instanceof RegExp?["string",e,i]:[e.type||"string",e.validate,r._`${i}.validate`]}(o);s===t&&e.pass(function(){if("object"==typeof o&&!(o instanceof RegExp)&&o.async){if(!h.$async)throw new Error("async format in sync schema");return r._`await ${d}(${i})`}return"function"==typeof c?r._`${d}(${i})`:r._`${d}.test(${i})`}())}())}};t.default=i},27373:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DeleteDeploymentTool=void 0;const r=n(66473),i=n(14233);class o extends r.AtlasLocalToolBase{constructor(){super(...arguments),this.name="atlas-local-delete-deployment",this.description="Delete a MongoDB Atlas local deployment",this.argsShape={deploymentName:i.CommonArgs.string().describe("Name of the deployment to delete")}}async executeWithAtlasLocalClient({deploymentName:e},{client:t}){const n=await this.lookupTelemetryMetadata(t,e);return await t.deleteDeployment(e),{content:[{type:"text",text:`Deployment "${e}" deleted successfully.`}],_meta:{...n}}}}t.DeleteDeploymentTool=o,o.operationType="delete"},28098:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(86),i=n(36937),o=n(78249),a=new o.Name("fullFormats"),s=new o.Name("fastFormats"),c=(e,t={keywords:!0})=>{if(Array.isArray(t))return u(e,t,r.fullFormats,a),e;const[n,o]="fast"===t.mode?[r.fastFormats,s]:[r.fullFormats,a];return u(e,t.formats||r.formatNames,n,o),t.keywords&&(0,i.default)(e),e};function u(e,t,n,r){var i,a;null!==(i=(a=e.opts.code).formats)&&void 0!==i||(a.formats=o._`require("ajv-formats/dist/formats").${r}`);for(const r of t)e.addFormat(r,n[r])}c.get=(e,t="full")=>{const n=("fast"===t?r.fastFormats:r.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n},e.exports=t=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c},28285:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InspectClusterTool=t.InspectClusterArgs=void 0;const r=n(77710),i=n(55415),o=n(30084),a=n(14233);t.InspectClusterArgs={projectId:a.AtlasArgs.projectId().describe("Atlas project ID"),clusterName:a.AtlasArgs.clusterName().describe("Atlas cluster name")};class s extends i.AtlasToolBase{constructor(){super(...arguments),this.name="atlas-inspect-cluster",this.description="Inspect metadata of a MongoDB Atlas cluster",this.argsShape={...t.InspectClusterArgs}}async execute({projectId:e,clusterName:t}){const n=await(0,o.inspectCluster)(this.apiClient,e,t);return this.formatOutput(n)}formatOutput(e){const t={name:e.name||"Unknown",instanceType:e.instanceType,instanceSize:e.instanceSize||"N/A",state:e.state||"UNKNOWN",mongoDBVersion:e.mongoDBVersion||"N/A",connectionStrings:e.connectionStrings||{}};return{content:(0,r.formatUntrustedData)("Cluster details:",JSON.stringify(t))}}}t.InspectClusterTool=s,s.operationType="read"},29009:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getDataLake=function(e){return d(e)&&d(e.dataLake)&&"string"==typeof e.dataLake.version?{isDataLake:!0,dlVersion:e.dataLake.version}:{isDataLake:!1,dlVersion:null}},t.isEnterprise=function(e){return!!d(e)&&(!("string"!=typeof e.gitVersion||!e.gitVersion.match(/enterprise/))||!(!Array.isArray(e.modules)||-1===e.modules.indexOf("enterprise")))},t.isAtlas=function(e){return!!p(e).match(a)},t.isLocalAtlas=async function(e){try{return await e("admin","atlascli",{managedClusterType:"atlasCliLocalDevCluster"})>0}catch{return!1}},t.isAtlasStream=function(e){const t=p(e);return!(!t.match(a)||!t.match(s))},t.isLocalhost=function(e){return!!p(e).match(c)},t.isDigitalOcean=function(e){return!!p(e).match(u)},t.getGenuineMongoDB=function(e){const t=p(e);return t.match(l)?{isGenuine:!1,serverName:"cosmosdb"}:t.match(h)?{isGenuine:!1,serverName:"documentdb"}:{isGenuine:!0,serverName:"mongodb"}},t.identifyServerName=async function({connectionString:e,adminCommand:t}){try{const n=p(e);if(n.match(a))return"mongodb";if(n.match(l))return"cosmosdb";if(n.match(h))return"documentdb";if(n.match(f))return"firestore";const r=await Promise.all([t({buildInfo:1}).then((e=>"ferretdb"in e?["ferretdb"]:[]),(e=>(o("buildInfo command failed %O",e),[]))),t({getParameter:"foo"}).then((()=>[]),(e=>e instanceof Error&&/documentdb_api/.test(e.message)?["pg_documentdb"]:[]))]).then((e=>e.flat()));return 0===r.length?"mongodb":1===r.length?r[0]:"unknown"}catch(e){return o("Failed to identify server name",e),"unknown"}},t.getBuildEnv=function(e){if(!d(e)||!d(e.buildEnvironment))return{serverOs:null,serverArch:null};const{buildEnvironment:t}=e;return{serverOs:"string"==typeof t.target_os?t.target_os:null,serverArch:"string"==typeof t.target_arch?t.target_arch:null}};const i=r(n(65031)),o=(0,n(46696).debug)("mongodb-build-info"),a=/\.mongodb(-dev|-qa|-stage)?\.net$/i,s=/^atlas-stream-.+/i,c=/^(localhost|127\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])|0\.0\.0\.0|(?:0*:)*?:?0*1)$/i,u=/\.mongo\.ondigitalocean\.com$/i,l=/\.cosmos\.azure\.com$/i,h=/docdb(-elastic)?\.amazonaws\.com$/i,f=/\.firestore.goog$/i;function d(e){return"object"==typeof e&&null!==e}function g(e){return e.startsWith("[")?e.substring(1).split("]")[0]:e.split(":")[0]}function p(e){if("string"!=typeof e)return"";try{return g(new i.default(e).hosts[0])}catch(t){return g(e)}}},29382:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReactiveResource=void 0;const r=n(45584);t.ReactiveResource=class{constructor({resourceConfiguration:e,options:t,session:n,config:r,telemetry:i,current:o}){this.resourceCallback=async e=>({contents:[{text:await this.toOutput(),mimeType:"application/json",uri:e.href}]}),this.session=n,this.config=r,this.telemetry=i,this.name=e.name,this.uri=e.uri,this.resourceConfig=e.config,this.events=t.events,this.current=o??t.initial,this.setupEventListeners()}setupEventListeners(){for(const e of this.events)this.session.on(e,((...t)=>{this.reduceApply(e,t[0]),this.triggerUpdate()}))}register(e){this.server=e,this.server.mcpServer.registerResource(this.name,this.uri,this.resourceConfig,this.resourceCallback)}triggerUpdate(){try{this.server?.sendResourceListChanged(),this.server?.sendResourceUpdated(this.uri)}catch(e){this.session.logger.warning({id:r.LogId.resourceUpdateFailure,context:"resource",message:`Could not send the latest resources to the client: ${e}`})}}reduceApply(e,...t){this.current=this.reduce(e,...t)}}},30084:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatFlexCluster=a,t.formatCluster=s,t.inspectCluster=c,t.getConnectionString=function(e,t){switch(t){case"standard":return e.standardSrv||e.standard;case"private":return e.privateSrv||e.private;case"privateEndpoint":return e.privateEndpoint?.[0]?.srvConnectionString||e.privateEndpoint?.[0]?.connectionString}},t.getProcessIdsFromCluster=async function(e,t,n){try{return(await c(e,t,n)).processIds||[]}catch(e){throw new Error(`Failed to get processIds from cluster: ${e instanceof Error?e.message:String(e)}`)}};const r=n(45584),i=n(14052);function o(e){return e?new i.ConnectionString(e).hosts:[]}function a(e){return{name:e.name,instanceType:"FLEX",instanceSize:void 0,state:e.stateName,mongoDBVersion:e.mongoDBVersion,connectionStrings:e.connectionStrings,processIds:o(e.connectionStrings?.standard??"")}}function s(e){const t=(e.replicationSpecs||[]).map((e=>e.regionConfigs||[])).flat().map((e=>({providerName:e.providerName,instanceSize:e.electableSpecs?.instanceSize||e.readOnlySpecs?.instanceSize||e.analyticsSpecs?.instanceSize}))),n=t[0]?.instanceSize??"UNKNOWN",r="M0"===n?"FREE":"DEDICATED";return{name:e.name,instanceType:r,instanceSize:"DEDICATED"===r?n:void 0,state:e.stateName,mongoDBVersion:e.mongoDBVersion,connectionStrings:e.connectionStrings,processIds:o(e.connectionStrings?.standard??"")}}async function c(e,t,n){try{return s(await e.getCluster({params:{path:{groupId:t,clusterName:n}}}))}catch(i){try{return a(await e.getFlexCluster({params:{path:{groupId:t,name:n}}}))}catch(t){const n=t instanceof Error?t:new Error(String(t));throw e.logger.error({id:r.LogId.atlasInspectFailure,context:"inspect-cluster",message:`error inspecting cluster: ${n.message}`}),i}}}},30098:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(78249),i=n(87351),o=n(89689),a=n(98245),s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>r.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>r._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:n,it:r}=e,{prefixItems:s}=n;r.items=!0,(0,i.alwaysValidSchema)(r,t)||(s?(0,a.validateAdditionalItems)(e,s):e.ok((0,o.validateArray)(e)))}};t.default=s},30784:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SwitchConnectionTool=t.DropIndexTool=t.ExportTool=t.LogsTool=t.CreateCollectionTool=t.ExplainTool=t.DropCollectionTool=t.DropDatabaseTool=t.RenameCollectionTool=t.UpdateManyTool=t.AggregateTool=t.DbStatsTool=t.CountTool=t.CollectionStorageSizeTool=t.DeleteManyTool=t.InsertManyTool=t.FindTool=t.CollectionSchemaTool=t.CreateIndexTool=t.ListDatabasesTool=t.CollectionIndexesTool=t.ListCollectionsTool=t.ConnectTool=void 0;var r=n(3668);Object.defineProperty(t,"ConnectTool",{enumerable:!0,get:function(){return r.ConnectTool}});var i=n(43376);Object.defineProperty(t,"ListCollectionsTool",{enumerable:!0,get:function(){return i.ListCollectionsTool}});var o=n(47437);Object.defineProperty(t,"CollectionIndexesTool",{enumerable:!0,get:function(){return o.CollectionIndexesTool}});var a=n(77107);Object.defineProperty(t,"ListDatabasesTool",{enumerable:!0,get:function(){return a.ListDatabasesTool}});var s=n(70444);Object.defineProperty(t,"CreateIndexTool",{enumerable:!0,get:function(){return s.CreateIndexTool}});var c=n(21570);Object.defineProperty(t,"CollectionSchemaTool",{enumerable:!0,get:function(){return c.CollectionSchemaTool}});var u=n(32665);Object.defineProperty(t,"FindTool",{enumerable:!0,get:function(){return u.FindTool}});var l=n(58272);Object.defineProperty(t,"InsertManyTool",{enumerable:!0,get:function(){return l.InsertManyTool}});var h=n(92983);Object.defineProperty(t,"DeleteManyTool",{enumerable:!0,get:function(){return h.DeleteManyTool}});var f=n(55101);Object.defineProperty(t,"CollectionStorageSizeTool",{enumerable:!0,get:function(){return f.CollectionStorageSizeTool}});var d=n(9015);Object.defineProperty(t,"CountTool",{enumerable:!0,get:function(){return d.CountTool}});var g=n(43052);Object.defineProperty(t,"DbStatsTool",{enumerable:!0,get:function(){return g.DbStatsTool}});var p=n(43443);Object.defineProperty(t,"AggregateTool",{enumerable:!0,get:function(){return p.AggregateTool}});var b=n(17179);Object.defineProperty(t,"UpdateManyTool",{enumerable:!0,get:function(){return b.UpdateManyTool}});var m=n(13511);Object.defineProperty(t,"RenameCollectionTool",{enumerable:!0,get:function(){return m.RenameCollectionTool}});var w=n(3131);Object.defineProperty(t,"DropDatabaseTool",{enumerable:!0,get:function(){return w.DropDatabaseTool}});var v=n(2622);Object.defineProperty(t,"DropCollectionTool",{enumerable:!0,get:function(){return v.DropCollectionTool}});var y=n(75966);Object.defineProperty(t,"ExplainTool",{enumerable:!0,get:function(){return y.ExplainTool}});var S=n(11062);Object.defineProperty(t,"CreateCollectionTool",{enumerable:!0,get:function(){return S.CreateCollectionTool}});var k=n(77854);Object.defineProperty(t,"LogsTool",{enumerable:!0,get:function(){return k.LogsTool}});var E=n(20644);Object.defineProperty(t,"ExportTool",{enumerable:!0,get:function(){return E.ExportTool}});var x=n(74964);Object.defineProperty(t,"DropIndexTool",{enumerable:!0,get:function(){return x.DropIndexTool}});var M=n(46096);Object.defineProperty(t,"SwitchConnectionTool",{enumerable:!0,get:function(){return M.SwitchConnectionTool}})},31022:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldPath=function(e,t,i){const o=t.split(".");if(o.some((e=>!e.trim())))throw new Error(`Invalid field path: '${t}'`);if(o.length>n)throw new Error(`Field path "${t}" has too many nested levels (maximum ${n} allowed).`);r(e,o,i,"")};const n=100;function r(e,t,n,o){const[a,...s]=t;if(!a)throw new Error(`Cannot set field at provided path: Unexpected empty key - '${a}' in field path.`);if(0===s.length)return void i(e,a,n);const c=o?`${o}.${a}`:a,u=Object.prototype.hasOwnProperty.call(e,a)?e[a]:void 0;if(null==u)i(e,a,{});else if("object"!=typeof u||Array.isArray(u))throw new Error(`Cannot set field at provided path: intermediate path '${c}' is not an object.`);r(e[a],s,n,c)}function i(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}},31999:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(78249),i=n(87351),o=n(12798),a={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>r._`{allowedValues: ${e}}`},code(e){const{gen:t,data:n,$data:a,schema:s,schemaCode:c,it:u}=e;if(!a&&0===s.length)throw new Error("enum must have non-empty array");const l=s.length>=u.opts.loopEnum;let h;const f=()=>null!=h?h:h=(0,i.useFunc)(t,o.default);let d;if(l||a)d=t.let("valid"),e.block$data(d,(function(){t.assign(d,!1),t.forOf("v",c,(e=>t.if(r._`${f()}(${n}, ${e})`,(()=>t.assign(d,!0).break()))))}));else{if(!Array.isArray(s))throw new Error("ajv implementation error");const e=t.const("vSchema",c);d=(0,r.or)(...s.map(((t,i)=>function(e,t){const i=s[t];return"object"==typeof i&&null!==i?r._`${f()}(${n}, ${e}[${t}])`:r._`${n} === ${i}`}(e,i))))}e.pass(d)}};t.default=a},32665:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FindTool=t.FindArgs=void 0;const r=n(69761),i=n(58203),o=n(77710),a=n(49446),s=n(62444),c=n(92639),u=n(86463),l=n(18253),h=n(14233),f=n(45584);t.FindArgs={filter:(0,h.zEJSON)().optional().describe("The query filter, matching the syntax of the query argument of db.collection.find()"),projection:r.z.object({}).passthrough().optional().describe("The projection, matching the syntax of the projection argument of db.collection.find()"),limit:r.z.number().optional().default(10).describe("The maximum number of documents to return"),sort:r.z.object({}).catchall(r.z.custom()).optional().describe("A document, describing the sort order, matching the syntax of the sort argument of cursor.sort(). The keys of the object are the fields to sort on, while the values are the sort directions (1 for ascending, -1 for descending).")};class d extends i.MongoDBToolBase{constructor(){super(...arguments),this.name="find",this.description="Run a find query against a MongoDB collection",this.argsShape={...i.DbOperationArgs,...t.FindArgs,responseBytesLimit:r.z.number().optional().default(l.ONE_MB).describe('The maximum number of bytes to return in the response. This value is capped by the server\'s configured maxBytesPerQuery and cannot be exceeded. Note to LLM: If the entire query result is required, use the "export" tool instead of increasing this limit.')}}async execute({database:e,collection:t,filter:n,projection:r,limit:i,sort:h,responseBytesLimit:f},{signal:d}){let g;try{const p=await this.ensureConnected();this.config.indexCheck&&await(0,a.checkIndexUsage)({database:e,collection:t,operation:"find",explainCallback:async()=>p.find(e,t,n,{projection:r,limit:i,sort:h,signal:d}).explain("queryPlanner"),logger:this.session.logger});const b=this.getLimitForFindCursor(i);g=p.find(e,t,n,{projection:r,limit:b.limit,sort:h,signal:d});const[m,w]=await Promise.all([(0,u.operationWithFallback)((()=>p.countDocuments(e,t,n,{limit:i,maxTimeMS:l.QUERY_COUNT_MAX_TIME_MS_CAP,signal:d})),void 0),(0,c.collectCursorUntilMaxBytesLimit)({cursor:g,configuredMaxBytesPerQuery:this.config.maxBytesPerQuery,toolResponseBytesLimit:f,abortSignal:d})]);return{content:(0,o.formatUntrustedData)(this.generateMessage({collection:t,queryResultsCount:m,documents:w.documents,appliedLimits:[b.cappedBy,w.cappedBy].filter((e=>!!e))}),...w.documents.length>0?[s.EJSON.stringify(w.documents)]:[])}}finally{g&&this.safeCloseCursor(g)}}async safeCloseCursor(e){try{await e.close()}catch(e){this.session.logger.warning({id:f.LogId.mongodbCursorCloseError,context:"find tool",message:`Error when closing the cursor - ${e instanceof Error?e.message:String(e)}`})}}generateMessage({collection:e,queryResultsCount:t,documents:n,appliedLimits:r}){const i=r.length?`while respecting the applied limits of ${r.map((e=>l.CURSOR_LIMITS_TO_LLM_TEXT[e])).join(", ")}. Note to LLM: If the entire query result is required then use "export" tool to export the query results.`:"";return`Query on collection "${e}" resulted in ${void 0===t?"indeterminable number of":t} documents. Returning ${n.length} documents${i?` ${i}`:"."}`}getLimitForFindCursor(e){const t=parseInt(String(this.config.maxDocumentsPerQuery),10);return Number.isNaN(t)||t<=0?{cappedBy:void 0,limit:e??void 0}:null==e?{cappedBy:"config.maxDocumentsPerQuery",limit:t}:{cappedBy:t<e?"config.maxDocumentsPerQuery":void 0,limit:Math.min(e,t)}}}t.FindTool=d,d.operationType="read"},32674:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setAppNameParamIfMissing=async function({connectionString:e,components:t}){const n=new r.ConnectionString(e),i=n.typedSearchParams();if(i.has("appName"))return n.toString();const o=`${t.appName||"unknown"}--${t.deviceId?await t.deviceId:"unknown"}--${t.clientName||"unknown"}`;return i.set("appName",o),n.toString()},t.validateConnectionString=function(e,t){try{new r.ConnectionString(e,{looseValidation:t})}catch(e){throw new Error(`Invalid connection string with error: ${e instanceof Error?e.message:String(e)}`)}};const r=n(14052)},32781:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectDeploymentTool=void 0;const r=n(66473),i=n(14233);class o extends r.AtlasLocalToolBase{constructor(){super(...arguments),this.name="atlas-local-connect-deployment",this.description="Connect to a MongoDB Atlas Local deployment",this.argsShape={deploymentName:i.CommonArgs.string().describe("Name of the deployment to connect to")}}async executeWithAtlasLocalClient({deploymentName:e},{client:t}){const n=await t.getConnectionString(e);return await this.session.connectToMongoDB({connectionString:n}),{content:[{type:"text",text:`Successfully connected to Atlas Local deployment "${e}".`}],_meta:{...await this.lookupTelemetryMetadata(t,e)}}}resolveTelemetryMetadata(e,{result:t}){return{...super.resolveTelemetryMetadata(e,{result:t}),...this.getConnectionInfoMetadata()}}}t.ConnectDeploymentTool=o,o.operationType="connect"},33168:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.toTypescriptTypeDefinition=t.schemaStats=t.SchemaAnalyzer=t.getSimplifiedSchema=t.getSchemaPaths=t.analyzeDocuments=t.parseSchema=void 0;const a=n(37057),s=n(75996);Object.defineProperty(t,"SchemaAnalyzer",{enumerable:!0,get:function(){return s.SchemaAnalyzer}});const c=n(79059),u=n(59942),l=n(61283),h=o(n(33787));t.schemaStats=h;const f=n(33859);async function d(e,t){return(await(0,s.getCompletedSchemaAnalyzer)(e,t)).getResult()}Object.defineProperty(t,"toTypescriptTypeDefinition",{enumerable:!0,get:function(){return f.toTypescriptTypeDefinition}}),t.analyzeDocuments=async function(e,t){const n=(await(0,s.getCompletedSchemaAnalyzer)(e,t)).getResult();return new a.InternalSchemaBasedAccessor(n,{internalToStandard:l.convertInternalToStandard,internalToMongoDB:u.convertInternalToMongodb,internalToExpanded:c.convertInternalToExpanded})},t.parseSchema=d,t.getSchemaPaths=async function(e){return(await(0,s.getCompletedSchemaAnalyzer)(e)).getSchemaPaths()},t.getSimplifiedSchema=async function(e){return(await(0,s.getCompletedSchemaAnalyzer)(e)).getSimplifiedSchema()},t.default=d},33433:function(e,t,n){!function(e,t){function r(e,t){if(!e)throw new Error(t||"Assertion failed")}function i(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}function o(e,t,n){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(n=t,t=10),this._init(e||0,t||10,n||"be"))}var a;"object"==typeof e?e.exports=o:t.BN=o,o.BN=o,o.wordSize=26;try{a="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:n(67787).Buffer}catch(e){}function s(e,t){var n=e.charCodeAt(t);return n>=65&&n<=70?n-55:n>=97&&n<=102?n-87:n-48&15}function c(e,t,n){var r=s(e,n);return n-1>=t&&(r|=s(e,n-1)<<4),r}function u(e,t,n,r){for(var i=0,o=Math.min(e.length,n),a=t;a<o;a++){var s=e.charCodeAt(a)-48;i*=r,i+=s>=49?s-49+10:s>=17?s-17+10:s}return i}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,n){if("number"==typeof e)return this._initNumber(e,t,n);if("object"==typeof e)return this._initArray(e,t,n);"hex"===t&&(t=16),r(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i<e.length&&(16===t?this._parseHex(e,i,n):(this._parseBase(e,t,i),"le"===n&&this._initArray(this.toArray(),t,n)))},o.prototype._initNumber=function(e,t,n){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(r(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),t,n)},o.prototype._initArray=function(e,t,n){if(r("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var o,a,s=0;if("be"===n)for(i=e.length-1,o=0;i>=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<<s&67108863,this.words[o+1]=a>>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===n)for(i=0,o=0;i<e.length;i+=3)a=e[i]|e[i+1]<<8|e[i+2]<<16,this.words[o]|=a<<s&67108863,this.words[o+1]=a>>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t,n){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r<this.length;r++)this.words[r]=0;var i,o=0,a=0;if("be"===n)for(r=e.length-1;r>=t;r-=2)i=c(e,t,r)<<o,this.words[a]|=67108863&i,o>=18?(o-=18,a+=1,this.words[a]|=i>>>26):o+=8;else for(r=(e.length-t)%2==0?t+1:t;r<e.length;r+=2)i=c(e,t,r)<<o,this.words[a]|=67108863&i,o>=18?(o-=18,a+=1,this.words[a]|=i>>>26):o+=8;this.strip()},o.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,i=1;i<=67108863;i*=t)r++;r--,i=i/t|0;for(var o=e.length-n,a=o%r,s=Math.min(o,o-a)+n,c=0,l=n;l<s;l+=r)c=u(e,l,l+r,t),this.imuln(i),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c);if(0!==a){var h=1;for(c=u(e,l,e.length,t),l=0;l<a;l++)h*=t;this.imuln(h),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c)}this.strip()},o.prototype.copy=function(e){e.words=new Array(this.length);for(var t=0;t<this.length;t++)e.words[t]=this.words[t];e.length=this.length,e.negative=this.negative,e.red=this.red},o.prototype.clone=function(){var e=new o(null);return this.copy(e),e},o.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},o.prototype.strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var l=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],h=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],f=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function d(e,t,n){n.negative=t.negative^e.negative;var r=e.length+t.length|0;n.length=r,r=r-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,c=a/67108864|0;n.words[0]=s;for(var u=1;u<r;u++){for(var l=c>>>26,h=67108863&c,f=Math.min(u,t.length-1),d=Math.max(0,u-e.length+1);d<=f;d++){var g=u-d|0;l+=(a=(i=0|e.words[g])*(o=0|t.words[d])+h)/67108864|0,h=67108863&a}n.words[u]=0|h,c=0|l}return 0!==c?n.words[u]=0|c:n.length--,n.strip()}o.prototype.toString=function(e,t){var n;if(t=0|t||1,16===(e=e||10)||"hex"===e){n="";for(var i=0,o=0,a=0;a<this.length;a++){var s=this.words[a],c=(16777215&(s<<i|o)).toString(16);n=0!=(o=s>>>24-i&16777215)||a!==this.length-1?l[6-c.length]+c+n:c+n,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(n=o.toString(16)+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(e===(0|e)&&e>=2&&e<=36){var u=h[e],d=f[e];n="";var g=this.clone();for(g.negative=0;!g.isZero();){var p=g.modn(d).toString(e);n=(g=g.idivn(d)).isZero()?p+n:l[u-p.length]+p+n}for(this.isZero()&&(n="0"+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return r(void 0!==a),this.toArrayLike(a,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var a,s,c="le"===t,u=new e(o),l=this.clone();if(c){for(s=0;!l.isZero();s++)a=l.andln(255),l.iushrn(8),u[s]=a;for(;s<o;s++)u[s]=0}else{for(s=0;s<o-i;s++)u[s]=0;for(s=0;!l.isZero();s++)a=l.andln(255),l.iushrn(8),u[o-s-1]=a}return u},Math.clz32?o.prototype._countBits=function(e){return 32-Math.clz32(e)}:o.prototype._countBits=function(e){var t=e,n=0;return t>=4096&&(n+=13,t>>>=13),t>=64&&(n+=7,t>>>=7),t>=8&&(n+=4,t>>>=4),t>=2&&(n+=2,t>>>=2),n+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,n=0;return 8191&t||(n+=13,t>>>=13),127&t||(n+=7,t>>>=7),15&t||(n+=4,t>>>=4),3&t||(n+=2,t>>>=2),1&t||n++,n},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;t<this.length;t++){var n=this._zeroBits(this.words[t]);if(e+=n,26!==n)break}return e},o.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},o.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},o.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},o.prototype.isNeg=function(){return 0!==this.negative},o.prototype.neg=function(){return this.clone().ineg()},o.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},o.prototype.iuor=function(e){for(;this.length<e.length;)this.words[this.length++]=0;for(var t=0;t<e.length;t++)this.words[t]=this.words[t]|e.words[t];return this.strip()},o.prototype.ior=function(e){return r(!(this.negative|e.negative)),this.iuor(e)},o.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var n=0;n<t.length;n++)this.words[n]=this.words[n]&e.words[n];return this.length=t.length,this.strip()},o.prototype.iand=function(e){return r(!(this.negative|e.negative)),this.iuand(e)},o.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var r=0;r<n.length;r++)this.words[r]=t.words[r]^n.words[r];if(this!==t)for(;r<t.length;r++)this.words[r]=t.words[r];return this.length=t.length,this.strip()},o.prototype.ixor=function(e){return r(!(this.negative|e.negative)),this.iuxor(e)},o.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){r("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),n=e%26;this._expand(t),n>0&&t--;for(var i=0;i<t;i++)this.words[i]=67108863&~this.words[i];return n>0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){r("number"==typeof e&&e>=0);var n=e/26|0,i=e%26;return this._expand(n+1),this.words[n]=t?this.words[n]|1<<i:this.words[n]&~(1<<i),this.strip()},o.prototype.iadd=function(e){var t,n,r;if(0!==this.negative&&0===e.negative)return this.negative=0,t=this.isub(e),this.negative^=1,this._normSign();if(0===this.negative&&0!==e.negative)return e.negative=0,t=this.isub(e),e.negative=1,t._normSign();this.length>e.length?(n=this,r=e):(n=e,r=this);for(var i=0,o=0;o<r.length;o++)t=(0|n.words[o])+(0|r.words[o])+i,this.words[o]=67108863&t,i=t>>>26;for(;0!==i&&o<n.length;o++)t=(0|n.words[o])+i,this.words[o]=67108863&t,i=t>>>26;if(this.length=n.length,0!==i)this.words[this.length]=i,this.length++;else if(n!==this)for(;o<n.length;o++)this.words[o]=n.words[o];return this},o.prototype.add=function(e){var t;return 0!==e.negative&&0===this.negative?(e.negative=0,t=this.sub(e),e.negative^=1,t):0===e.negative&&0!==this.negative?(this.negative=0,t=e.sub(this),this.negative=1,t):this.length>e.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var n,r,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(n=this,r=e):(n=e,r=this);for(var o=0,a=0;a<r.length;a++)o=(t=(0|n.words[a])-(0|r.words[a])+o)>>26,this.words[a]=67108863&t;for(;0!==o&&a<n.length;a++)o=(t=(0|n.words[a])+o)>>26,this.words[a]=67108863&t;if(0===o&&a<n.length&&n!==this)for(;a<n.length;a++)this.words[a]=n.words[a];return this.length=Math.max(this.length,a),n!==this&&(this.negative=1),this.strip()},o.prototype.sub=function(e){return this.clone().isub(e)};var g=function(e,t,n){var r,i,o,a=e.words,s=t.words,c=n.words,u=0,l=0|a[0],h=8191&l,f=l>>>13,d=0|a[1],g=8191&d,p=d>>>13,b=0|a[2],m=8191&b,w=b>>>13,v=0|a[3],y=8191&v,S=v>>>13,k=0|a[4],E=8191&k,x=k>>>13,M=0|a[5],T=8191&M,C=M>>>13,_=0|a[6],P=8191&_,I=_>>>13,A=0|a[7],O=8191&A,j=A>>>13,$=0|a[8],R=8191&$,N=$>>>13,L=0|a[9],D=8191&L,F=L>>>13,B=0|s[0],z=8191&B,U=B>>>13,q=0|s[1],H=8191&q,J=q>>>13,G=0|s[2],V=8191&G,K=G>>>13,W=0|s[3],X=8191&W,Y=W>>>13,Q=0|s[4],Z=8191&Q,ee=Q>>>13,te=0|s[5],ne=8191&te,re=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ce=8191&se,ue=se>>>13,le=0|s[8],he=8191&le,fe=le>>>13,de=0|s[9],ge=8191&de,pe=de>>>13;n.negative=e.negative^t.negative,n.length=19;var be=(u+(r=Math.imul(h,z))|0)+((8191&(i=(i=Math.imul(h,U))+Math.imul(f,z)|0))<<13)|0;u=((o=Math.imul(f,U))+(i>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(g,z),i=(i=Math.imul(g,U))+Math.imul(p,z)|0,o=Math.imul(p,U);var me=(u+(r=r+Math.imul(h,H)|0)|0)+((8191&(i=(i=i+Math.imul(h,J)|0)+Math.imul(f,H)|0))<<13)|0;u=((o=o+Math.imul(f,J)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,r=Math.imul(m,z),i=(i=Math.imul(m,U))+Math.imul(w,z)|0,o=Math.imul(w,U),r=r+Math.imul(g,H)|0,i=(i=i+Math.imul(g,J)|0)+Math.imul(p,H)|0,o=o+Math.imul(p,J)|0;var we=(u+(r=r+Math.imul(h,V)|0)|0)+((8191&(i=(i=i+Math.imul(h,K)|0)+Math.imul(f,V)|0))<<13)|0;u=((o=o+Math.imul(f,K)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(y,z),i=(i=Math.imul(y,U))+Math.imul(S,z)|0,o=Math.imul(S,U),r=r+Math.imul(m,H)|0,i=(i=i+Math.imul(m,J)|0)+Math.imul(w,H)|0,o=o+Math.imul(w,J)|0,r=r+Math.imul(g,V)|0,i=(i=i+Math.imul(g,K)|0)+Math.imul(p,V)|0,o=o+Math.imul(p,K)|0;var ve=(u+(r=r+Math.imul(h,X)|0)|0)+((8191&(i=(i=i+Math.imul(h,Y)|0)+Math.imul(f,X)|0))<<13)|0;u=((o=o+Math.imul(f,Y)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(E,z),i=(i=Math.imul(E,U))+Math.imul(x,z)|0,o=Math.imul(x,U),r=r+Math.imul(y,H)|0,i=(i=i+Math.imul(y,J)|0)+Math.imul(S,H)|0,o=o+Math.imul(S,J)|0,r=r+Math.imul(m,V)|0,i=(i=i+Math.imul(m,K)|0)+Math.imul(w,V)|0,o=o+Math.imul(w,K)|0,r=r+Math.imul(g,X)|0,i=(i=i+Math.imul(g,Y)|0)+Math.imul(p,X)|0,o=o+Math.imul(p,Y)|0;var ye=(u+(r=r+Math.imul(h,Z)|0)|0)+((8191&(i=(i=i+Math.imul(h,ee)|0)+Math.imul(f,Z)|0))<<13)|0;u=((o=o+Math.imul(f,ee)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(T,z),i=(i=Math.imul(T,U))+Math.imul(C,z)|0,o=Math.imul(C,U),r=r+Math.imul(E,H)|0,i=(i=i+Math.imul(E,J)|0)+Math.imul(x,H)|0,o=o+Math.imul(x,J)|0,r=r+Math.imul(y,V)|0,i=(i=i+Math.imul(y,K)|0)+Math.imul(S,V)|0,o=o+Math.imul(S,K)|0,r=r+Math.imul(m,X)|0,i=(i=i+Math.imul(m,Y)|0)+Math.imul(w,X)|0,o=o+Math.imul(w,Y)|0,r=r+Math.imul(g,Z)|0,i=(i=i+Math.imul(g,ee)|0)+Math.imul(p,Z)|0,o=o+Math.imul(p,ee)|0;var Se=(u+(r=r+Math.imul(h,ne)|0)|0)+((8191&(i=(i=i+Math.imul(h,re)|0)+Math.imul(f,ne)|0))<<13)|0;u=((o=o+Math.imul(f,re)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(P,z),i=(i=Math.imul(P,U))+Math.imul(I,z)|0,o=Math.imul(I,U),r=r+Math.imul(T,H)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(C,H)|0,o=o+Math.imul(C,J)|0,r=r+Math.imul(E,V)|0,i=(i=i+Math.imul(E,K)|0)+Math.imul(x,V)|0,o=o+Math.imul(x,K)|0,r=r+Math.imul(y,X)|0,i=(i=i+Math.imul(y,Y)|0)+Math.imul(S,X)|0,o=o+Math.imul(S,Y)|0,r=r+Math.imul(m,Z)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(w,Z)|0,o=o+Math.imul(w,ee)|0,r=r+Math.imul(g,ne)|0,i=(i=i+Math.imul(g,re)|0)+Math.imul(p,ne)|0,o=o+Math.imul(p,re)|0;var ke=(u+(r=r+Math.imul(h,oe)|0)|0)+((8191&(i=(i=i+Math.imul(h,ae)|0)+Math.imul(f,oe)|0))<<13)|0;u=((o=o+Math.imul(f,ae)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(O,z),i=(i=Math.imul(O,U))+Math.imul(j,z)|0,o=Math.imul(j,U),r=r+Math.imul(P,H)|0,i=(i=i+Math.imul(P,J)|0)+Math.imul(I,H)|0,o=o+Math.imul(I,J)|0,r=r+Math.imul(T,V)|0,i=(i=i+Math.imul(T,K)|0)+Math.imul(C,V)|0,o=o+Math.imul(C,K)|0,r=r+Math.imul(E,X)|0,i=(i=i+Math.imul(E,Y)|0)+Math.imul(x,X)|0,o=o+Math.imul(x,Y)|0,r=r+Math.imul(y,Z)|0,i=(i=i+Math.imul(y,ee)|0)+Math.imul(S,Z)|0,o=o+Math.imul(S,ee)|0,r=r+Math.imul(m,ne)|0,i=(i=i+Math.imul(m,re)|0)+Math.imul(w,ne)|0,o=o+Math.imul(w,re)|0,r=r+Math.imul(g,oe)|0,i=(i=i+Math.imul(g,ae)|0)+Math.imul(p,oe)|0,o=o+Math.imul(p,ae)|0;var Ee=(u+(r=r+Math.imul(h,ce)|0)|0)+((8191&(i=(i=i+Math.imul(h,ue)|0)+Math.imul(f,ce)|0))<<13)|0;u=((o=o+Math.imul(f,ue)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(R,z),i=(i=Math.imul(R,U))+Math.imul(N,z)|0,o=Math.imul(N,U),r=r+Math.imul(O,H)|0,i=(i=i+Math.imul(O,J)|0)+Math.imul(j,H)|0,o=o+Math.imul(j,J)|0,r=r+Math.imul(P,V)|0,i=(i=i+Math.imul(P,K)|0)+Math.imul(I,V)|0,o=o+Math.imul(I,K)|0,r=r+Math.imul(T,X)|0,i=(i=i+Math.imul(T,Y)|0)+Math.imul(C,X)|0,o=o+Math.imul(C,Y)|0,r=r+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(x,Z)|0,o=o+Math.imul(x,ee)|0,r=r+Math.imul(y,ne)|0,i=(i=i+Math.imul(y,re)|0)+Math.imul(S,ne)|0,o=o+Math.imul(S,re)|0,r=r+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,ae)|0)+Math.imul(w,oe)|0,o=o+Math.imul(w,ae)|0,r=r+Math.imul(g,ce)|0,i=(i=i+Math.imul(g,ue)|0)+Math.imul(p,ce)|0,o=o+Math.imul(p,ue)|0;var xe=(u+(r=r+Math.imul(h,he)|0)|0)+((8191&(i=(i=i+Math.imul(h,fe)|0)+Math.imul(f,he)|0))<<13)|0;u=((o=o+Math.imul(f,fe)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(D,z),i=(i=Math.imul(D,U))+Math.imul(F,z)|0,o=Math.imul(F,U),r=r+Math.imul(R,H)|0,i=(i=i+Math.imul(R,J)|0)+Math.imul(N,H)|0,o=o+Math.imul(N,J)|0,r=r+Math.imul(O,V)|0,i=(i=i+Math.imul(O,K)|0)+Math.imul(j,V)|0,o=o+Math.imul(j,K)|0,r=r+Math.imul(P,X)|0,i=(i=i+Math.imul(P,Y)|0)+Math.imul(I,X)|0,o=o+Math.imul(I,Y)|0,r=r+Math.imul(T,Z)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(C,Z)|0,o=o+Math.imul(C,ee)|0,r=r+Math.imul(E,ne)|0,i=(i=i+Math.imul(E,re)|0)+Math.imul(x,ne)|0,o=o+Math.imul(x,re)|0,r=r+Math.imul(y,oe)|0,i=(i=i+Math.imul(y,ae)|0)+Math.imul(S,oe)|0,o=o+Math.imul(S,ae)|0,r=r+Math.imul(m,ce)|0,i=(i=i+Math.imul(m,ue)|0)+Math.imul(w,ce)|0,o=o+Math.imul(w,ue)|0,r=r+Math.imul(g,he)|0,i=(i=i+Math.imul(g,fe)|0)+Math.imul(p,he)|0,o=o+Math.imul(p,fe)|0;var Me=(u+(r=r+Math.imul(h,ge)|0)|0)+((8191&(i=(i=i+Math.imul(h,pe)|0)+Math.imul(f,ge)|0))<<13)|0;u=((o=o+Math.imul(f,pe)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,r=Math.imul(D,H),i=(i=Math.imul(D,J))+Math.imul(F,H)|0,o=Math.imul(F,J),r=r+Math.imul(R,V)|0,i=(i=i+Math.imul(R,K)|0)+Math.imul(N,V)|0,o=o+Math.imul(N,K)|0,r=r+Math.imul(O,X)|0,i=(i=i+Math.imul(O,Y)|0)+Math.imul(j,X)|0,o=o+Math.imul(j,Y)|0,r=r+Math.imul(P,Z)|0,i=(i=i+Math.imul(P,ee)|0)+Math.imul(I,Z)|0,o=o+Math.imul(I,ee)|0,r=r+Math.imul(T,ne)|0,i=(i=i+Math.imul(T,re)|0)+Math.imul(C,ne)|0,o=o+Math.imul(C,re)|0,r=r+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,ae)|0,r=r+Math.imul(y,ce)|0,i=(i=i+Math.imul(y,ue)|0)+Math.imul(S,ce)|0,o=o+Math.imul(S,ue)|0,r=r+Math.imul(m,he)|0,i=(i=i+Math.imul(m,fe)|0)+Math.imul(w,he)|0,o=o+Math.imul(w,fe)|0;var Te=(u+(r=r+Math.imul(g,ge)|0)|0)+((8191&(i=(i=i+Math.imul(g,pe)|0)+Math.imul(p,ge)|0))<<13)|0;u=((o=o+Math.imul(p,pe)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(D,V),i=(i=Math.imul(D,K))+Math.imul(F,V)|0,o=Math.imul(F,K),r=r+Math.imul(R,X)|0,i=(i=i+Math.imul(R,Y)|0)+Math.imul(N,X)|0,o=o+Math.imul(N,Y)|0,r=r+Math.imul(O,Z)|0,i=(i=i+Math.imul(O,ee)|0)+Math.imul(j,Z)|0,o=o+Math.imul(j,ee)|0,r=r+Math.imul(P,ne)|0,i=(i=i+Math.imul(P,re)|0)+Math.imul(I,ne)|0,o=o+Math.imul(I,re)|0,r=r+Math.imul(T,oe)|0,i=(i=i+Math.imul(T,ae)|0)+Math.imul(C,oe)|0,o=o+Math.imul(C,ae)|0,r=r+Math.imul(E,ce)|0,i=(i=i+Math.imul(E,ue)|0)+Math.imul(x,ce)|0,o=o+Math.imul(x,ue)|0,r=r+Math.imul(y,he)|0,i=(i=i+Math.imul(y,fe)|0)+Math.imul(S,he)|0,o=o+Math.imul(S,fe)|0;var Ce=(u+(r=r+Math.imul(m,ge)|0)|0)+((8191&(i=(i=i+Math.imul(m,pe)|0)+Math.imul(w,ge)|0))<<13)|0;u=((o=o+Math.imul(w,pe)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(D,X),i=(i=Math.imul(D,Y))+Math.imul(F,X)|0,o=Math.imul(F,Y),r=r+Math.imul(R,Z)|0,i=(i=i+Math.imul(R,ee)|0)+Math.imul(N,Z)|0,o=o+Math.imul(N,ee)|0,r=r+Math.imul(O,ne)|0,i=(i=i+Math.imul(O,re)|0)+Math.imul(j,ne)|0,o=o+Math.imul(j,re)|0,r=r+Math.imul(P,oe)|0,i=(i=i+Math.imul(P,ae)|0)+Math.imul(I,oe)|0,o=o+Math.imul(I,ae)|0,r=r+Math.imul(T,ce)|0,i=(i=i+Math.imul(T,ue)|0)+Math.imul(C,ce)|0,o=o+Math.imul(C,ue)|0,r=r+Math.imul(E,he)|0,i=(i=i+Math.imul(E,fe)|0)+Math.imul(x,he)|0,o=o+Math.imul(x,fe)|0;var _e=(u+(r=r+Math.imul(y,ge)|0)|0)+((8191&(i=(i=i+Math.imul(y,pe)|0)+Math.imul(S,ge)|0))<<13)|0;u=((o=o+Math.imul(S,pe)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(D,Z),i=(i=Math.imul(D,ee))+Math.imul(F,Z)|0,o=Math.imul(F,ee),r=r+Math.imul(R,ne)|0,i=(i=i+Math.imul(R,re)|0)+Math.imul(N,ne)|0,o=o+Math.imul(N,re)|0,r=r+Math.imul(O,oe)|0,i=(i=i+Math.imul(O,ae)|0)+Math.imul(j,oe)|0,o=o+Math.imul(j,ae)|0,r=r+Math.imul(P,ce)|0,i=(i=i+Math.imul(P,ue)|0)+Math.imul(I,ce)|0,o=o+Math.imul(I,ue)|0,r=r+Math.imul(T,he)|0,i=(i=i+Math.imul(T,fe)|0)+Math.imul(C,he)|0,o=o+Math.imul(C,fe)|0;var Pe=(u+(r=r+Math.imul(E,ge)|0)|0)+((8191&(i=(i=i+Math.imul(E,pe)|0)+Math.imul(x,ge)|0))<<13)|0;u=((o=o+Math.imul(x,pe)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,r=Math.imul(D,ne),i=(i=Math.imul(D,re))+Math.imul(F,ne)|0,o=Math.imul(F,re),r=r+Math.imul(R,oe)|0,i=(i=i+Math.imul(R,ae)|0)+Math.imul(N,oe)|0,o=o+Math.imul(N,ae)|0,r=r+Math.imul(O,ce)|0,i=(i=i+Math.imul(O,ue)|0)+Math.imul(j,ce)|0,o=o+Math.imul(j,ue)|0,r=r+Math.imul(P,he)|0,i=(i=i+Math.imul(P,fe)|0)+Math.imul(I,he)|0,o=o+Math.imul(I,fe)|0;var Ie=(u+(r=r+Math.imul(T,ge)|0)|0)+((8191&(i=(i=i+Math.imul(T,pe)|0)+Math.imul(C,ge)|0))<<13)|0;u=((o=o+Math.imul(C,pe)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(D,oe),i=(i=Math.imul(D,ae))+Math.imul(F,oe)|0,o=Math.imul(F,ae),r=r+Math.imul(R,ce)|0,i=(i=i+Math.imul(R,ue)|0)+Math.imul(N,ce)|0,o=o+Math.imul(N,ue)|0,r=r+Math.imul(O,he)|0,i=(i=i+Math.imul(O,fe)|0)+Math.imul(j,he)|0,o=o+Math.imul(j,fe)|0;var Ae=(u+(r=r+Math.imul(P,ge)|0)|0)+((8191&(i=(i=i+Math.imul(P,pe)|0)+Math.imul(I,ge)|0))<<13)|0;u=((o=o+Math.imul(I,pe)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(D,ce),i=(i=Math.imul(D,ue))+Math.imul(F,ce)|0,o=Math.imul(F,ue),r=r+Math.imul(R,he)|0,i=(i=i+Math.imul(R,fe)|0)+Math.imul(N,he)|0,o=o+Math.imul(N,fe)|0;var Oe=(u+(r=r+Math.imul(O,ge)|0)|0)+((8191&(i=(i=i+Math.imul(O,pe)|0)+Math.imul(j,ge)|0))<<13)|0;u=((o=o+Math.imul(j,pe)|0)+(i>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,r=Math.imul(D,he),i=(i=Math.imul(D,fe))+Math.imul(F,he)|0,o=Math.imul(F,fe);var je=(u+(r=r+Math.imul(R,ge)|0)|0)+((8191&(i=(i=i+Math.imul(R,pe)|0)+Math.imul(N,ge)|0))<<13)|0;u=((o=o+Math.imul(N,pe)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863;var $e=(u+(r=Math.imul(D,ge))|0)+((8191&(i=(i=Math.imul(D,pe))+Math.imul(F,ge)|0))<<13)|0;return u=((o=Math.imul(F,pe))+(i>>>13)|0)+($e>>>26)|0,$e&=67108863,c[0]=be,c[1]=me,c[2]=we,c[3]=ve,c[4]=ye,c[5]=Se,c[6]=ke,c[7]=Ee,c[8]=xe,c[9]=Me,c[10]=Te,c[11]=Ce,c[12]=_e,c[13]=Pe,c[14]=Ie,c[15]=Ae,c[16]=Oe,c[17]=je,c[18]=$e,0!==u&&(c[19]=u,n.length++),n};function p(e,t,n){return(new b).mulp(e,t,n)}function b(e,t){this.x=e,this.y=t}Math.imul||(g=d),o.prototype.mulTo=function(e,t){var n,r=this.length+e.length;return n=10===this.length&&10===e.length?g(this,e,t):r<63?d(this,e,t):r<1024?function(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,i=0,o=0;o<n.length-1;o++){var a=i;i=0;for(var s=67108863&r,c=Math.min(o,t.length-1),u=Math.max(0,o-e.length+1);u<=c;u++){var l=o-u,h=(0|e.words[l])*(0|t.words[u]),f=67108863&h;s=67108863&(f=f+s|0),i+=(a=(a=a+(h/67108864|0)|0)+(f>>>26)|0)>>>26,a&=67108863}n.words[o]=s,r=a,a=i}return 0!==r?n.words[o]=r:n.length--,n.strip()}(this,e,t):p(this,e,t),n},b.prototype.makeRBT=function(e){for(var t=new Array(e),n=o.prototype._countBits(e)-1,r=0;r<e;r++)t[r]=this.revBin(r,n,e);return t},b.prototype.revBin=function(e,t,n){if(0===e||e===n-1)return e;for(var r=0,i=0;i<t;i++)r|=(1&e)<<t-i-1,e>>=1;return r},b.prototype.permute=function(e,t,n,r,i,o){for(var a=0;a<o;a++)r[a]=t[e[a]],i[a]=n[e[a]]},b.prototype.transform=function(e,t,n,r,i,o){this.permute(o,e,t,n,r,i);for(var a=1;a<i;a<<=1)for(var s=a<<1,c=Math.cos(2*Math.PI/s),u=Math.sin(2*Math.PI/s),l=0;l<i;l+=s)for(var h=c,f=u,d=0;d<a;d++){var g=n[l+d],p=r[l+d],b=n[l+d+a],m=r[l+d+a],w=h*b-f*m;m=h*m+f*b,b=w,n[l+d]=g+b,r[l+d]=p+m,n[l+d+a]=g-b,r[l+d+a]=p-m,d!==s&&(w=c*h-u*f,f=c*f+u*h,h=w)}},b.prototype.guessLen13b=function(e,t){var n=1|Math.max(t,e),r=1&n,i=0;for(n=n/2|0;n;n>>>=1)i++;return 1<<i+1+r},b.prototype.conjugate=function(e,t,n){if(!(n<=1))for(var r=0;r<n/2;r++){var i=e[r];e[r]=e[n-r-1],e[n-r-1]=i,i=t[r],t[r]=-t[n-r-1],t[n-r-1]=-i}},b.prototype.normalize13b=function(e,t){for(var n=0,r=0;r<t/2;r++){var i=8192*Math.round(e[2*r+1]/t)+Math.round(e[2*r]/t)+n;e[r]=67108863&i,n=i<67108864?0:i/67108864|0}return e},b.prototype.convert13b=function(e,t,n,i){for(var o=0,a=0;a<t;a++)o+=0|e[a],n[2*a]=8191&o,o>>>=13,n[2*a+1]=8191&o,o>>>=13;for(a=2*t;a<i;++a)n[a]=0;r(0===o),r(!(-8192&o))},b.prototype.stub=function(e){for(var t=new Array(e),n=0;n<e;n++)t[n]=0;return t},b.prototype.mulp=function(e,t,n){var r=2*this.guessLen13b(e.length,t.length),i=this.makeRBT(r),o=this.stub(r),a=new Array(r),s=new Array(r),c=new Array(r),u=new Array(r),l=new Array(r),h=new Array(r),f=n.words;f.length=r,this.convert13b(e.words,e.length,a,r),this.convert13b(t.words,t.length,u,r),this.transform(a,o,s,c,r,i),this.transform(u,o,l,h,r,i);for(var d=0;d<r;d++){var g=s[d]*l[d]-c[d]*h[d];c[d]=s[d]*h[d]+c[d]*l[d],s[d]=g}return this.conjugate(s,c,r),this.transform(s,c,f,o,r,i),this.conjugate(f,o,r),this.normalize13b(f,r),n.negative=e.negative^t.negative,n.length=e.length+t.length,n.strip()},o.prototype.mul=function(e){var t=new o(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},o.prototype.mulf=function(e){var t=new o(null);return t.words=new Array(this.length+e.length),p(this,e,t)},o.prototype.imul=function(e){return this.clone().mulTo(e,this)},o.prototype.imuln=function(e){r("number"==typeof e),r(e<67108864);for(var t=0,n=0;n<this.length;n++){var i=(0|this.words[n])*e,o=(67108863&i)+(67108863&t);t>>=26,t+=i/67108864|0,t+=o>>>26,this.words[n]=67108863&o}return 0!==t&&(this.words[n]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n<t.length;n++){var r=n/26|0,i=n%26;t[n]=(e.words[r]&1<<i)>>>i}return t}(e);if(0===t.length)return new o(1);for(var n=this,r=0;r<t.length&&0===t[r];r++,n=n.sqr());if(++r<t.length)for(var i=n.sqr();r<t.length;r++,i=i.sqr())0!==t[r]&&(n=n.mul(i));return n},o.prototype.iushln=function(e){r("number"==typeof e&&e>=0);var t,n=e%26,i=(e-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var a=0;for(t=0;t<this.length;t++){var s=this.words[t]&o,c=(0|this.words[t])-s<<n;this.words[t]=c|a,a=s>>>26-n}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t<i;t++)this.words[t]=0;this.length+=i}return this.strip()},o.prototype.ishln=function(e){return r(0===this.negative),this.iushln(e)},o.prototype.iushrn=function(e,t,n){var i;r("number"==typeof e&&e>=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<<o,c=n;if(i-=a,i=Math.max(0,i),c){for(var u=0;u<a;u++)c.words[u]=this.words[u];c.length=a}if(0===a);else if(this.length>a)for(this.length-=a,u=0;u<this.length;u++)this.words[u]=this.words[u+a];else this.words[0]=0,this.length=1;var l=0;for(u=this.length-1;u>=0&&(0!==l||u>=i);u--){var h=0|this.words[u];this.words[u]=l<<26-o|h>>>o,l=h&s}return c&&0!==l&&(c.words[c.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,n){return r(0===this.negative),this.iushrn(e,t,n)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){r("number"==typeof e&&e>=0);var t=e%26,n=(e-t)/26,i=1<<t;return!(this.length<=n||!(this.words[n]&i))},o.prototype.imaskn=function(e){r("number"==typeof e&&e>=0);var t=e%26,n=(e-t)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==t&&n++,this.length=Math.min(n,this.length),0!==t){var i=67108863^67108863>>>t<<t;this.words[this.length-1]&=i}return this.strip()},o.prototype.maskn=function(e){return this.clone().imaskn(e)},o.prototype.iaddn=function(e){return r("number"==typeof e),r(e<67108864),e<0?this.isubn(-e):0!==this.negative?1===this.length&&(0|this.words[0])<e?(this.words[0]=e-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(e),this.negative=1,this):this._iaddn(e)},o.prototype._iaddn=function(e){this.words[0]+=e;for(var t=0;t<this.length&&this.words[t]>=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(r("number"==typeof e),r(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=67108864,this.words[t+1]-=1;return this.strip()},o.prototype.addn=function(e){return this.clone().iaddn(e)},o.prototype.subn=function(e){return this.clone().isubn(e)},o.prototype.iabs=function(){return this.negative=0,this},o.prototype.abs=function(){return this.clone().iabs()},o.prototype._ishlnsubmul=function(e,t,n){var i,o,a=e.length+n;this._expand(a);var s=0;for(i=0;i<e.length;i++){o=(0|this.words[i+n])+s;var c=(0|e.words[i])*t;s=((o-=67108863&c)>>26)-(c/67108864|0),this.words[i+n]=67108863&o}for(;i<this.length-n;i++)s=(o=(0|this.words[i+n])+s)>>26,this.words[i+n]=67108863&o;if(0===s)return this.strip();for(r(-1===s),s=0,i=0;i<this.length;i++)s=(o=-(0|this.words[i])+s)>>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),i=e,a=0|i.words[i.length-1];0!=(n=26-this._countBits(a))&&(i=i.ushln(n),r.iushln(n),a=0|i.words[i.length-1]);var s,c=r.length-i.length;if("mod"!==t){(s=new o(null)).length=c+1,s.words=new Array(s.length);for(var u=0;u<s.length;u++)s.words[u]=0}var l=r.clone()._ishlnsubmul(i,1,c);0===l.negative&&(r=l,s&&(s.words[c]=1));for(var h=c-1;h>=0;h--){var f=67108864*(0|r.words[i.length+h])+(0|r.words[i.length+h-1]);for(f=Math.min(f/a|0,67108863),r._ishlnsubmul(i,f,h);0!==r.negative;)f--,r.negative=0,r._ishlnsubmul(i,1,h),r.isZero()||(r.negative^=1);s&&(s.words[h]=f)}return s&&s.strip(),r.strip(),"div"!==t&&0!==n&&r.iushrn(n),{div:s||null,mod:r}},o.prototype.divmod=function(e,t,n){return r(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),n&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):this.negative&e.negative?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),n&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var n=0!==t.div.negative?t.mod.isub(e):t.mod,r=e.ushrn(1),i=e.andln(1),o=n.cmp(r);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){r(e<=67108863);for(var t=(1<<26)%e,n=0,i=this.length-1;i>=0;i--)n=(t*n+(0|this.words[i]))%e;return n},o.prototype.idivn=function(e){r(e<=67108863);for(var t=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*t;this.words[n]=i/e|0,t=i%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),c=new o(1),u=0;t.isEven()&&n.isEven();)t.iushrn(1),n.iushrn(1),++u;for(var l=n.clone(),h=t.clone();!t.isZero();){for(var f=0,d=1;!(t.words[0]&d)&&f<26;++f,d<<=1);if(f>0)for(t.iushrn(f);f-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(l),a.isub(h)),i.iushrn(1),a.iushrn(1);for(var g=0,p=1;!(n.words[0]&p)&&g<26;++g,p<<=1);if(g>0)for(n.iushrn(g);g-- >0;)(s.isOdd()||c.isOdd())&&(s.iadd(l),c.isub(h)),s.iushrn(1),c.iushrn(1);t.cmp(n)>=0?(t.isub(n),i.isub(s),a.isub(c)):(n.isub(t),s.isub(i),c.isub(a))}return{a:s,b:c,gcd:n.iushln(u)}},o.prototype._invmp=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),c=n.clone();t.cmpn(1)>0&&n.cmpn(1)>0;){for(var u=0,l=1;!(t.words[0]&l)&&u<26;++u,l<<=1);if(u>0)for(t.iushrn(u);u-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);for(var h=0,f=1;!(n.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(n.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);t.cmp(n)>=0?(t.isub(n),a.isub(s)):(n.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),n=e.clone();t.negative=0,n.negative=0;for(var r=0;t.isEven()&&n.isEven();r++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var i=t.cmp(n);if(i<0){var o=t;t=n,n=o}else if(0===i||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return!(1&this.words[0])},o.prototype.isOdd=function(){return!(1&~this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){r("number"==typeof e);var t=e%26,n=(e-t)/26,i=1<<t;if(this.length<=n)return this._expand(n+1),this.words[n]|=i,this;for(var o=i,a=n;0!==o&&a<this.length;a++){var s=0|this.words[a];o=(s+=o)>>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,n=e<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)t=1;else{n&&(e=-e),r(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:i<e?-1:1}return 0!==this.negative?0|-t:t},o.prototype.cmp=function(e){if(0!==this.negative&&0===e.negative)return-1;if(0===this.negative&&0!==e.negative)return 1;var t=this.ucmp(e);return 0!==this.negative?0|-t:t},o.prototype.ucmp=function(e){if(this.length>e.length)return 1;if(this.length<e.length)return-1;for(var t=0,n=this.length-1;n>=0;n--){var r=0|this.words[n],i=0|e.words[n];if(r!==i){r<i?t=-1:r>i&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new E(e)},o.prototype.toRed=function(e){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return r(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return r(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var m={k256:null,p224:null,p192:null,p25519:null};function w(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){w.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function y(){w.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function S(){w.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function k(){w.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function E(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else r(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function x(e){E.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}w.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},w.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var r=t<this.n?-1:n.ucmp(this.p);return 0===r?(n.words[0]=0,n.length=1):r>0?n.isub(this.p):void 0!==n.strip?n.strip():n._strip(),n},w.prototype.split=function(e,t){e.iushrn(this.n,0,t)},w.prototype.imulK=function(e){return e.imul(this.k)},i(v,w),v.prototype.split=function(e,t){for(var n=4194303,r=Math.min(e.length,9),i=0;i<r;i++)t.words[i]=e.words[i];if(t.length=r,e.length<=9)return e.words[0]=0,void(e.length=1);var o=e.words[9];for(t.words[t.length++]=o&n,i=10;i<e.length;i++){var a=0|e.words[i];e.words[i-10]=(a&n)<<4|o>>>22,o=a}o>>>=22,e.words[i-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},v.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n<e.length;n++){var r=0|e.words[n];t+=977*r,e.words[n]=67108863&t,t=64*r+(t/67108864|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},i(y,w),i(S,w),i(k,w),k.prototype.imulK=function(e){for(var t=0,n=0;n<e.length;n++){var r=19*(0|e.words[n])+t,i=67108863&r;r>>>=26,e.words[n]=i,t=r}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(m[e])return m[e];var t;if("k256"===e)t=new v;else if("p224"===e)t=new y;else if("p192"===e)t=new S;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new k}return m[e]=t,t},E.prototype._verify1=function(e){r(0===e.negative,"red works only with positives"),r(e.red,"red works only with red numbers")},E.prototype._verify2=function(e,t){r(!(e.negative|t.negative),"red works only with positives"),r(e.red&&e.red===t.red,"red works only with red numbers")},E.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},E.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},E.prototype.add=function(e,t){this._verify2(e,t);var n=e.add(t);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},E.prototype.iadd=function(e,t){this._verify2(e,t);var n=e.iadd(t);return n.cmp(this.m)>=0&&n.isub(this.m),n},E.prototype.sub=function(e,t){this._verify2(e,t);var n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},E.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},E.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},E.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},E.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},E.prototype.isqr=function(e){return this.imul(e,e.clone())},E.prototype.sqr=function(e){return this.mul(e,e)},E.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(r(t%2==1),3===t){var n=this.m.add(new o(1)).iushrn(2);return this.pow(e,n)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);r(!i.isZero());var s=new o(1).toRed(this),c=s.redNeg(),u=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new o(2*l*l).toRed(this);0!==this.pow(l,u).cmp(c);)l.redIAdd(c);for(var h=this.pow(l,i),f=this.pow(e,i.addn(1).iushrn(1)),d=this.pow(e,i),g=a;0!==d.cmp(s);){for(var p=d,b=0;0!==p.cmp(s);b++)p=p.redSqr();r(b<g);var m=this.pow(h,new o(1).iushln(g-b-1));f=f.redMul(m),h=m.redSqr(),d=d.redMul(h),g=b}return f},E.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},E.prototype.pow=function(e,t){if(t.isZero())return new o(1).toRed(this);if(0===t.cmpn(1))return e.clone();var n=new Array(16);n[0]=new o(1).toRed(this),n[1]=e;for(var r=2;r<n.length;r++)n[r]=this.mul(n[r-1],e);var i=n[0],a=0,s=0,c=t.bitLength()%26;for(0===c&&(c=26),r=t.length-1;r>=0;r--){for(var u=t.words[r],l=c-1;l>=0;l--){var h=u>>l&1;i!==n[0]&&(i=this.sqr(i)),0!==h||0!==a?(a<<=1,a|=h,(4==++s||0===r&&0===l)&&(i=this.mul(i,n[a]),s=0,a=0)):s=0}c=26}return i},E.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},E.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new x(e)},i(x,E),x.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},x.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},x.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},x.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},x.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e=n.nmd(e),this)},33532:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isObjectEmpty=function(e){if(!e)return!0;for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}},33787:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default={width:function e(t){var n;let r=0;return t?(void 0===t.fields||(r+=t.fields.length,r+=t.fields.map((t=>e(t.types.find((e=>"Document"===e.name))))).reduce(((e,t)=>e+t||0),0),r+=null!==(n=t.fields.map((t=>{const n=t.types.find((e=>"Array"===e.name));if(n)return e(n.types.find((e=>"Document"===e.name)))})).reduce(((e,t)=>(null!=e?e:0)+(null!=t?t:0)||0),0))&&void 0!==n?n:0),r):r},depth:function e(t){if(!t)return 0;let n=0;return void 0!==t.fields&&t.fields.length>0&&(n=1+Math.max(Math.max(...t.fields.map((t=>e(t.types.find((e=>"Document"===e.name)))))),Math.max(...t.fields.map((t=>{const n=t.types.find((e=>"Array"===e.name));return n?e(n.types.find((e=>"Document"===e.name))):0}))))),n},branch:function e(t){const n=[];let r;return t?(void 0!==t.fields&&t.fields.length>0&&(n.push(t.fields.length),r=t.fields.map((function(t){return e(t.types.find((e=>"Document"===e.name)))})),n.push(...r.flat(1/0)),r=t.fields.map((function(t){const n=t.types.find((e=>"Array"===e.name));return n?e(n.types.find((e=>"Document"===e.name))):[]})),n.push(...r.flat(1/0))),n.sort().reverse()):n}}},33859:(e,t)=>{function n(e){return e.bsonType||e.type}function r(e,t){if(null==e)throw new Error(t)}function i(e){const t=n(e),r=(Array.isArray(t)?t:[null!=t?t:"any"]).map((e=>function(e){switch(e){case"string":return"string";case"number":case"integer":return"number";case"boolean":case"bool":return"boolean";case"null":return"null";case"double":return["bson.Double","number"];case"binData":return"bson.Binary";case"objectId":return"bson.ObjectId";case"date":return"bson.Date";case"regex":return"bson.BSONRegExp";case"symbol":return"bson.BSONSymbol";case"javascript":case"javascriptWithScope":return"bson.Code";case"int":return["bson.Int32","number"];case"timestamp":return"bson.Timestamp";case"long":return["bson.Long","number"];case"decimal":return"bson.Decimal128";case"minKey":return"bson.MinKey";case"maxKey":return"bson.MaxKey";case"dbPointer":return"bson.DBPointer";case"undefined":return"undefined";default:return"any"}}(e))).flat();return new Set(r.flat())}function o(e){const t=[];for(let n=0;n<e;n++)t.push(" ");return t.join("")}function a(e,t){return`{\n${Object.entries(e).map((([e,s])=>{switch(n(s)){case"array":return r(s.items,"schema.items must be defined"),`${o(t)}${e}?: ${c=[...i(s.items)],1===c.length?`${c[0]}[]`:`${c.join(" | ")})[]`}`;case"object":return r(s.properties,"schema.properties must be defined"),`${o(t)}${e}?: ${a(s.properties,t+1)}`;default:return`${o(t)}${e}?: ${[...i(s)].join(" | ")}`}var c})).join(";\n")};\n${o(t-1)}}`}Object.defineProperty(t,"__esModule",{value:!0}),t.toTypescriptTypeDefinition=void 0,t.toTypescriptTypeDefinition=function(e){return r(e.properties,"schema.properties must be defined"),a(e.properties,1)}},34557:e=>{e.exports=JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},34995:function(e,t,n){var r,i=n(67787).Buffer,o=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=r(e),i=0;i<n.length;i++)"default"!==n[i]&&o(t,e,n[i]);return a(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.GLOBAL_FUNCTIONS=t.GLOBALS=void 0,t.getScopeFunction=function(e,t){if(t&&f[e])return f[e];if(!t&&h[e])return h[e];if(d[e])return d[e];throw new Error(`Attempted to access scope property '${e}' that doesn't exist`)},t.isMethodWhitelisted=function(e,t){if(Object.prototype.hasOwnProperty.call(g,e)){const n=g[e].allowedMethods;return"string"==typeof n?g[n].allowedMethods[t]:n[t]}return!1},t.getClass=function(e){if(Object.prototype.hasOwnProperty.call(g,e))return g[e].class;throw new Error(`Attempted to access member '${e}' that doesn't exist`)};const c=s(n(62444));function u(e){return Object.freeze(Object.create(null,Object.getOwnPropertyDescriptors(e)))}function l(e){return"string"==typeof e?c.Long.fromString(e):c.Long.fromNumber(e)}const h=u({Date:function(...e){return Date(...e)}}),f=u({Date:function(...e){return new Date(...e)}}),d=u({RegExp,Binary:function(e,t){return new c.Binary(e,t)},LegacyJavaUUID:function(e){void 0===e&&(e=(new c.UUID).toHexString());let t=String.prototype.replace.call(e,/[{}-]/g,(()=>"")),n=String.prototype.substring.call(t,0,16),r=String.prototype.substring.call(t,16,32);n=String.prototype.substring.call(n,14,16)+String.prototype.substring.call(n,12,14)+String.prototype.substring.call(n,10,12)+String.prototype.substring.call(n,8,10)+String.prototype.substring.call(n,6,8)+String.prototype.substring.call(n,4,6)+String.prototype.substring.call(n,2,4)+String.prototype.substring.call(n,0,2),r=String.prototype.substring.call(r,14,16)+String.prototype.substring.call(r,12,14)+String.prototype.substring.call(r,10,12)+String.prototype.substring.call(r,8,10)+String.prototype.substring.call(r,6,8)+String.prototype.substring.call(r,4,6)+String.prototype.substring.call(r,2,4)+String.prototype.substring.call(r,0,2),t=n+r;const o=i.from(t,"hex");return new c.Binary(o,3)},LegacyCSharpUUID:function(e){void 0===e&&(e=(new c.UUID).toHexString());let t=String.prototype.replace.call(e,/[{}-]/g,(()=>""));t=String.prototype.substring.call(t,6,8)+String.prototype.substring.call(t,4,6)+String.prototype.substring.call(t,2,4)+String.prototype.substring.call(t,0,2)+(String.prototype.substring.call(t,10,12)+String.prototype.substring.call(t,8,10))+(String.prototype.substring.call(t,14,16)+String.prototype.substring.call(t,12,14))+String.prototype.substring.call(t,16,32);const n=i.from(t,"hex");return new c.Binary(n,3)},LegacyPythonUUID:function(e){return void 0===e?new c.Binary((new c.UUID).toBinary().buffer,3):new c.Binary(i.from(String.prototype.replace.call(e,/[{}-]/g,(()=>"")),"hex"),3)},BinData:function(e,t){return new c.Binary(i.from(t,"base64"),e)},UUID:function(e){return void 0===e?(new c.UUID).toBinary():new c.Binary(i.from(e.replace(/-/g,""),"hex"),4)},Code:function(e,t){return new c.Code(e,t)},DBRef:function(e,t,n,r){return new c.DBRef(e,t,n,r)},Decimal128:function(e){return c.Decimal128.fromString(e)},NumberDecimal:function(e){return c.Decimal128.fromString(e)},Double:function(e){return new c.Double(e)},Int32:function(e){return new c.Int32(e)},NumberInt:function(e){return new c.Int32(e)},Long:function(e,t){return new c.Long(e,t)},NumberLong:l,Int64:l,Map:function(e){return new(c.Map??Map)(e)},MaxKey:function(){return new c.MaxKey},MinKey:function(){return new c.MinKey},ObjectID:function(e){return new c.ObjectId(e)},ObjectId:function(e){return new c.ObjectId(e)},Symbol:function(e){return new c.BSONSymbol(e)},Timestamp:function(e,t){return"number"==typeof e&&"number"==typeof t||void 0!==t?new c.Timestamp({t:e,i:t}):new c.Timestamp(e)},ISODate:function(e){if(void 0===e)return new Date;if("string"!=typeof e)return new Date(e);const t=e.match(/^(?<Y>\d{4})-?(?<M>\d{2})-?(?<D>\d{2})([T ](?<h>\d{2})(:?(?<m>\d{2})(:?((?<s>\d{2})(\.(?<ms>\d+))?))?)?(?<tz>Z|([+-])(\d{2}):?(\d{2})?)?)?$/);if(null!==t&&void 0!==t.groups){const{Y:e,M:n,D:r,h:i,m:o,s:a,ms:s,tz:c}=t.groups,u=new Date(`${e}-${n}-${r}T${i||"00"}:${o||"00"}:${a||"00"}.${s||"000"}${c||"Z"}`);if(u.getTime()>=-621672192e5&&u.getTime()<=0xe677d21fdbff)return u}throw new Error(`${JSON.stringify(e)} is not a valid ISODate`)}});t.GLOBALS=u({Infinity:1/0,NaN:NaN,undefined:void 0});const g=u({Math:u({class:Math,allowedMethods:u({abs:!0,acos:!0,acosh:!0,asin:!0,asinh:!0,atan:!0,atan2:!0,atanh:!0,cbrt:!0,ceil:!0,clz32:!0,cos:!0,cosh:!0,exp:!0,expm1:!0,floor:!0,fround:!0,hypot:!0,imul:!0,log:!0,log10:!0,log1p:!0,log2:!0,max:!0,min:!0,pow:!0,round:!0,sign:!0,sin:!0,sinh:!0,sqrt:!0,tan:!0,tanh:!0,trunc:!0})}),Date:u({class:Date,allowedMethods:u({getDate:!0,getDay:!0,getFullYear:!0,getHours:!0,getMilliseconds:!0,getMinutes:!0,getMonth:!0,getSeconds:!0,getTime:!0,getTimezoneOffset:!0,getUTCDate:!0,getUTCDay:!0,getUTCFullYear:!0,getUTCHours:!0,getUTCMilliseconds:!0,getUTCMinutes:!0,getUTCMonth:!0,getUTCSeconds:!0,getYear:!0,now:!0,setDate:!0,setFullYear:!0,setHours:!0,setMilliseconds:!0,setMinutes:!0,setMonth:!0,setSeconds:!0,setTime:!0,setUTCDate:!0,setUTCFullYear:!0,setUTCHours:!0,setUTCMilliseconds:!0,setUTCMinutes:!0,setUTCMonth:!0,setUTCSeconds:!0,setYear:!0,toISOString:!0,valueOf:!0})}),ISODate:u({class:Date,allowedMethods:"Date"}),Binary:u({class:c.Binary,allowedMethods:{createFromHexString:!0,createFromBase64:!0}})});t.GLOBAL_FUNCTIONS=Object.freeze([...Object.keys(d),...Object.keys(f),...Object.keys(h)])},35902:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ExportsManager=t.jsonExportFormat=void 0,t.decodeAndNormalize=g,t.ensureExtension=p,t.isExportExpired=b;const i=r(n(69761)),o=r(n(17642)),a=r(n(65981)),s=r(n(8763)),c=n(36374),u=n(62444),l=n(93874),h=n(2444),f=n(45584);t.jsonExportFormat=i.default.enum(["relaxed","canonical"]);class d extends s.default{constructor(e,t,n){super(),this.exportsDirectoryPath=e,this.config=t,this.logger=n,this.storedExports={},this.exportsCleanupInProgress=!1,this.shutdownController=new AbortController}get availableExports(){return this.assertIsNotShuttingDown(),Object.values(this.storedExports).filter((e=>"ready"===e.exportStatus&&!b(e.exportCreatedAt,this.config.exportTimeoutMs))).map((({exportName:e,exportTitle:t,exportURI:n,exportPath:r})=>({exportName:e,exportTitle:t,exportURI:n,exportPath:r})))}init(){this.exportsCleanupInterval||(this.exportsCleanupInterval=setInterval((()=>{this.cleanupExpiredExports()}),this.config.exportCleanupIntervalMs))}async close(){if(!this.shutdownController.signal.aborted)try{clearInterval(this.exportsCleanupInterval),this.shutdownController.abort(),await a.default.rm(this.exportsDirectoryPath,{force:!0,recursive:!0}),this.emit("closed")}catch(e){this.logger.error({id:f.LogId.exportCloseError,context:"Error while closing ExportsManager",message:e instanceof Error?e.message:String(e)})}}async readExport(e){try{this.assertIsNotShuttingDown(),e=g(e);const t=this.storedExports[e];if(!t)throw new Error("Requested export has either expired or does not exist.");if("in-progress"===t.exportStatus)throw new Error("Requested export is still being generated. Try again later.");const{exportPath:n,docsTransformed:r}=t;return{content:await a.default.readFile(n,{encoding:"utf8",signal:this.shutdownController.signal}),docsTransformed:r}}catch(t){throw this.logger.error({id:f.LogId.exportReadError,context:`Error when reading export - ${e}`,message:t instanceof Error?t.message:String(t)}),t}}async createJSONExport({input:e,exportName:t,exportTitle:n,jsonExportFormat:r}){try{this.assertIsNotShuttingDown();const i=g(p(t,"json"));if(this.storedExports[i])return Promise.reject(new Error("Export with same name is either already available or being generated."));const a=`exported-data://${encodeURIComponent(i)}`,s=o.default.join(this.exportsDirectoryPath,i),c=this.storedExports[i]={exportName:i,exportTitle:n,exportPath:s,exportURI:a,exportStatus:"in-progress"};return this.startExport({input:e,jsonExportFormat:r,inProgressExport:c}),Promise.resolve(c)}catch(e){throw this.logger.error({id:f.LogId.exportCreationError,context:"Error when registering JSON export request",message:e instanceof Error?e.message:String(e)}),e}}async startExport({input:e,jsonExportFormat:t,inProgressExport:n}){try{let r=!1,i=0;try{await a.default.mkdir(this.exportsDirectoryPath,{recursive:!0});const o=(0,c.createWriteStream)(n.exportPath),s=this.docToEJSONStream(this.getEJSONOptionsForFormat(t));await(0,h.pipeline)([e.stream(),s,o],{signal:this.shutdownController.signal}),i=s.docsTransformed,r=!0}catch(e){throw delete this.storedExports[n.exportName],this.silentlyRemoveExport(n.exportPath,f.LogId.exportCreationCleanupError,`Error when removing incomplete export ${n.exportName}`),e}finally{r&&(this.storedExports[n.exportName]={...n,exportCreatedAt:Date.now(),exportStatus:"ready",docsTransformed:i},this.emit("export-available",n.exportURI)),e.close()}}catch(e){this.logger.error({id:f.LogId.exportCreationError,context:`Error when generating JSON export for ${n.exportName}`,message:e instanceof Error?e.message:String(e)})}}getEJSONOptionsForFormat(e){switch(e){case"relaxed":return{relaxed:!0};case"canonical":return{relaxed:!1};default:return}}docToEJSONStream(e){let t=0;const n=Object.assign(new l.Transform({objectMode:!0,transform(n,r,i){try{const r=u.EJSON.stringify(n,void 0,void 0,e);0===t?this.push("["+r):this.push(",\n"+r),t++,i()}catch(e){i(e)}},flush(e){0===t?this.push("[]"):this.push("]"),n.docsTransformed=t,e()}}),{docsTransformed:t});return n}async cleanupExpiredExports(){if(!this.exportsCleanupInProgress){this.exportsCleanupInProgress=!0;try{const e=[];for(const t of Object.values(this.storedExports))"ready"===t.exportStatus&&b(t.exportCreatedAt,this.config.exportTimeoutMs)&&(e.push(t),delete this.storedExports[t.exportName]);const t=[];for(const{exportPath:n,exportName:r}of e)t.push(this.silentlyRemoveExport(n,f.LogId.exportCleanupError,`Considerable error when removing export ${r}`));await Promise.allSettled(t)}catch(e){this.logger.error({id:f.LogId.exportCleanupError,context:"Error when cleaning up exports",message:e instanceof Error?e.message:String(e)})}finally{this.exportsCleanupInProgress=!1}}}async silentlyRemoveExport(e,t,n){try{await a.default.unlink(e)}catch(e){"ENOENT"!==e.code&&this.logger.error({id:t,context:n,message:e instanceof Error?e.message:String(e)})}}assertIsNotShuttingDown(){if(this.shutdownController.signal.aborted)throw new Error("ExportsManager is shutting down.")}static init(e,t,n=(new u.ObjectId).toString()){const r=o.default.join(e.exportsPath,n),i=new d(r,e,t);return i.init(),i}}function g(e){return decodeURIComponent(e).normalize("NFKC")}function p(e,t){const n=t.startsWith(".")?t:`.${t}`;return e.endsWith(n)?e:`${e}${n}`}function b(e,t){return Date.now()-e>t}t.ExportsManager=d},35941:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CommonErrors=void 0,t.CommonErrors={InvalidArgument:"COMMON-10001",InvalidOperation:"COMMON-10002",Deprecated:"COMMON-10003",CommandFailed:"COMMON-10004",UnexpectedInternalError:"COMMON-90001",NotImplemented:"COMMON-90002"}},36019:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(78249),i=n(87351),o={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:e})=>r.str`must match "${e.ifClause}" schema`,params:({params:e})=>r._`{failingKeyword: ${e.ifClause}}`},code(e){const{gen:t,parentSchema:n,it:o}=e;void 0===n.then&&void 0===n.else&&(0,i.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const s=a(o,"then"),c=a(o,"else");if(!s&&!c)return;const u=t.let("valid",!0),l=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},l);e.mergeEvaluated(t)}(),e.reset(),s&&c){const n=t.let("ifClause");e.setParams({ifClause:n}),t.if(l,h("then",n),h("else",n))}else s?t.if(l,h("then")):t.if((0,r.not)(l),h("else"));function h(n,i){return()=>{const o=e.subschema({keyword:n},l);t.assign(u,l),e.mergeValidEvaluated(o,u),i?t.assign(i,r._`${n}`):e.setParams({ifClause:n})}}e.pass(u,(()=>e.error(!0)))}};function a(e,t){const n=e.schema[t];return void 0!==n&&!(0,i.alwaysValidSchema)(e,n)}t.default=o},36937:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;const r=n(68694),i=n(78249),o=i.operators,a={formatMaximum:{okStr:"<=",ok:o.LTE,fail:o.GT},formatMinimum:{okStr:">=",ok:o.GTE,fail:o.LT},formatExclusiveMaximum:{okStr:"<",ok:o.LT,fail:o.GTE},formatExclusiveMinimum:{okStr:">",ok:o.GT,fail:o.LTE}},s={message:({keyword:e,schemaCode:t})=>i.str`should be ${a[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>i._`{comparison: ${a[e].okStr}, limit: ${t}}`};t.formatLimitDefinition={keyword:Object.keys(a),type:"string",schemaType:"string",$data:!0,error:s,code(e){const{gen:t,data:n,schemaCode:o,keyword:s,it:c}=e,{opts:u,self:l}=c;if(!u.validateFormats)return;const h=new r.KeywordCxt(c,l.RULES.all.format.definition,"format");function f(e){return i._`${e}.compare(${n}, ${o}) ${a[s].fail} 0`}h.$data?function(){const n=t.scopeValue("formats",{ref:l.formats,code:u.code.formats}),r=t.const("fmt",i._`${n}[${h.schemaCode}]`);e.fail$data((0,i.or)(i._`typeof ${r} != "object"`,i._`${r} instanceof RegExp`,i._`typeof ${r}.compare != "function"`,f(r)))}():function(){const n=h.schema,r=l.formats[n];if(!r||!0===r)return;if("object"!=typeof r||r instanceof RegExp||"function"!=typeof r.compare)throw new Error(`"${s}": format "${n}" does not define "compare" function`);const o=t.scopeValue("formats",{key:n,ref:r,code:u.code.formats?i._`${u.code.formats}${(0,i.getProperty)(n)}`:void 0});e.fail$data(f(o))}()},dependencies:["format"]},t.default=e=>(e.addKeyword(t.formatLimitDefinition),e)},37057:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalSchemaBasedAccessor=void 0,t.InternalSchemaBasedAccessor=class{constructor(e,t){this.internalSchema=e,this.converters=t}async getInternalSchema(){return this.internalSchema}async getStandardJsonSchema(e={}){var t;return null!==(t=this.standardJSONSchema)&&void 0!==t?t:this.standardJSONSchema=await this.converters.internalToStandard(this.internalSchema,e)}async getMongoDBJsonSchema(e={}){var t;return null!==(t=this.mongodbJSONSchema)&&void 0!==t?t:this.mongodbJSONSchema=await this.converters.internalToMongoDB(this.internalSchema,e)}async getExpandedJSONSchema(e={}){var t;return null!==(t=this.expandedJSONSchema)&&void 0!==t?t:this.expandedJSONSchema=await this.converters.internalToExpanded(this.internalSchema,e)}}},37370:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CreateDBUserTool=t.CreateDBUserArgs=void 0;const r=n(69761),i=n(55415),o=n(56092),a=n(5853),s=n(14233);t.CreateDBUserArgs={projectId:s.AtlasArgs.projectId().describe("Atlas project ID"),username:s.AtlasArgs.username().describe("Username for the new user"),password:s.AtlasArgs.password().nullish().describe("Password for the new user. IMPORTANT: If the user hasn't supplied an explicit password, leave it unset and under no circumstances try to generate a random one. A secure password will be generated by the MCP server if necessary."),roles:r.z.array(r.z.object({roleName:s.CommonArgs.string().describe("Role name"),databaseName:s.CommonArgs.string().describe("Database name").default("admin"),collectionName:s.CommonArgs.string().describe("Collection name").optional()})).describe("Roles for the new user"),clusters:r.z.array(s.AtlasArgs.clusterName()).describe("Clusters to assign the user to, leave empty for access to all clusters").optional()};class c extends i.AtlasToolBase{constructor(){super(...arguments),this.name="atlas-create-db-user",this.description="Create an MongoDB Atlas database user",this.argsShape={...t.CreateDBUserArgs}}async execute({projectId:e,username:t,password:n,roles:r,clusters:i}){await(0,a.ensureCurrentIpInAccessList)(this.apiClient,e);const s=!n;s&&(n=await(0,o.generateSecurePassword)());const c={groupId:e,awsIAMType:"NONE",databaseName:"admin",ldapAuthType:"NONE",oidcAuthType:"NONE",x509Type:"NONE",username:t,password:n,roles:r,scopes:i?.length?i.map((e=>({type:"CLUSTER",name:e}))):void 0};return await this.apiClient.createDatabaseUser({params:{path:{groupId:e}},body:c}),this.session.keychain.register(t,"user"),n&&this.session.keychain.register(n,"password"),{content:[{type:"text",text:`User "${t}" created successfully${s?` with password: \`${n}\``:""}.`}]}}getConfirmationMessage({projectId:e,username:t,password:n,roles:r,clusters:i}){return`You are about to create a database user in Atlas project \`${e}\`:\n\n**Username**: \`${t}\`\n\n**Password**: ${n?"(User-provided password)":"(Auto-generated secure password)"}\n\n**Roles**: ${r.map((e=>`${e.roleName}${e.collectionName?` on ${e.databaseName}.${e.collectionName}`:` on ${e.databaseName}`}`)).join(", ")}\n\n**Cluster Access**: ${i?.length?i.join(", "):"All clusters in the project"}\n\nThis will create a new database user with the specified permissions. **Do you confirm the execution of the action?**`}}t.CreateDBUserTool=c,c.operationType="create"},37939:(e,t,n)=>{var r=n(9606).URL;Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectClusterTool=t.ConnectClusterArgs=void 0;const i=n(55415),o=n(56092),a=n(45584),s=n(30084),c=n(5853),u=n(20999),l=n(14233),h="Note: Your current IP address has been added to the Atlas project's IP access list to enable secure connection.",f="Note: A temporary user has been created to enable secure connection to the cluster. For more information, see https://dochub.mongodb.org/core/mongodb-mcp-server-tools-considerations\n\nNote to LLM Agent: it is important to include the following link in your response to the user in case they want to get more information about the temporary user created: https://dochub.mongodb.org/core/mongodb-mcp-server-tools-considerations";function d(e){return new Promise((t=>setTimeout(t,e)))}t.ConnectClusterArgs={projectId:l.AtlasArgs.projectId().describe("Atlas project ID"),clusterName:l.AtlasArgs.clusterName().describe("Atlas cluster name"),connectionType:l.AtlasArgs.connectionType().describe("Type of connection (standard, private, or privateEndpoint) to an Atlas cluster")};class g extends i.AtlasToolBase{constructor(){super(...arguments),this.name="atlas-connect-cluster",this.description="Connect to MongoDB Atlas cluster",this.argsShape=t.ConnectClusterArgs}queryConnection(e,t){if(!this.session.connectedAtlasCluster)return this.session.isConnectedToMongoDB?"connected-to-other-cluster":"disconnected";const n=this.session.connectionManager.currentConnectionState;if(this.session.connectedAtlasCluster.projectId!==e||this.session.connectedAtlasCluster.clusterName!==t)return"connected-to-other-cluster";switch(n.tag){case"connecting":case"disconnected":return"connecting";case"connected":return"connected";case"errored":return this.session.logger.debug({id:a.LogId.atlasConnectFailure,context:"atlas-connect-cluster",message:`error querying cluster: ${n.errorReason}`}),"unknown"}}async prepareClusterConnection(e,t,n="standard"){const i=await(0,s.inspectCluster)(this.apiClient,e,t);if(void 0===i.connectionStrings)throw new Error("Connection strings not available");const a=(0,s.getConnectionString)(i.connectionStrings,n);if(void 0===a)throw new Error(`Connection string for connection type "${n}" is not available. Please ensure this connection type is set up in Atlas. See https://www.mongodb.com/docs/atlas/connect-to-database-deployment/#connect-to-an-atlas-cluster.`);const c=`mcpUser${Math.floor(1e5*Math.random())}`,l=await(0,o.generateSecurePassword)(),h=new Date(Date.now()+this.config.atlasTemporaryDatabaseUserLifetimeMs),f=(0,u.getDefaultRoleFromConfig)(this.config);await this.apiClient.createDatabaseUser({params:{path:{groupId:e}},body:{databaseName:"admin",groupId:e,roles:[f],scopes:[{type:"CLUSTER",name:t}],username:c,password:l,awsIAMType:"NONE",ldapAuthType:"NONE",oidcAuthType:"NONE",x509Type:"NONE",deleteAfterDate:h.toISOString(),description:"MDB MCP Temporary user, see https://dochub.mongodb.org/core/mongodb-mcp-server-tools-considerations"}});const d={username:c,projectId:e,clusterName:t,expiryDate:h},g=new r(a);return g.username=c,g.password=l,g.searchParams.set("authSource","admin"),this.session.keychain.register(c,"user"),this.session.keychain.register(l,"password"),{connectionString:g.toString(),atlas:d}}async connectToCluster(e,t){let n;this.session.logger.debug({id:a.LogId.atlasConnectAttempt,context:"atlas-connect-cluster",message:`attempting to connect to cluster: ${this.session.connectedAtlasCluster?.clusterName}`,noRedaction:!0});for(let r=0;r<600;r++){try{n=void 0,await this.session.connectToMongoDB({connectionString:e,atlas:t});break}catch(e){const t=e instanceof Error?e:new Error(String(e));n=t,this.session.logger.debug({id:a.LogId.atlasConnectFailure,context:"atlas-connect-cluster",message:`error connecting to cluster: ${t.message}`}),await d(500)}if(!this.session.connectedAtlasCluster||this.session.connectedAtlasCluster.projectId!==t.projectId||this.session.connectedAtlasCluster.clusterName!==t.clusterName)throw new Error("Cluster connection aborted")}if(n)throw this.session.connectedAtlasCluster?.projectId===t.projectId&&this.session.connectedAtlasCluster?.clusterName===t.clusterName&&this.session.connectedAtlasCluster?.username&&this.apiClient.deleteDatabaseUser({params:{path:{groupId:this.session.connectedAtlasCluster.projectId,username:this.session.connectedAtlasCluster.username,databaseName:"admin"}}}).catch((e=>{const t=e instanceof Error?e:new Error(String(e));this.session.logger.debug({id:a.LogId.atlasConnectFailure,context:"atlas-connect-cluster",message:`error deleting database user: ${t.message}`})})),n;this.session.logger.debug({id:a.LogId.atlasConnectSucceeded,context:"atlas-connect-cluster",message:`connected to cluster: ${this.session.connectedAtlasCluster?.clusterName}`,noRedaction:!0})}async execute({projectId:e,clusterName:t,connectionType:n}){const r=await(0,c.ensureCurrentIpInAccessList)(this.apiClient,e);let i=!1;switch(this.queryConnection(e,t)){case"connected-to-other-cluster":case"disconnected":{await this.session.disconnect();const{connectionString:r,atlas:o}=await this.prepareClusterConnection(e,t,n);i=!0,this.connectToCluster(r,o).catch((e=>{const t=e instanceof Error?e:new Error(String(e));this.session.logger.error({id:a.LogId.atlasConnectFailure,context:"atlas-connect-cluster",message:`error connecting to cluster: ${t.message}`})}));break}}for(let n=0;n<60;n++){if("connected"===this.queryConnection(e,t)){const e=[{type:"text",text:`Connected to cluster "${t}".`}];return r&&e.push({type:"text",text:h}),i&&e.push({type:"text",text:f}),{content:e}}await d(500)}const o=[{type:"text",text:`Attempting to connect to cluster "${t}"...`},{type:"text",text:"Warning: Provisioning a user and connecting to the cluster may take more time, please check again in a few seconds."}];return r&&o.push({type:"text",text:h}),i&&o.push({type:"text",text:f}),{content:o}}resolveTelemetryMetadata(e,{result:t}){const n=super.resolveTelemetryMetadata(e,{result:t}),r=this.getConnectionInfoMetadata();return r&&void 0!==r.project_id&&delete n.project_id,{...n,...r}}}t.ConnectClusterTool=g,g.operationType="connect"},38679:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;const r=n(87351),i=n(16428),o=n(96422),a=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);t.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!c(e):!!t&&u(e)<=t)};const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function c(e){for(const t in e){if(s.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(c))return!0;if("object"==typeof n&&c(n))return!0}return!1}function u(e){let t=0;for(const n in e){if("$ref"===n)return 1/0;if(t++,!a.has(n)&&("object"==typeof e[n]&&(0,r.eachItem)(e[n],(e=>t+=u(e))),t===1/0))return 1/0}return t}function l(e,t="",n){!1!==n&&(t=d(t));const r=e.parse(t);return h(e,r)}function h(e,t){return e.serialize(t).split("#")[0]+"#"}t.getFullPath=l,t._getFullPath=h;const f=/#\/?$/;function d(e){return e?e.replace(f,""):""}t.normalizeId=d,t.resolveUrl=function(e,t,n){return n=d(n),e.resolve(t,n)};const g=/^[a-z_][-a-z0-9._]*$/i;t.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:n,uriResolver:r}=this.opts,a=d(e[n]||t),s={"":a},c=l(r,a,!1),u={},h=new Set;return o(e,{allKeys:!0},((e,t,r,i)=>{if(void 0===i)return;const o=c+t;let a=s[i];function l(t){const n=this.opts.uriResolver.resolve;if(t=d(a?n(a,t):t),h.has(t))throw p(t);h.add(t);let r=this.refs[t];return"string"==typeof r&&(r=this.refs[r]),"object"==typeof r?f(e,r.schema,t):t!==d(o)&&("#"===t[0]?(f(e,u[t],t),u[t]=e):this.refs[t]=o),t}function b(e){if("string"==typeof e){if(!g.test(e))throw new Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}"string"==typeof e[n]&&(a=l.call(this,e[n])),b.call(this,e.$anchor),b.call(this,e.$dynamicAnchor),s[t]=a})),u;function f(e,t,n){if(void 0!==t&&!i(e,t))throw p(n)}function p(e){return new Error(`reference "${e}" resolves to more than one schema`)}}},39255:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(87351),i={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:i}=e;if((0,r.alwaysValidSchema)(i,n))return void e.fail();const o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,(()=>e.reset()),(()=>e.error()))},error:{message:"must NOT be valid"}};t.default=i},40165:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(86493);t.default={Email:r.isEmail}},40526:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(99442),i={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,r.validateTuple)(e,"items")};t.default=i},40967:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkTree=void 0;const r=n(34995);class i{constructor(e){this.options=e,this.checkSafeCall=e=>{const t=this.options.allowMethods;if("Identifier"===e.callee.type)return r.GLOBAL_FUNCTIONS.indexOf(e.callee.name)>=0&&e.arguments.every(this.checkSafeExpression);if(t&&"MemberExpression"===e.callee.type){const t=e.callee.object,n=e.callee.property;if("Identifier"===t.type&&"Identifier"===n.type)return(0,r.isMethodWhitelisted)(t.name,n.name)&&e.arguments.every(this.checkSafeExpression);if("NewExpression"!==t.type&&"CallExpression"!==t.type||"Identifier"!==t.callee.type)return this.checkSafeExpression(t)&&e.arguments.every(this.checkSafeExpression);{const i=t.callee;return(0,r.isMethodWhitelisted)(i.name,n.name)&&e.arguments.every(this.checkSafeExpression)}}return!1},this.checkSafeExpression=e=>{switch(e?.type){case"Identifier":return Object.prototype.hasOwnProperty.call(r.GLOBALS,e.name);case"Literal":return!0;case"ArrayExpression":return e.elements.every(this.checkSafeExpression);case"UnaryExpression":return this.checkSafeExpression(e.argument);case"BinaryExpression":return this.checkSafeExpression(e.left)&&this.checkSafeExpression(e.right);case"CallExpression":case"NewExpression":return this.checkSafeCall(e);case"ObjectExpression":return e.properties.every((e=>!("computed"in e&&e.computed||"method"in e&&e.method)&&!(!("key"in e)||!["Literal","Identifier"].includes(e.key.type))&&"value"in e&&(["FunctionExpression","ArrowFunctionExpression"].includes(e.value.type)||this.checkSafeExpression(e.value))));default:return!1}}}}t.checkTree=(e,t)=>"Program"===e.type&&1===e.body.length&&"ExpressionStatement"===e.body[0].type&&new i(t).checkSafeExpression(e.body[0].expression)},41654:function(e,t,n){var r,i=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=r(e),a=0;a<n.length;a++)"default"!==n[a]&&i(t,e,n[a]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.DeviceId=t.DEVICE_ID_TIMEOUT=void 0;const s=n(87641),c=n(45584);t.DEVICE_ID_TIMEOUT=3e3;class u{constructor(e,r=t.DEVICE_ID_TIMEOUT){this.logger=e,this.timeout=r,this.getMachineId=async()=>{const e=await Promise.resolve().then((()=>a(n(85745))));return(e.default?.machineId||e.machineId)(!0)},this.abortController=new AbortController,this.deviceIdPromise=u.UnknownDeviceId}initialize(){this.deviceIdPromise=(0,s.getDeviceId)({getMachineId:this.getMachineId,onError:(e,t)=>{this.handleDeviceIdError(e,String(t))},timeout:this.timeout,abortSignal:this.abortController.signal})}static create(e,n){const r=new u(e,n??t.DEVICE_ID_TIMEOUT);return r.initialize(),r}close(){this.abortController.abort()}get(){return this.deviceIdPromise}handleDeviceIdError(e,t){switch(this.deviceIdPromise=u.UnknownDeviceId,e){case"resolutionError":this.logger.debug({id:c.LogId.deviceIdResolutionError,context:"deviceId",message:`Resolution error: ${String(t)}`});break;case"timeout":this.logger.debug({id:c.LogId.deviceIdTimeout,context:"deviceId",message:"Device ID retrieval timed out",noRedaction:!0})}}}t.DeviceId=u,u.UnknownDeviceId=Promise.resolve("unknown")},42479:e=>{e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}')},43052:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DbStatsTool=void 0;const r=n(58203),i=n(77710),o=n(62444);class a extends r.MongoDBToolBase{constructor(){super(...arguments),this.name="db-stats",this.description="Returns statistics that reflect the use state of a single database",this.argsShape={database:r.DbOperationArgs.database}}async execute({database:e},{signal:t}){const n=await this.ensureConnected(),r=await n.runCommandWithCheck(e,{dbStats:1,scale:1},{signal:t});return{content:(0,i.formatUntrustedData)(`Statistics for database ${e}`,o.EJSON.stringify(r))}}}t.DbStatsTool=a,a.operationType="metadata"},43376:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListCollectionsTool=void 0;const r=n(58203),i=n(77710);class o extends r.MongoDBToolBase{constructor(){super(...arguments),this.name="list-collections",this.description="List all collections for a given database",this.argsShape={database:r.DbOperationArgs.database}}async execute({database:e},{signal:t}){const n=await this.ensureConnected(),r=await n.listCollections(e,{},{signal:t});return 0===r.length?{content:[{type:"text",text:`Found 0 collections for database "${e}". To create a collection, use the "create-collection" tool.`}]}:{content:(0,i.formatUntrustedData)(`Found ${r.length} collections for database "${e}".`,r.map((e=>`"${e.name}"`)).join("\n"))}}}t.ListCollectionsTool=o,o.operationType="metadata"},43443:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTool=t.getAggregateArgs=void 0;const r=n(69761),i=n(58203),o=n(77710),a=n(49446),s=n(62444),c=n(46319),u=n(92639),l=n(86463),h=n(18253),f=n(45584),d=n(70685),g=n(72439);t.getAggregateArgs=e=>({pipeline:r.z.array(e?r.z.union([d.VectorSearchStage,d.AnyAggregateStage]):d.AnyAggregateStage).describe(e?"An array of aggregation stages to execute.\nIf the user has asked for a vector search, `$vectorSearch` **MUST** be the first stage of the pipeline, or the first stage of a `$unionWith` subpipeline.\nIf the user has asked for lexical/Atlas search, use `$search` instead of `$text`.\n### Usage Rules for `$vectorSearch`\n- **Unset embeddings:**\n Unless the user explicitly requests the embeddings, add an `$unset` stage **at the end of the pipeline** to remove the embedding field and avoid context limits. **The $unset stage in this situation is mandatory**.\n- **Pre-filtering:**\nIf the user requests additional filtering, include filters in `$vectorSearch.filter` only for pre-filter fields in the vector index.\n NEVER include fields in $vectorSearch.filter that are not part of the vector index.\n- **Post-filtering:**\n For all remaining filters, add a $match stage after $vectorSearch.\n- If unsure which fields are filterable, use the collection-indexes tool to determine valid prefilter fields.\n- If no requested filters are valid prefilters, omit the filter key from $vectorSearch.\n\n### Usage Rules for `$search`\n- Include the index name, unless you know for a fact there's a default index. If unsure, use the collection-indexes tool to determine the index name.\n- The `$search` stage supports multiple operators, such as 'autocomplete', 'text', 'geoWithin', and others. Choose the approprate operator based on the user's query. If unsure of the exact syntax, consult the MongoDB Atlas Search documentation, which can be found here: https://www.mongodb.com/docs/atlas/atlas-search/operators-and-collectors/\n":"An array of aggregation stages to execute.")});class p extends i.MongoDBToolBase{constructor(){super(...arguments),this.name="aggregate",this.description="Run an aggregation against a MongoDB collection",this.argsShape={...i.DbOperationArgs,...(0,t.getAggregateArgs)(this.isFeatureEnabled("search")),responseBytesLimit:r.z.number().optional().default(h.ONE_MB).describe('The maximum number of bytes to return in the response. This value is capped by the server\'s configured maxBytesPerQuery and cannot be exceeded. Note to LLM: If the entire aggregation result is required, use the "export" tool instead of increasing this limit.')}}async execute({database:e,collection:t,pipeline:n,responseBytesLimit:r},{signal:i}){let l;try{const h=await this.ensureConnected();if(await this.assertOnlyUsesPermittedStages(n),await this.session.isSearchSupported()&&(0,g.assertVectorSearchFilterFieldsAreIndexed)({searchIndexes:await h.getSearchIndexes(e,t),pipeline:n,logger:this.session.logger}),this.config.indexCheck){const[r,o]=await this.isVectorSearchIndexUsed({database:e,collection:t,pipeline:n});switch(r){case"not-vector-search-query":await(0,a.checkIndexUsage)({database:e,collection:t,operation:"aggregate",explainCallback:async()=>h.aggregate(e,t,n,{signal:i},{writeConcern:void 0}).explain("queryPlanner"),logger:this.session.logger});break;case"non-existent-index":throw new c.MongoDBError(c.ErrorCodes.AtlasVectorSearchIndexNotFound,`Could not find an index with name "${o}" in namespace "${e}.${t}".`)}}let f,d;if((n=await this.replaceRawValuesWithEmbeddingsIfNecessary({database:e,collection:t,pipeline:n})).some((e=>this.isWriteStage(e))))l=h.aggregate(e,t,n,{signal:i}),d=await l.toArray(),f="The aggregation pipeline executed successfully.";else{const o=[...n];this.config.maxDocumentsPerQuery>0&&o.push({$limit:this.config.maxDocumentsPerQuery}),l=h.aggregate(e,t,o,{signal:i});const[a,s]=await Promise.all([this.countAggregationResultDocuments({provider:h,database:e,collection:t,pipeline:n,abortSignal:i}),(0,u.collectCursorUntilMaxBytesLimit)({cursor:l,configuredMaxBytesPerQuery:this.config.maxBytesPerQuery,toolResponseBytesLimit:r,abortSignal:i})]),c=this.config.maxDocumentsPerQuery>0&&!!a&&a>this.config.maxDocumentsPerQuery;d=s.documents,f=this.generateMessage({aggResultsCount:a,documents:s.documents,appliedLimits:[c?"config.maxDocumentsPerQuery":void 0,s.cappedBy].filter((e=>!!e))})}return{content:(0,o.formatUntrustedData)(f,...d.length>0?[s.EJSON.stringify(d)]:[])}}finally{l&&this.safeCloseCursor(l)}}async safeCloseCursor(e){try{await e.close()}catch(e){this.session.logger.warning({id:f.LogId.mongodbCursorCloseError,context:"aggregate tool",message:`Error when closing the cursor - ${e instanceof Error?e.message:String(e)}`})}}async assertOnlyUsesPermittedStages(e){const t=["update","create","delete"],n=await this.session.isSearchSupported();let r="";this.config.readOnly?r="In readOnly mode you can not run pipelines with $out or $merge stages.":this.config.disabledTools.some((e=>t.includes(e)))&&(r="When 'create', 'update', or 'delete' operations are disabled, you can not run pipelines with $out or $merge stages.");for(const t of e){if(this.isWriteStage(t)&&r)throw new c.MongoDBError(c.ErrorCodes.ForbiddenWriteOperation,r);if(this.isSearchStage(t)&&!n)throw new c.MongoDBError(c.ErrorCodes.AtlasSearchNotSupported,"Atlas Search is not supported in this cluster.")}}async countAggregationResultDocuments({provider:e,database:t,collection:n,pipeline:r,abortSignal:i}){const o=[...r,{$count:"totalDocuments"}];return await(0,l.operationWithFallback)((async()=>{const r=await e.aggregate(t,n,o,{signal:i}).maxTimeMS(h.AGG_COUNT_MAX_TIME_MS_CAP).toArray(),a=1===r.length?r[0]:void 0;return a&&"object"==typeof a&&"totalDocuments"in a&&"number"==typeof a.totalDocuments?a.totalDocuments:0}),void 0)}async replaceRawValuesWithEmbeddingsIfNecessary({database:e,collection:t,pipeline:n}){for(const r of n)if("$vectorSearch"in r){const{$vectorSearch:n}=r;if(Array.isArray(n.queryVector))continue;if(!n.embeddingParameters)throw new c.MongoDBError(c.ErrorCodes.AtlasVectorSearchInvalidQuery,"embeddingModel is mandatory if queryVector is a raw string.");const i=n.embeddingParameters;delete n.embeddingParameters,await this.session.vectorSearchEmbeddingsManager.assertVectorSearchIndexExists({database:e,collection:t,path:n.path});const[o]=await this.session.vectorSearchEmbeddingsManager.generateEmbeddings({rawValues:[n.queryVector],embeddingParameters:i,inputType:"query"});if(!o)throw new c.MongoDBError(c.ErrorCodes.AtlasVectorSearchInvalidQuery,"Failed to generate embeddings for the query vector.");n.queryVector=o}return await this.session.vectorSearchEmbeddingsManager.assertFieldsHaveCorrectEmbeddings({database:e,collection:t},n),n}async isVectorSearchIndexUsed({database:e,collection:t,pipeline:n}){let r=!1,i="default";for(const e of n)if("$vectorSearch"in e){const{$vectorSearch:t}=e;r=!0,i=t.index;break}return r?[await this.session.vectorSearchEmbeddingsManager.indexExists({database:e,collection:t,indexName:i})?"valid-index":"non-existent-index",i]:["not-vector-search-query"]}generateMessage({aggResultsCount:e,documents:t,appliedLimits:n}){let r=`The aggregation resulted in ${void 0===e?"indeterminable number of":e} documents.`;return(t.length!==e||n.length)&&(r+=` Returning ${t.length} documents`,n.length&&(r+=` while respecting the applied limits of ${n.map((e=>h.CURSOR_LIMITS_TO_LLM_TEXT[e])).join(", ")}. Note to LLM: If the entire query result is required then use "export" tool to export the query results`),r+="."),r}resolveTelemetryMetadata(e,{result:t}){const[n]=e.pipeline;return null!==n&&n instanceof Object&&"$vectorSearch"in n&&"embeddingParameters"in n.$vectorSearch&&this.config.voyageApiKey?{...super.resolveTelemetryMetadata(e,{result:t}),embeddingsGeneratedBy:"mcp"}:super.resolveTelemetryMetadata(e,{result:t})}isSearchStage(e){return"$vectorSearch"in e||"$search"in e||"$searchMeta"in e}isWriteStage(e){return"$out"in e||"$merge"in e}}t.AggregateTool=p,p.operationType="read"},43802:(e,t,n)=>{Object.defineProperty(t,"BJ",{value:!0}),t.On=t.R5=t.U$=void 0;var r=n(44558);Object.defineProperty(t,"U$",{enumerable:!0,get:function(){return r.translateToElectronProxyConfig}}),Object.defineProperty(t,"R5",{enumerable:!0,get:function(){return r.extractProxySecrets}}),Object.defineProperty(t,"On",{enumerable:!0,get:function(){return r.mergeProxySecrets}})},44216:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setManagedTimeout=function(e,t){let n=setTimeout((()=>{e()}),t);function r(){clearTimeout(n),n=void 0}return{cancel:r,restart:function(){r(),n=setTimeout((()=>{e()}),t)}}}},44558:(e,t,n)=>{var r=n(9606).URL,i=n(65994).process;function o(e){const t=new Map;let n="";for(const[r,i]of Object.entries(e)){if(void 0===i)continue;const e=r.toUpperCase();e.endsWith("_PROXY")&&"NO_PROXY"!==e&&t.set(e.replace(/_PROXY$/,"").toLowerCase(),i||"direct://"),"NO_PROXY"===e&&(n=i)}return{map:t,noProxy:n}}function a(e,t){if(!e)return!0;if("*"===e)return!1;for(const n of e.split(/[\s,]/)){let{host:e,port:r}=n.match(/(?<host>.+)(:(?<port>\d+)$)?/)?.groups??{};if(e||(e=n,r=""),(!r||t.port===r)&&(e===t.hostname||e.startsWith("*")&&t.hostname.endsWith(e.substring(1))))return!1}return!0}function s(e,t,n){if(e.proxy){const n=e.proxy;return"direct:"===new r(n).protocol?"":a(e.noProxyHosts||"",new r(t))?n:""}if(e.useEnvironmentVariableProxies){const{map:s,noProxy:c}=o(e.env??i.env),u=new r(t),l=(n?.overrideProtocol??u.protocol).replace(/:$/,""),h=[c,e.noProxyHosts].filter(Boolean).join(","),f=s.get(l)||s.get("all");return f&&a(h,u)?f:""}return""}function c(e){if("ssh:"===(e=new r(e.toString())).protocol)throw new Error(`Using ssh:// proxies for generic browser proxy usage is not supported (translating '${u(e)}')`);if(e.username||e.password)throw new Error(`Using authenticated proxies for generic browser proxy usage is not supported (translating '${u(e)}')`);if("http:"!==e.protocol&&"https:"!==e.protocol&&"socks5:"!==e.protocol)throw new Error(`Unsupported proxy protocol (translating '${u(e)}')`);if(e.search||e.hash)throw new Error(`Unsupported URL extensions in proxy specification (translating '${u(e)}')`);if(""===e.pathname)return e.toString();if("/"!==e.pathname)throw new Error(`Unsupported URL pathname in proxy specification (translating '${u(e)}')`);return e.toString().replace(/\/$/,"")}function u(e){const t=new r(e.toString());return t.password&&(t.password="(credential)"),t.toString()}Object.defineProperty(t,"__esModule",{value:!0}),t.proxyConfForEnvVars=o,t.proxyForUrl=s,t.translateToElectronProxyConfig=function(e){if(e.proxy){let t=e.proxy;return new r(t).protocol.startsWith("pac+")?(t=t.replace("pac+",""),{mode:"pac_script",pacScript:t.toString(),proxyBypassRules:e.noProxyHosts}):{mode:"fixed_servers",proxyRules:c(t),proxyBypassRules:e.noProxyHosts}}if(e.useEnvironmentVariableProxies){const t=[],n=[e.noProxyHosts],{map:r,noProxy:a}=o(e.env??i.env);for(const e of["http","https","ftp"]){const n=r.get(e)||r.get("all");n&&t.push(`${e}=${c(n)}`)}n.push(a);const s=t.join(";"),u=n.filter(Boolean).join(",")||void 0;return s?{mode:"fixed_servers",proxyBypassRules:u,proxyRules:s}:u?{proxyBypassRules:u}:{}}return{}},t.getSocks5OnlyProxyOptions=function(e,t){let n;if(void 0!==t?n=s(e,t):e.noProxyHosts||(n=e.proxy),!n)return;const i=new r(n);return"socks5:"!==i.protocol?void 0:{proxyHost:decodeURIComponent(i.hostname),proxyPort:+(i.port||1080),proxyUsername:decodeURIComponent(i.username)||void 0,proxyPassword:decodeURIComponent(i.password)||void 0}},t.extractProxySecrets=function(e){const t={};if(e.proxy){const n=new r(e.proxy);t.password=n.password,n.password="",e={...e,proxy:n.toString()}}return e.sshOptions&&(t.sshIdentityKeyPassphrase=e.sshOptions.identityKeyPassphrase,e={...e,sshOptions:{...e.sshOptions,identityKeyPassphrase:void 0}}),{secrets:JSON.stringify(t),proxyOptions:e}},t.mergeProxySecrets=function({proxyOptions:e,secrets:t}){const n=JSON.parse(t||"{}");if((n.username||n.password)&&e.proxy){const t=new r(e.proxy);t.password=n.password||"",e={...e,proxy:t.toString()}}return n.sshIdentityKeyPassphrase&&(e={...e,sshOptions:{...e.sshOptions,identityKeyPassphrase:n.sshIdentityKeyPassphrase}}),e},t.redactUrl=u},45334:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(78249),i=r.operators,o={maximum:{okStr:"<=",ok:i.LTE,fail:i.GT},minimum:{okStr:">=",ok:i.GTE,fail:i.LT},exclusiveMaximum:{okStr:"<",ok:i.LT,fail:i.GTE},exclusiveMinimum:{okStr:">",ok:i.GT,fail:i.LTE}},a={message:({keyword:e,schemaCode:t})=>r.str`must be ${o[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>r._`{comparison: ${o[e].okStr}, limit: ${t}}`},s={keyword:Object.keys(o),type:"number",schemaType:"number",$data:!0,error:a,code(e){const{keyword:t,data:n,schemaCode:i}=e;e.fail$data(r._`${n} ${o[t].fail} ${i} || isNaN(${n})`)}};t.default=s},45584:function(e,t,n){var r=n(65994).process,i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CompositeLogger=t.McpLogger=t.DiskLogger=t.ConsoleLogger=t.LoggerBase=t.LogId=void 0;const o=i(n(65981)),a=n(91174),s=n(23319),c=n(8763);t.LogId={serverStartFailure:(0,a.mongoLogId)(1000001),serverInitialized:(0,a.mongoLogId)(1000002),serverCloseRequested:(0,a.mongoLogId)(1000003),serverClosed:(0,a.mongoLogId)(1000004),serverCloseFailure:(0,a.mongoLogId)(1000005),serverDuplicateLoggers:(0,a.mongoLogId)(1000006),serverMcpClientSet:(0,a.mongoLogId)(1000007),atlasCheckCredentials:(0,a.mongoLogId)(1001001),atlasDeleteDatabaseUserFailure:(0,a.mongoLogId)(1001002),atlasConnectFailure:(0,a.mongoLogId)(1001003),atlasInspectFailure:(0,a.mongoLogId)(1001004),atlasConnectAttempt:(0,a.mongoLogId)(1001005),atlasConnectSucceeded:(0,a.mongoLogId)(1001006),atlasApiRevokeFailure:(0,a.mongoLogId)(1001007),atlasIpAccessListAdded:(0,a.mongoLogId)(1001008),atlasIpAccessListAddFailure:(0,a.mongoLogId)(1001009),telemetryDisabled:(0,a.mongoLogId)(1002001),telemetryEmitFailure:(0,a.mongoLogId)(1002002),telemetryEmitStart:(0,a.mongoLogId)(1002003),telemetryEmitSuccess:(0,a.mongoLogId)(1002004),telemetryMetadataError:(0,a.mongoLogId)(1002005),deviceIdResolutionError:(0,a.mongoLogId)(1002006),deviceIdTimeout:(0,a.mongoLogId)(1002007),telemetryClose:(0,a.mongoLogId)(1002008),toolExecute:(0,a.mongoLogId)(1003001),toolExecuteFailure:(0,a.mongoLogId)(1003002),toolDisabled:(0,a.mongoLogId)(1003003),toolMetadataChange:(0,a.mongoLogId)(1003004),mongodbConnectFailure:(0,a.mongoLogId)(1004001),mongodbDisconnectFailure:(0,a.mongoLogId)(1004002),mongodbConnectTry:(0,a.mongoLogId)(1004003),mongodbCursorCloseError:(0,a.mongoLogId)(1004004),mongodbIndexCheckFailure:(0,a.mongoLogId)(1004005),toolUpdateFailure:(0,a.mongoLogId)(1005001),resourceUpdateFailure:(0,a.mongoLogId)(1005002),updateToolMetadata:(0,a.mongoLogId)(1005003),toolValidationError:(0,a.mongoLogId)(1005004),streamableHttpTransportStarted:(0,a.mongoLogId)(1006001),streamableHttpTransportSessionCloseFailure:(0,a.mongoLogId)(1006002),streamableHttpTransportSessionCloseNotification:(0,a.mongoLogId)(1006003),streamableHttpTransportSessionCloseNotificationFailure:(0,a.mongoLogId)(1006004),streamableHttpTransportRequestFailure:(0,a.mongoLogId)(1006005),streamableHttpTransportCloseFailure:(0,a.mongoLogId)(1006006),streamableHttpTransportKeepAliveFailure:(0,a.mongoLogId)(1006007),streamableHttpTransportKeepAlive:(0,a.mongoLogId)(1006008),streamableHttpTransportHttpHostWarning:(0,a.mongoLogId)(1006009),exportCleanupError:(0,a.mongoLogId)(1007001),exportCreationError:(0,a.mongoLogId)(1007002),exportCreationCleanupError:(0,a.mongoLogId)(1007003),exportReadError:(0,a.mongoLogId)(1007004),exportCloseError:(0,a.mongoLogId)(1007005),exportedDataListError:(0,a.mongoLogId)(1007006),exportedDataAutoCompleteError:(0,a.mongoLogId)(1007007),exportLockError:(0,a.mongoLogId)(1007008),oidcFlow:(0,a.mongoLogId)(1008001),atlasPaSuggestedIndexesFailure:(0,a.mongoLogId)(1009001),atlasPaDropIndexSuggestionsFailure:(0,a.mongoLogId)(1009002),atlasPaSchemaAdviceFailure:(0,a.mongoLogId)(1009003),atlasPaSlowQueryLogsFailure:(0,a.mongoLogId)(1009004),atlasLocalDockerNotRunning:(0,a.mongoLogId)(1010001),atlasLocalUnsupportedPlatform:(0,a.mongoLogId)(1010002)};class u extends c.EventEmitter{constructor(e){super(),this.keychain=e,this.defaultUnredactedLogger="mcp"}log(e,t){const n=void 0!==t.noRedaction?t.noRedaction:this.defaultUnredactedLogger;this.logCore(e,{...t,message:this.redactIfNecessary(t.message,n)})}redactIfNecessary(e,t){return"boolean"==typeof t&&t||"string"==typeof t&&t===this.type||"object"==typeof t&&Array.isArray(t)&&this.type&&-1!==t.indexOf(this.type)?e:(0,s.redact)(e,this.keychain?.allSecrets??[])}info(e){this.log("info",e)}error(e){this.log("error",e)}debug(e){this.log("debug",e)}notice(e){this.log("notice",e)}warning(e){this.log("warning",e)}critical(e){this.log("critical",e)}alert(e){this.log("alert",e)}emergency(e){this.log("emergency",e)}mapToMongoDBLogLevel(e){switch(e){case"info":default:return"info";case"warning":return"warn";case"error":return"error";case"notice":case"debug":return"debug";case"critical":case"alert":case"emergency":return"fatal"}}}t.LoggerBase=u,t.ConsoleLogger=class extends u{constructor(e){super(e),this.type="console"}logCore(e,t){const{id:n,context:i,message:o}=t;console.error(`[${e.toUpperCase()}] ${n.__value} - ${i}: ${o} (${r.pid}${this.serializeAttributes(t.attributes)})`)}serializeAttributes(e){return e&&0!==Object.keys(e).length?`, ${Object.entries(e).map((([e,t])=>`${e}=${t}`)).join(", ")}`:""}},t.DiskLogger=class extends u{constructor(e,t,n){super(n),this.bufferedMessages=[],this.type="disk",this.initialize(e,t)}async initialize(e,t){try{await o.default.mkdir(e,{recursive:!0});const t=new a.MongoLogManager({directory:e,retentionDays:30,onwarn:console.warn,onerror:console.error,gzip:!1,retentionGB:1});await t.cleanupOldLogFiles(),this.logWriter=await t.createLogWriter();for(const e of this.bufferedMessages)this.logCore(e.level,e.payload);this.bufferedMessages=[],this.emit("initialized")}catch(e){t(e)}}logCore(e,t){if(!this.logWriter)return void this.bufferedMessages.push({level:e,payload:t});const{id:n,context:r,message:i}=t,o=this.mapToMongoDBLogLevel(e);this.logWriter[o]("MONGODB-MCP",n,r,i,t.attributes)}};class l extends u{constructor(e,t){super(t),this.server=e,this.type="mcp"}logCore(e,t){this.server.mcpServer.isConnected()&&(l.LOG_LEVELS.indexOf(this.server.mcpLogLevel)>l.LOG_LEVELS.indexOf(e)||this.server.mcpServer.server.sendLoggingMessage({level:e,data:`[${t.context}]: ${t.message}`}))}}t.McpLogger=l,l.LOG_LEVELS=["debug","info","notice","warning","error","critical","alert","emergency"],t.CompositeLogger=class extends u{constructor(...e){super(void 0),this.loggers=[],this.attributes={},this.loggers=e}addLogger(e){this.loggers.push(e)}log(e,t){for(const n of this.loggers){const r=Object.keys(this.attributes).length>0||t.attributes?{...this.attributes,...t.attributes}:void 0;n.log(e,{...t,attributes:r})}}logCore(){throw new Error("logCore should never be invoked on CompositeLogger")}setAttribute(e,t){this.attributes[e]=t}}},46096:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SwitchConnectionTool=void 0;const i=r(n(69761)),o=n(58203);class a extends o.MongoDBToolBase{constructor(e){super(e),this.name="switch-connection",this.description="Switch to a different MongoDB connection. If the user has configured a connection string or has previously called the connect tool, a connection is already established and there's no need to call this tool unless the user has explicitly requested to switch to a new instance.",this.argsShape={connectionString:i.default.string().optional().describe("MongoDB connection string to switch to (in the mongodb:// or mongodb+srv:// format). If a connection string is not provided, the connection string from the config will be used.")},e.session.on("connect",(()=>{this.enable()})),e.session.on("disconnect",(()=>{this.disable()}))}register(e){const t=super.register(e);return t&&!this.session.isConnectedToMongoDB&&this.disable(),t}async execute({connectionString:e}){return"string"!=typeof e?await this.session.connectToConfiguredConnection():await this.session.connectToMongoDB({connectionString:e}),{content:[{type:"text",text:"Successfully connected to MongoDB."}]}}}t.SwitchConnectionTool=a,a.operationType="connect"},46249:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdioServerTransport=void 0;const i=r(n(65994)),o=n(10083);t.StdioServerTransport=class{constructor(e=i.default.stdin,t=i.default.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new o.ReadBuffer,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}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(;;)try{const e=this._readBuffer.readMessage();if(null===e)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise((t=>{const n=(0,o.serializeMessage)(e);this._stdout.write(n)?t():this._stdout.once("drain",t)}))}}},46319:(e,t)=>{var n;Object.defineProperty(t,"__esModule",{value:!0}),t.MongoDBError=t.ErrorCodes=void 0,function(e){e[e.NotConnectedToMongoDB=1e6]="NotConnectedToMongoDB",e[e.MisconfiguredConnectionString=1000001]="MisconfiguredConnectionString",e[e.ForbiddenCollscan=1000002]="ForbiddenCollscan",e[e.ForbiddenWriteOperation=1000003]="ForbiddenWriteOperation",e[e.AtlasSearchNotSupported=1000004]="AtlasSearchNotSupported",e[e.NoEmbeddingsProviderConfigured=1000005]="NoEmbeddingsProviderConfigured",e[e.AtlasVectorSearchIndexNotFound=1000006]="AtlasVectorSearchIndexNotFound",e[e.AtlasVectorSearchInvalidQuery=1000007]="AtlasVectorSearchInvalidQuery",e[e.Unexpected=1000008]="Unexpected"}(n||(t.ErrorCodes=n={}));class r extends Error{constructor(e,t){super(t),this.code=e}}t.MongoDBError=r},46575:(e,t,n)=>{n.d(t,{Fp:()=>Dc,Jo:()=>kp,LP:()=>Sp,PV:()=>yp,R4:()=>Ai,rN:()=>Tu,yF:()=>up});var r=n(10873),i=n(96003),o=n(35196),a=n(80512),s=n(96652),c=n.n(s),u=(n(46410),n(76144)),l=n(46398),h=n(59389),f=n(92026),d=n(83008),g=n(27898),p=n(25072);function b(){return b=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},b.apply(null,arguments)}!function(){try{if(typeof document<"u"){var e=document.createElement("style");e.appendChild(document.createTextNode(".react-flow{direction:ltr;--xy-edge-stroke-default: #b1b1b7;--xy-edge-stroke-width-default: 1;--xy-edge-stroke-selected-default: #555;--xy-connectionline-stroke-default: #b1b1b7;--xy-connectionline-stroke-width-default: 1;--xy-attribution-background-color-default: rgba(255, 255, 255, .5);--xy-minimap-background-color-default: #fff;--xy-minimap-mask-background-color-default: rgb(240, 240, 240, .6);--xy-minimap-mask-stroke-color-default: transparent;--xy-minimap-mask-stroke-width-default: 1;--xy-minimap-node-background-color-default: #e2e2e2;--xy-minimap-node-stroke-color-default: transparent;--xy-minimap-node-stroke-width-default: 2;--xy-background-color-default: transparent;--xy-background-pattern-dots-color-default: #91919a;--xy-background-pattern-lines-color-default: #eee;--xy-background-pattern-cross-color-default: #e2e2e2;background-color:var(--xy-background-color, var(--xy-background-color-default));--xy-node-color-default: inherit;--xy-node-border-default: 1px solid #1a192b;--xy-node-background-color-default: #fff;--xy-node-group-background-color-default: rgba(240, 240, 240, .25);--xy-node-boxshadow-hover-default: 0 1px 4px 1px rgba(0, 0, 0, .08);--xy-node-boxshadow-selected-default: 0 0 0 .5px #1a192b;--xy-node-border-radius-default: 3px;--xy-handle-background-color-default: #1a192b;--xy-handle-border-color-default: #fff;--xy-selection-background-color-default: rgba(0, 89, 220, .08);--xy-selection-border-default: 1px dotted rgba(0, 89, 220, .8);--xy-controls-button-background-color-default: #fefefe;--xy-controls-button-background-color-hover-default: #f4f4f4;--xy-controls-button-color-default: inherit;--xy-controls-button-color-hover-default: inherit;--xy-controls-button-border-color-default: #eee;--xy-controls-box-shadow-default: 0 0 2px 1px rgba(0, 0, 0, .08);--xy-edge-label-background-color-default: #ffffff;--xy-edge-label-color-default: inherit;--xy-resize-background-color-default: #3367d9}.react-flow.dark{--xy-edge-stroke-default: #3e3e3e;--xy-edge-stroke-width-default: 1;--xy-edge-stroke-selected-default: #727272;--xy-connectionline-stroke-default: #b1b1b7;--xy-connectionline-stroke-width-default: 1;--xy-attribution-background-color-default: rgba(150, 150, 150, .25);--xy-minimap-background-color-default: #141414;--xy-minimap-mask-background-color-default: rgb(60, 60, 60, .6);--xy-minimap-mask-stroke-color-default: transparent;--xy-minimap-mask-stroke-width-default: 1;--xy-minimap-node-background-color-default: #2b2b2b;--xy-minimap-node-stroke-color-default: transparent;--xy-minimap-node-stroke-width-default: 2;--xy-background-color-default: #141414;--xy-background-pattern-dots-color-default: #777;--xy-background-pattern-lines-color-default: #777;--xy-background-pattern-cross-color-default: #777;--xy-node-color-default: #f8f8f8;--xy-node-border-default: 1px solid #3c3c3c;--xy-node-background-color-default: #1e1e1e;--xy-node-group-background-color-default: rgba(240, 240, 240, .25);--xy-node-boxshadow-hover-default: 0 1px 4px 1px rgba(255, 255, 255, .08);--xy-node-boxshadow-selected-default: 0 0 0 .5px #999;--xy-handle-background-color-default: #bebebe;--xy-handle-border-color-default: #1e1e1e;--xy-selection-background-color-default: rgba(200, 200, 220, .08);--xy-selection-border-default: 1px dotted rgba(200, 200, 220, .8);--xy-controls-button-background-color-default: #2b2b2b;--xy-controls-button-background-color-hover-default: #3e3e3e;--xy-controls-button-color-default: #f8f8f8;--xy-controls-button-color-hover-default: #fff;--xy-controls-button-border-color-default: #5b5b5b;--xy-controls-box-shadow-default: 0 0 2px 1px rgba(0, 0, 0, .08);--xy-edge-label-background-color-default: #141414;--xy-edge-label-color-default: #f8f8f8}.react-flow__background{background-color:var(--xy-background-color, var(--xy-background-color-props, var(--xy-background-color-default)));pointer-events:none;z-index:-1}.react-flow__container{position:absolute;width:100%;height:100%;top:0;left:0}.react-flow__pane{z-index:1}.react-flow__pane.draggable{cursor:grab}.react-flow__pane.dragging{cursor:grabbing}.react-flow__pane.selection{cursor:pointer}.react-flow__viewport{transform-origin:0 0;z-index:2;pointer-events:none}.react-flow__renderer{z-index:4}.react-flow__selection{z-index:6}.react-flow__nodesselection-rect:focus,.react-flow__nodesselection-rect:focus-visible{outline:none}.react-flow__edge-path{stroke:var(--xy-edge-stroke, var(--xy-edge-stroke-default));stroke-width:var(--xy-edge-stroke-width, var(--xy-edge-stroke-width-default));fill:none}.react-flow__connection-path{stroke:var(--xy-connectionline-stroke, var(--xy-connectionline-stroke-default));stroke-width:var(--xy-connectionline-stroke-width, var(--xy-connectionline-stroke-width-default));fill:none}.react-flow .react-flow__edges{position:absolute}.react-flow .react-flow__edges svg{overflow:visible;position:absolute;pointer-events:none}.react-flow__edge{pointer-events:visibleStroke}.react-flow__edge.selectable{cursor:pointer}.react-flow__edge.animated path{stroke-dasharray:5;animation:dashdraw .5s linear infinite}.react-flow__edge.animated path.react-flow__edge-interaction{stroke-dasharray:none;animation:none}.react-flow__edge.inactive{pointer-events:none}.react-flow__edge.selected,.react-flow__edge:focus,.react-flow__edge:focus-visible{outline:none}.react-flow__edge.selected .react-flow__edge-path,.react-flow__edge.selectable:focus .react-flow__edge-path,.react-flow__edge.selectable:focus-visible .react-flow__edge-path{stroke:var(--xy-edge-stroke-selected, var(--xy-edge-stroke-selected-default))}.react-flow__edge-textwrapper{pointer-events:all}.react-flow__edge .react-flow__edge-text{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.react-flow__connection{pointer-events:none}.react-flow__connection .animated{stroke-dasharray:5;animation:dashdraw .5s linear infinite}svg.react-flow__connectionline{z-index:1001;overflow:visible;position:absolute}.react-flow__nodes{pointer-events:none;transform-origin:0 0}.react-flow__node{position:absolute;-webkit-user-select:none;-moz-user-select:none;user-select:none;pointer-events:all;transform-origin:0 0;box-sizing:border-box;cursor:default}.react-flow__node.selectable{cursor:pointer}.react-flow__node.draggable{cursor:grab;pointer-events:all}.react-flow__node.draggable.dragging{cursor:grabbing}.react-flow__nodesselection{z-index:3;transform-origin:left top;pointer-events:none}.react-flow__nodesselection-rect{position:absolute;pointer-events:all;cursor:grab}.react-flow__handle{position:absolute;pointer-events:none;min-width:5px;min-height:5px;width:6px;height:6px;background-color:var(--xy-handle-background-color, var(--xy-handle-background-color-default));border:1px solid var(--xy-handle-border-color, var(--xy-handle-border-color-default));border-radius:100%}.react-flow__handle.connectingfrom{pointer-events:all}.react-flow__handle.connectionindicator{pointer-events:all;cursor:crosshair}.react-flow__handle-bottom{top:auto;left:50%;bottom:0;transform:translate(-50%,50%)}.react-flow__handle-top{top:0;left:50%;transform:translate(-50%,-50%)}.react-flow__handle-left{top:50%;left:0;transform:translate(-50%,-50%)}.react-flow__handle-right{top:50%;right:0;transform:translate(50%,-50%)}.react-flow__edgeupdater{cursor:move;pointer-events:all}.react-flow__panel{position:absolute;z-index:5;margin:15px}.react-flow__panel.top{top:0}.react-flow__panel.bottom{bottom:0}.react-flow__panel.top.center,.react-flow__panel.bottom.center{left:50%;transform:translate(-50%)}.react-flow__panel.left{left:0}.react-flow__panel.right{right:0}.react-flow__panel.left.center,.react-flow__panel.right.center{top:50%;transform:translateY(-50%)}.react-flow__attribution{font-size:10px;background:var(--xy-attribution-background-color, var(--xy-attribution-background-color-default));padding:2px 3px;margin:0}.react-flow__attribution a{text-decoration:none;color:#999}@keyframes dashdraw{0%{stroke-dashoffset:10}}.react-flow__edgelabel-renderer{position:absolute;width:100%;height:100%;pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;left:0;top:0}.react-flow__viewport-portal{position:absolute;width:100%;height:100%;left:0;top:0;-webkit-user-select:none;-moz-user-select:none;user-select:none}.react-flow__minimap{background:var( --xy-minimap-background-color-props, var(--xy-minimap-background-color, var(--xy-minimap-background-color-default)) )}.react-flow__minimap-svg{display:block}.react-flow__minimap-mask{fill:var( --xy-minimap-mask-background-color-props, var(--xy-minimap-mask-background-color, var(--xy-minimap-mask-background-color-default)) );stroke:var( --xy-minimap-mask-stroke-color-props, var(--xy-minimap-mask-stroke-color, var(--xy-minimap-mask-stroke-color-default)) );stroke-width:var( --xy-minimap-mask-stroke-width-props, var(--xy-minimap-mask-stroke-width, var(--xy-minimap-mask-stroke-width-default)) )}.react-flow__minimap-node{fill:var( --xy-minimap-node-background-color-props, var(--xy-minimap-node-background-color, var(--xy-minimap-node-background-color-default)) );stroke:var( --xy-minimap-node-stroke-color-props, var(--xy-minimap-node-stroke-color, var(--xy-minimap-node-stroke-color-default)) );stroke-width:var( --xy-minimap-node-stroke-width-props, var(--xy-minimap-node-stroke-width, var(--xy-minimap-node-stroke-width-default)) )}.react-flow__background-pattern.dots{fill:var( --xy-background-pattern-color-props, var(--xy-background-pattern-color, var(--xy-background-pattern-dots-color-default)) )}.react-flow__background-pattern.lines{stroke:var( --xy-background-pattern-color-props, var(--xy-background-pattern-color, var(--xy-background-pattern-lines-color-default)) )}.react-flow__background-pattern.cross{stroke:var( --xy-background-pattern-color-props, var(--xy-background-pattern-color, var(--xy-background-pattern-cross-color-default)) )}.react-flow__controls{display:flex;flex-direction:column;box-shadow:var(--xy-controls-box-shadow, var(--xy-controls-box-shadow-default))}.react-flow__controls.horizontal{flex-direction:row}.react-flow__controls-button{display:flex;justify-content:center;align-items:center;height:26px;width:26px;padding:4px;border:none;background:var(--xy-controls-button-background-color, var(--xy-controls-button-background-color-default));border-bottom:1px solid var( --xy-controls-button-border-color-props, var(--xy-controls-button-border-color, var(--xy-controls-button-border-color-default)) );color:var( --xy-controls-button-color-props, var(--xy-controls-button-color, var(--xy-controls-button-color-default)) );cursor:pointer;-webkit-user-select:none;-moz-user-select:none;user-select:none}.react-flow__controls-button svg{width:100%;max-width:12px;max-height:12px;fill:currentColor}.react-flow__edge.updating .react-flow__edge-path{stroke:#777}.react-flow__edge-text{font-size:10px}.react-flow__node.selectable:focus,.react-flow__node.selectable:focus-visible{outline:none}.react-flow__node-input,.react-flow__node-default,.react-flow__node-output,.react-flow__node-group{padding:10px;border-radius:var(--xy-node-border-radius, var(--xy-node-border-radius-default));width:150px;font-size:12px;color:var(--xy-node-color, var(--xy-node-color-default));text-align:center;border:var(--xy-node-border, var(--xy-node-border-default));background-color:var(--xy-node-background-color, var(--xy-node-background-color-default))}.react-flow__node-input.selectable:hover,.react-flow__node-default.selectable:hover,.react-flow__node-output.selectable:hover,.react-flow__node-group.selectable:hover{box-shadow:var(--xy-node-boxshadow-hover, var(--xy-node-boxshadow-hover-default))}.react-flow__node-input.selectable.selected,.react-flow__node-input.selectable:focus,.react-flow__node-input.selectable:focus-visible,.react-flow__node-default.selectable.selected,.react-flow__node-default.selectable:focus,.react-flow__node-default.selectable:focus-visible,.react-flow__node-output.selectable.selected,.react-flow__node-output.selectable:focus,.react-flow__node-output.selectable:focus-visible,.react-flow__node-group.selectable.selected,.react-flow__node-group.selectable:focus,.react-flow__node-group.selectable:focus-visible{box-shadow:var(--xy-node-boxshadow-selected, var(--xy-node-boxshadow-selected-default))}.react-flow__node-group{background-color:var(--xy-node-group-background-color, var(--xy-node-group-background-color-default))}.react-flow__nodesselection-rect,.react-flow__selection{background:var(--xy-selection-background-color, var(--xy-selection-background-color-default));border:var(--xy-selection-border, var(--xy-selection-border-default))}.react-flow__nodesselection-rect:focus,.react-flow__nodesselection-rect:focus-visible,.react-flow__selection:focus,.react-flow__selection:focus-visible{outline:none}.react-flow__controls-button:hover{background:var( --xy-controls-button-background-color-hover-props, var(--xy-controls-button-background-color-hover, var(--xy-controls-button-background-color-hover-default)) );color:var( --xy-controls-button-color-hover-props, var(--xy-controls-button-color-hover, var(--xy-controls-button-color-hover-default)) )}.react-flow__controls-button:disabled{pointer-events:none}.react-flow__controls-button:disabled svg{fill-opacity:.4}.react-flow__controls-button:last-child{border-bottom:none}.react-flow__resize-control{position:absolute}.react-flow__resize-control.left,.react-flow__resize-control.right{cursor:ew-resize}.react-flow__resize-control.top,.react-flow__resize-control.bottom{cursor:ns-resize}.react-flow__resize-control.top.left,.react-flow__resize-control.bottom.right{cursor:nwse-resize}.react-flow__resize-control.bottom.left,.react-flow__resize-control.top.right{cursor:nesw-resize}.react-flow__resize-control.handle{width:4px;height:4px;border:1px solid #fff;border-radius:1px;background-color:var(--xy-resize-background-color, var(--xy-resize-background-color-default));transform:translate(-50%,-50%)}.react-flow__resize-control.handle.left{left:0;top:50%}.react-flow__resize-control.handle.right{left:100%;top:50%}.react-flow__resize-control.handle.top{left:50%;top:0}.react-flow__resize-control.handle.bottom{left:50%;top:100%}.react-flow__resize-control.handle.top.left,.react-flow__resize-control.handle.bottom.left{left:0}.react-flow__resize-control.handle.top.right,.react-flow__resize-control.handle.bottom.right{left:100%}.react-flow__resize-control.line{border-color:var(--xy-resize-background-color, var(--xy-resize-background-color-default));border-width:0;border-style:solid}.react-flow__resize-control.line.left,.react-flow__resize-control.line.right{width:1px;transform:translate(-50%);top:0;height:100%}.react-flow__resize-control.line.left{left:0;border-left-width:1px}.react-flow__resize-control.line.right{left:100%;border-right-width:1px}.react-flow__resize-control.line.top,.react-flow__resize-control.line.bottom{height:1px;transform:translateY(-50%);left:0;width:100%}.react-flow__resize-control.line.top{top:0;border-top-width:1px}.react-flow__resize-control.line.bottom{border-bottom-width:1px;top:100%}.react-flow__edge-textbg{fill:var(--xy-edge-label-background-color, var(--xy-edge-label-background-color-default))}.react-flow__edge-text{fill:var(--xy-edge-label-color, var(--xy-edge-label-color-default))}")),document.head.appendChild(e)}}catch(e){console.error("vite-plugin-css-injected-by-js",e)}}();var m={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,scale:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1};function w(e){var t=Object.create(null);return function(n){return void 0===t[n]&&(t[n]=e(n)),t[n]}}var v=/[A-Z]|^ms/g,y=/_EMO_([^_]+?)_([^]*?)_EMO_/g,S=function(e){return 45===e.charCodeAt(1)},k=function(e){return null!=e&&"boolean"!=typeof e},E=w((function(e){return S(e)?e:e.replace(v,"-$&").toLowerCase()})),x=function(e,t){switch(e){case"animation":case"animationName":if("string"==typeof t)return t.replace(y,(function(e,t,n){return T={name:t,styles:n,next:T},t}))}return 1===m[e]||S(e)||"number"!=typeof t||0===t?t:t+"px"};function M(e,t,n){if(null==n)return"";var r=n;if(void 0!==r.__emotion_styles)return r;switch(typeof n){case"boolean":return"";case"object":var i=n;if(1===i.anim)return T={name:i.name,styles:i.styles,next:T},i.name;var o=n;if(void 0!==o.styles){var a=o.next;if(void 0!==a)for(;void 0!==a;)T={name:a.name,styles:a.styles,next:T},a=a.next;return o.styles+";"}return function(e,t,n){var r="";if(Array.isArray(n))for(var i=0;i<n.length;i++)r+=M(e,t,n[i])+";";else for(var o in n){var a=n[o];if("object"!=typeof a){var s=a;null!=t&&void 0!==t[s]?r+=o+"{"+t[s]+"}":k(s)&&(r+=E(o)+":"+x(o,s)+";")}else if(!Array.isArray(a)||"string"!=typeof a[0]||null!=t&&void 0!==t[a[0]]){var c=M(e,t,a);switch(o){case"animation":case"animationName":r+=E(o)+":"+c+";";break;default:r+=o+"{"+c+"}"}}else for(var u=0;u<a.length;u++)k(a[u])&&(r+=E(o)+":"+x(o,a[u])+";")}return r}(e,t,n);case"function":if(void 0!==e){var s=T,c=n(e);return T=s,M(e,t,c)}}var u=n;if(null==t)return u;var l=t[u];return void 0!==l?l:u}var T,C=/label:\s*([^\s;{]+)\s*(;|$)/g,_=!!s.useInsertionEffect&&s.useInsertionEffect||function(e){return e()},P=function(e,t,n){var r=e.key+"-"+t.name;!1===n&&void 0===e.registered[r]&&(e.registered[r]=t.styles)},I=/^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|disableRemotePlayback|download|draggable|encType|enterKeyHint|fetchpriority|fetchPriority|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/,A=w((function(e){return I.test(e)||111===e.charCodeAt(0)&&110===e.charCodeAt(1)&&e.charCodeAt(2)<91})),O=A,j=function(e){return"theme"!==e},$=function(e){return"string"==typeof e&&e.charCodeAt(0)>96?O:j},R=function(e,t,n){var r;if(t){var i=t.shouldForwardProp;r=e.__emotion_forwardProp&&i?function(t){return e.__emotion_forwardProp(t)&&i(t)}:i}return"function"!=typeof r&&n&&(r=e.__emotion_forwardProp),r},N=function(e){var t=e.cache,n=e.serialized,r=e.isStringTag;return P(t,n,r),_((function(){return function(e,t,n){P(e,t,n);var r=e.key+"-"+t.name;if(void 0===e.inserted[t.name]){var i=t;do{e.insert(t===i?"."+r:"",i,e.sheet,!0),i=i.next}while(void 0!==i)}}(t,n,r)})),null},L=function e(t,n){var r,i,a=t.__emotion_real===t,c=a&&t.__emotion_base||t;void 0!==n&&(r=n.label,i=n.target);var u=R(t,n,a),l=u||$(c),h=!l("as");return function(){var f=arguments,d=a&&void 0!==t.__emotion_styles?t.__emotion_styles.slice(0):[];if(void 0!==r&&d.push("label:"+r+";"),null==f[0]||void 0===f[0].raw)d.push.apply(d,f);else{var g=f[0];d.push(g[0]);for(var p=f.length,m=1;m<p;m++)d.push(f[m],g[m])}var w=(0,o.w)((function(e,t,n){var r=h&&e.as||c,a="",f=[],g=e;if(null==e.theme){for(var p in g={},e)g[p]=e[p];g.theme=s.useContext(o.T)}"string"==typeof e.className?a=function(e,t,n){var r="";return n.split(" ").forEach((function(n){void 0!==e[n]?t.push(e[n]+";"):n&&(r+=n+" ")})),r}(t.registered,f,e.className):null!=e.className&&(a=e.className+" ");var b=function(e,t,n){if(1===e.length&&"object"==typeof e[0]&&null!==e[0]&&void 0!==e[0].styles)return e[0];var r=!0,i="";T=void 0;var o=e[0];null==o||void 0===o.raw?(r=!1,i+=M(n,t,o)):i+=o[0];for(var a=1;a<e.length;a++)i+=M(n,t,e[a]),r&&(i+=o[a]);C.lastIndex=0;for(var s,c="";null!==(s=C.exec(i));)c+="-"+s[1];var u=function(e){for(var t,n=0,r=0,i=e.length;i>=4;++r,i-=4)t=1540483477*(65535&(t=255&e.charCodeAt(r)|(255&e.charCodeAt(++r))<<8|(255&e.charCodeAt(++r))<<16|(255&e.charCodeAt(++r))<<24))+(59797*(t>>>16)<<16),n=1540483477*(65535&(t^=t>>>24))+(59797*(t>>>16)<<16)^1540483477*(65535&n)+(59797*(n>>>16)<<16);switch(i){case 3:n^=(255&e.charCodeAt(r+2))<<16;case 2:n^=(255&e.charCodeAt(r+1))<<8;case 1:n=1540483477*(65535&(n^=255&e.charCodeAt(r)))+(59797*(n>>>16)<<16)}return(((n=1540483477*(65535&(n^=n>>>13))+(59797*(n>>>16)<<16))^n>>>15)>>>0).toString(36)}(i)+c;return{name:u,styles:i,next:T}}(d.concat(f),t.registered,g);a+=t.key+"-"+b.name,void 0!==i&&(a+=" "+i);var m=h&&void 0===u?$(r):l,w={};for(var v in e)h&&"as"===v||m(v)&&(w[v]=e[v]);return w.className=a,n&&(w.ref=n),s.createElement(s.Fragment,null,s.createElement(N,{cache:t,serialized:b,isStringTag:"string"==typeof r}),s.createElement(r,w))}));return w.displayName=void 0!==r?r:"Styled("+("string"==typeof c?c:c.displayName||c.name||"Component")+")",w.defaultProps=t.defaultProps,w.__emotion_real=w,w.__emotion_base=c,w.__emotion_styles=d,w.__emotion_forwardProp=u,Object.defineProperty(w,"toString",{value:function(){return"."+i}}),w.withComponent=function(t,r){return e(t,b({},n,r,{shouldForwardProp:R(w,r,!0)})).apply(void 0,d)},w}}.bind(null);function D(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","marquee","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","tspan"].forEach((function(e){L[e]=L(e)}));var F,B,z={exports:{}},U=z.exports={};function q(){throw new Error("setTimeout has not been defined")}function H(){throw new Error("clearTimeout has not been defined")}function J(e){if(F===setTimeout)return setTimeout(e,0);if((F===q||!F)&&setTimeout)return F=setTimeout,setTimeout(e,0);try{return F(e,0)}catch{try{return F.call(null,e,0)}catch{return F.call(this,e,0)}}}!function(){try{F="function"==typeof setTimeout?setTimeout:q}catch{F=q}try{B="function"==typeof clearTimeout?clearTimeout:H}catch{B=H}}();var G,V=[],K=!1,W=-1;function X(){!K||!G||(K=!1,G.length?V=G.concat(V):W=-1,V.length&&Y())}function Y(){if(!K){var e=J(X);K=!0;for(var t=V.length;t;){for(G=V,V=[];++W<t;)G&&G[W].run();W=-1,t=V.length}G=null,K=!1,function(e){if(B===clearTimeout)return clearTimeout(e);if((B===H||!B)&&clearTimeout)return B=clearTimeout,clearTimeout(e);try{return B(e)}catch{try{return B.call(null,e)}catch{return B.call(this,e)}}}(e)}}function Q(e,t){this.fun=e,this.array=t}function Z(){}U.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];V.push(new Q(e,t)),1===V.length&&!K&&J(Y)},Q.prototype.run=function(){this.fun.apply(null,this.array)},U.title="browser",U.browser=!0,U.env={},U.argv=[],U.version="",U.versions={},U.on=Z,U.addListener=Z,U.once=Z,U.off=Z,U.removeListener=Z,U.removeAllListeners=Z,U.emit=Z,U.prependListener=Z,U.prependOnceListener=Z,U.listeners=function(e){return[]},U.binding=function(e){throw new Error("process.binding is not supported")},U.cwd=function(){return"/"},U.chdir=function(e){throw new Error("process.chdir is not supported")},U.umask=function(){return 0};const ee=D(z.exports);function te(e){if("string"==typeof e||"number"==typeof e)return""+e;let t="";if(Array.isArray(e))for(let n,r=0;r<e.length;r++)""!==(n=te(e[r]))&&(t+=(t&&" ")+n);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var ne={value:()=>{}};function re(){for(var e,t=0,n=arguments.length,r={};t<n;++t){if(!(e=arguments[t]+"")||e in r||/[\s.]/.test(e))throw new Error("illegal type: "+e);r[e]=[]}return new ie(r)}function ie(e){this._=e}function oe(e,t){for(var n,r=0,i=e.length;r<i;++r)if((n=e[r]).name===t)return n.value}function ae(e,t,n){for(var r=0,i=e.length;r<i;++r)if(e[r].name===t){e[r]=ne,e=e.slice(0,r).concat(e.slice(r+1));break}return null!=n&&e.push({name:t,value:n}),e}ie.prototype=re.prototype={constructor:ie,on:function(e,t){var n,r=this._,i=function(e,t){return e.trim().split(/^|\s+/).map((function(e){var n="",r=e.indexOf(".");if(r>=0&&(n=e.slice(r+1),e=e.slice(0,r)),e&&!t.hasOwnProperty(e))throw new Error("unknown type: "+e);return{type:e,name:n}}))}(e+"",r),o=-1,a=i.length;if(!(arguments.length<2)){if(null!=t&&"function"!=typeof t)throw new Error("invalid callback: "+t);for(;++o<a;)if(n=(e=i[o]).type)r[n]=ae(r[n],e.name,t);else if(null==t)for(n in r)r[n]=ae(r[n],e.name,null);return this}for(;++o<a;)if((n=(e=i[o]).type)&&(n=oe(r[n],e.name)))return n},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new ie(e)},call:function(e,t){if((n=arguments.length-2)>0)for(var n,r,i=new Array(n),o=0;o<n;++o)i[o]=arguments[o+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(o=0,n=(r=this._[e]).length;o<n;++o)r[o].value.apply(t,i)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],i=0,o=r.length;i<o;++i)r[i].value.apply(t,n)}};var se="http://www.w3.org/1999/xhtml";const ce={svg:"http://www.w3.org/2000/svg",xhtml:se,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function ue(e){var t=e+="",n=t.indexOf(":");return n>=0&&"xmlns"!==(t=e.slice(0,n))&&(e=e.slice(n+1)),ce.hasOwnProperty(t)?{space:ce[t],local:e}:e}function le(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===se&&t.documentElement.namespaceURI===se?t.createElement(e):t.createElementNS(n,e)}}function he(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function fe(e){var t=ue(e);return(t.local?he:le)(t)}function de(){}function ge(e){return null==e?de:function(){return this.querySelector(e)}}function pe(){return[]}function be(e){return null==e?pe:function(){return this.querySelectorAll(e)}}function me(e){return function(){return this.matches(e)}}function we(e){return function(t){return t.matches(e)}}var ve=Array.prototype.find;function ye(){return this.firstElementChild}var Se=Array.prototype.filter;function ke(){return Array.from(this.children)}function Ee(e){return new Array(e.length)}function xe(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function Me(e,t,n,r,i,o){for(var a,s=0,c=t.length,u=o.length;s<u;++s)(a=t[s])?(a.__data__=o[s],r[s]=a):n[s]=new xe(e,o[s]);for(;s<c;++s)(a=t[s])&&(i[s]=a)}function Te(e,t,n,r,i,o,a){var s,c,u,l=new Map,h=t.length,f=o.length,d=new Array(h);for(s=0;s<h;++s)(c=t[s])&&(d[s]=u=a.call(c,c.__data__,s,t)+"",l.has(u)?i[s]=c:l.set(u,c));for(s=0;s<f;++s)u=a.call(e,o[s],s,o)+"",(c=l.get(u))?(r[s]=c,c.__data__=o[s],l.delete(u)):n[s]=new xe(e,o[s]);for(s=0;s<h;++s)(c=t[s])&&l.get(d[s])===c&&(i[s]=c)}function Ce(e){return e.__data__}function _e(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function Pe(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function Ie(e){return function(){this.removeAttribute(e)}}function Ae(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Oe(e,t){return function(){this.setAttribute(e,t)}}function je(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function $e(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}}function Re(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function Ne(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function Le(e){return function(){this.style.removeProperty(e)}}function De(e,t,n){return function(){this.style.setProperty(e,t,n)}}function Fe(e,t,n){return function(){var r=t.apply(this,arguments);null==r?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function Be(e,t){return e.style.getPropertyValue(t)||Ne(e).getComputedStyle(e,null).getPropertyValue(t)}function ze(e){return function(){delete this[e]}}function Ue(e,t){return function(){this[e]=t}}function qe(e,t){return function(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}}function He(e){return e.trim().split(/^|\s+/)}function Je(e){return e.classList||new Ge(e)}function Ge(e){this._node=e,this._names=He(e.getAttribute("class")||"")}function Ve(e,t){for(var n=Je(e),r=-1,i=t.length;++r<i;)n.add(t[r])}function Ke(e,t){for(var n=Je(e),r=-1,i=t.length;++r<i;)n.remove(t[r])}function We(e){return function(){Ve(this,e)}}function Xe(e){return function(){Ke(this,e)}}function Ye(e,t){return function(){(t.apply(this,arguments)?Ve:Ke)(this,e)}}function Qe(){this.textContent=""}function Ze(e){return function(){this.textContent=e}}function et(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function tt(){this.innerHTML=""}function nt(e){return function(){this.innerHTML=e}}function rt(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function it(){this.nextSibling&&this.parentNode.appendChild(this)}function ot(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function at(){return null}function st(){var e=this.parentNode;e&&e.removeChild(this)}function ct(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function ut(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function lt(e){return function(){var t=this.__on;if(t){for(var n,r=0,i=-1,o=t.length;r<o;++r)n=t[r],e.type&&n.type!==e.type||n.name!==e.name?t[++i]=n:this.removeEventListener(n.type,n.listener,n.options);++i?t.length=i:delete this.__on}}}function ht(e,t,n){return function(){var r,i=this.__on,o=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(i)for(var a=0,s=i.length;a<s;++a)if((r=i[a]).type===e.type&&r.name===e.name)return this.removeEventListener(r.type,r.listener,r.options),this.addEventListener(r.type,r.listener=o,r.options=n),void(r.value=t);this.addEventListener(e.type,o,n),r={type:e.type,name:e.name,value:t,listener:o,options:n},i?i.push(r):this.__on=[r]}}function ft(e,t,n){var r=Ne(e),i=r.CustomEvent;"function"==typeof i?i=new i(t,n):(i=r.document.createEvent("Event"),n?(i.initEvent(t,n.bubbles,n.cancelable),i.detail=n.detail):i.initEvent(t,!1,!1)),e.dispatchEvent(i)}function dt(e,t){return function(){return ft(this,e,t)}}function gt(e,t){return function(){return ft(this,e,t.apply(this,arguments))}}xe.prototype={constructor:xe,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}},Ge.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var pt=[null];function bt(e,t){this._groups=e,this._parents=t}function mt(){return new bt([[document.documentElement]],pt)}function wt(e){return"string"==typeof e?new bt([[document.querySelector(e)]],[document.documentElement]):new bt([[e]],pt)}function vt(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,[(r=r.matrixTransform(t.getScreenCTM().inverse())).x,r.y]}if(t.getBoundingClientRect){var i=t.getBoundingClientRect();return[e.clientX-i.left-t.clientLeft,e.clientY-i.top-t.clientTop]}}return[e.pageX,e.pageY]}bt.prototype=mt.prototype={constructor:bt,select:function(e){"function"!=typeof e&&(e=ge(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o,a,s=t[i],c=s.length,u=r[i]=new Array(c),l=0;l<c;++l)(o=s[l])&&(a=e.call(o,o.__data__,l,s))&&("__data__"in o&&(a.__data__=o.__data__),u[l]=a);return new bt(r,this._parents)},selectAll:function(e){e="function"==typeof e?function(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}(e):be(e);for(var t=this._groups,n=t.length,r=[],i=[],o=0;o<n;++o)for(var a,s=t[o],c=s.length,u=0;u<c;++u)(a=s[u])&&(r.push(e.call(a,a.__data__,u,s)),i.push(a));return new bt(r,i)},selectChild:function(e){return this.select(null==e?ye:function(e){return function(){return ve.call(this.children,e)}}("function"==typeof e?e:we(e)))},selectChildren:function(e){return this.selectAll(null==e?ke:function(e){return function(){return Se.call(this.children,e)}}("function"==typeof e?e:we(e)))},filter:function(e){"function"!=typeof e&&(e=me(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o,a=t[i],s=a.length,c=r[i]=[],u=0;u<s;++u)(o=a[u])&&e.call(o,o.__data__,u,a)&&c.push(o);return new bt(r,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,Ce);var n=t?Te:Me,r=this._parents,i=this._groups;"function"!=typeof e&&(e=function(e){return function(){return e}}(e));for(var o=i.length,a=new Array(o),s=new Array(o),c=new Array(o),u=0;u<o;++u){var l=r[u],h=i[u],f=h.length,d=_e(e.call(l,l&&l.__data__,u,r)),g=d.length,p=s[u]=new Array(g),b=a[u]=new Array(g);n(l,h,p,b,c[u]=new Array(f),d,t);for(var m,w,v=0,y=0;v<g;++v)if(m=p[v]){for(v>=y&&(y=v+1);!(w=b[y])&&++y<g;);m._next=w||null}}return(a=new bt(a,r))._enter=s,a._exit=c,a},enter:function(){return new bt(this._enter||this._groups.map(Ee),this._parents)},exit:function(){return new bt(this._exit||this._groups.map(Ee),this._parents)},join:function(e,t,n){var r=this.enter(),i=this,o=this.exit();return"function"==typeof e?(r=e(r))&&(r=r.selection()):r=r.append(e+""),null!=t&&(i=t(i))&&(i=i.selection()),null==n?o.remove():n(o),r&&i?r.merge(i).order():i},merge:function(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,i=n.length,o=r.length,a=Math.min(i,o),s=new Array(i),c=0;c<a;++c)for(var u,l=n[c],h=r[c],f=l.length,d=s[c]=new Array(f),g=0;g<f;++g)(u=l[g]||h[g])&&(d[g]=u);for(;c<i;++c)s[c]=n[c];return new bt(s,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r,i=e[t],o=i.length-1,a=i[o];--o>=0;)(r=i[o])&&(a&&4^r.compareDocumentPosition(a)&&a.parentNode.insertBefore(r,a),a=r);return this},sort:function(e){function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}e||(e=Pe);for(var n=this._groups,r=n.length,i=new Array(r),o=0;o<r;++o){for(var a,s=n[o],c=s.length,u=i[o]=new Array(c),l=0;l<c;++l)(a=s[l])&&(u[l]=a);u.sort(t)}return new bt(i,this._parents).order()},call:function(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],i=0,o=r.length;i<o;++i){var a=r[i];if(a)return a}return null},size:function(){let e=0;for(const t of this)++e;return e},empty:function(){return!this.node()},each:function(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var i,o=t[n],a=0,s=o.length;a<s;++a)(i=o[a])&&e.call(i,i.__data__,a,o);return this},attr:function(e,t){var n=ue(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((null==t?n.local?Ae:Ie:"function"==typeof t?n.local?Re:$e:n.local?je:Oe)(n,t))},style:function(e,t,n){return arguments.length>1?this.each((null==t?Le:"function"==typeof t?Fe:De)(e,t,n??"")):Be(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?ze:"function"==typeof t?qe:Ue)(e,t)):this.node()[e]},classed:function(e,t){var n=He(e+"");if(arguments.length<2){for(var r=Je(this.node()),i=-1,o=n.length;++i<o;)if(!r.contains(n[i]))return!1;return!0}return this.each(("function"==typeof t?Ye:t?We:Xe)(n,t))},text:function(e){return arguments.length?this.each(null==e?Qe:("function"==typeof e?et:Ze)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?tt:("function"==typeof e?rt:nt)(e)):this.node().innerHTML},raise:function(){return this.each(it)},lower:function(){return this.each(ot)},append:function(e){var t="function"==typeof e?e:fe(e);return this.select((function(){return this.appendChild(t.apply(this,arguments))}))},insert:function(e,t){var n="function"==typeof e?e:fe(e),r=null==t?at:"function"==typeof t?t:ge(t);return this.select((function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)}))},remove:function(){return this.each(st)},clone:function(e){return this.select(e?ut:ct)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,n){var r,i,o=function(e){return e.trim().split(/^|\s+/).map((function(e){var t="",n=e.indexOf(".");return n>=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}}))}(e+""),a=o.length;if(!(arguments.length<2)){for(s=t?ht:lt,r=0;r<a;++r)this.each(s(o[r],t,n));return this}var s=this.node().__on;if(s)for(var c,u=0,l=s.length;u<l;++u)for(r=0,c=s[u];r<a;++r)if((i=o[r]).type===c.type&&i.name===c.name)return c.value},dispatch:function(e,t){return this.each(("function"==typeof t?gt:dt)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r,i=e[t],o=0,a=i.length;o<a;++o)(r=i[o])&&(yield r)}};const yt={passive:!1},St={capture:!0,passive:!1};function kt(e){e.stopImmediatePropagation()}function Et(e){e.preventDefault(),e.stopImmediatePropagation()}function xt(e){var t=e.document.documentElement,n=wt(e).on("dragstart.drag",Et,St);"onselectstart"in t?n.on("selectstart.drag",Et,St):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function Mt(e,t){var n=e.document.documentElement,r=wt(e).on("dragstart.drag",null);t&&(r.on("click.drag",Et,St),setTimeout((function(){r.on("click.drag",null)}),0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const Tt=e=>()=>e;function Ct(e,{sourceEvent:t,subject:n,target:r,identifier:i,active:o,x:a,y:s,dx:c,dy:u,dispatch:l}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:i,enumerable:!0,configurable:!0},active:{value:o,enumerable:!0,configurable:!0},x:{value:a,enumerable:!0,configurable:!0},y:{value:s,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:l}})}function _t(e){return!e.ctrlKey&&!e.button}function Pt(){return this.parentNode}function It(e,t){return t??{x:e.x,y:e.y}}function At(){return navigator.maxTouchPoints||"ontouchstart"in this}function Ot(){var e,t,n,r,i=_t,o=Pt,a=It,s=At,c={},u=re("start","drag","end"),l=0,h=0;function f(e){e.on("mousedown.drag",d).filter(s).on("touchstart.drag",b).on("touchmove.drag",m,yt).on("touchend.drag touchcancel.drag",w).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function d(a,s){if(!r&&i.call(this,a,s)){var c=v(this,o.call(this,a,s),a,s,"mouse");c&&(wt(a.view).on("mousemove.drag",g,St).on("mouseup.drag",p,St),xt(a.view),kt(a),n=!1,e=a.clientX,t=a.clientY,c("start",a))}}function g(r){if(Et(r),!n){var i=r.clientX-e,o=r.clientY-t;n=i*i+o*o>h}c.mouse("drag",r)}function p(e){wt(e.view).on("mousemove.drag mouseup.drag",null),Mt(e.view,n),Et(e),c.mouse("end",e)}function b(e,t){if(i.call(this,e,t)){var n,r,a=e.changedTouches,s=o.call(this,e,t),c=a.length;for(n=0;n<c;++n)(r=v(this,s,e,t,a[n].identifier,a[n]))&&(kt(e),r("start",e,a[n]))}}function m(e){var t,n,r=e.changedTouches,i=r.length;for(t=0;t<i;++t)(n=c[r[t].identifier])&&(Et(e),n("drag",e,r[t]))}function w(e){var t,n,i=e.changedTouches,o=i.length;for(r&&clearTimeout(r),r=setTimeout((function(){r=null}),500),t=0;t<o;++t)(n=c[i[t].identifier])&&(kt(e),n("end",e,i[t]))}function v(e,t,n,r,i,o){var s,h,d,g=u.copy(),p=vt(o||n,t);if(null!=(d=a.call(e,new Ct("beforestart",{sourceEvent:n,target:f,identifier:i,active:l,x:p[0],y:p[1],dx:0,dy:0,dispatch:g}),r)))return s=d.x-p[0]||0,h=d.y-p[1]||0,function n(o,a,u){var b,m=p;switch(o){case"start":c[i]=n,b=l++;break;case"end":delete c[i],--l;case"drag":p=vt(u||a,t),b=l}g.call(o,e,new Ct(o,{sourceEvent:a,subject:d,target:f,identifier:i,active:b,x:p[0]+s,y:p[1]+h,dx:p[0]-m[0],dy:p[1]-m[1],dispatch:g}),r)}}return f.filter=function(e){return arguments.length?(i="function"==typeof e?e:Tt(!!e),f):i},f.container=function(e){return arguments.length?(o="function"==typeof e?e:Tt(e),f):o},f.subject=function(e){return arguments.length?(a="function"==typeof e?e:Tt(e),f):a},f.touchable=function(e){return arguments.length?(s="function"==typeof e?e:Tt(!!e),f):s},f.on=function(){var e=u.on.apply(u,arguments);return e===u?f:e},f.clickDistance=function(e){return arguments.length?(h=(e=+e)*e,f):Math.sqrt(h)},f}function jt(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function $t(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Rt(){}Ct.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};var Nt=.7,Lt=1/Nt,Dt="\\s*([+-]?\\d+)\\s*",Ft="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Bt="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",zt=/^#([0-9a-f]{3,8})$/,Ut=new RegExp(`^rgb\\(${Dt},${Dt},${Dt}\\)$`),qt=new RegExp(`^rgb\\(${Bt},${Bt},${Bt}\\)$`),Ht=new RegExp(`^rgba\\(${Dt},${Dt},${Dt},${Ft}\\)$`),Jt=new RegExp(`^rgba\\(${Bt},${Bt},${Bt},${Ft}\\)$`),Gt=new RegExp(`^hsl\\(${Ft},${Bt},${Bt}\\)$`),Vt=new RegExp(`^hsla\\(${Ft},${Bt},${Bt},${Ft}\\)$`),Kt={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function Wt(){return this.rgb().formatHex()}function Xt(){return this.rgb().formatRgb()}function Yt(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=zt.exec(e))?(n=t[1].length,t=parseInt(t[1],16),6===n?Qt(t):3===n?new tn(t>>8&15|t>>4&240,t>>4&15|240&t,(15&t)<<4|15&t,1):8===n?Zt(t>>24&255,t>>16&255,t>>8&255,(255&t)/255):4===n?Zt(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|240&t,((15&t)<<4|15&t)/255):null):(t=Ut.exec(e))?new tn(t[1],t[2],t[3],1):(t=qt.exec(e))?new tn(255*t[1]/100,255*t[2]/100,255*t[3]/100,1):(t=Ht.exec(e))?Zt(t[1],t[2],t[3],t[4]):(t=Jt.exec(e))?Zt(255*t[1]/100,255*t[2]/100,255*t[3]/100,t[4]):(t=Gt.exec(e))?cn(t[1],t[2]/100,t[3]/100,1):(t=Vt.exec(e))?cn(t[1],t[2]/100,t[3]/100,t[4]):Kt.hasOwnProperty(e)?Qt(Kt[e]):"transparent"===e?new tn(NaN,NaN,NaN,0):null}function Qt(e){return new tn(e>>16&255,e>>8&255,255&e,1)}function Zt(e,t,n,r){return r<=0&&(e=t=n=NaN),new tn(e,t,n,r)}function en(e,t,n,r){return 1===arguments.length?function(e){return e instanceof Rt||(e=Yt(e)),e?new tn((e=e.rgb()).r,e.g,e.b,e.opacity):new tn}(e):new tn(e,t,n,r??1)}function tn(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}function nn(){return`#${sn(this.r)}${sn(this.g)}${sn(this.b)}`}function rn(){const e=on(this.opacity);return`${1===e?"rgb(":"rgba("}${an(this.r)}, ${an(this.g)}, ${an(this.b)}${1===e?")":`, ${e})`}`}function on(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function an(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function sn(e){return((e=an(e))<16?"0":"")+e.toString(16)}function cn(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new ln(e,t,n,r)}function un(e){if(e instanceof ln)return new ln(e.h,e.s,e.l,e.opacity);if(e instanceof Rt||(e=Yt(e)),!e)return new ln;if(e instanceof ln)return e;var t=(e=e.rgb()).r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),o=Math.max(t,n,r),a=NaN,s=o-i,c=(o+i)/2;return s?(a=t===o?(n-r)/s+6*(n<r):n===o?(r-t)/s+2:(t-n)/s+4,s/=c<.5?o+i:2-o-i,a*=60):s=c>0&&c<1?0:a,new ln(a,s,c,e.opacity)}function ln(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}function hn(e){return(e=(e||0)%360)<0?e+360:e}function fn(e){return Math.max(0,Math.min(1,e||0))}function dn(e,t,n){return 255*(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)}jt(Rt,Yt,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Wt,formatHex:Wt,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return un(this).formatHsl()},formatRgb:Xt,toString:Xt}),jt(tn,en,$t(Rt,{brighter(e){return e=null==e?Lt:Math.pow(Lt,e),new tn(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=null==e?Nt:Math.pow(Nt,e),new tn(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new tn(an(this.r),an(this.g),an(this.b),on(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:nn,formatHex:nn,formatHex8:function(){return`#${sn(this.r)}${sn(this.g)}${sn(this.b)}${sn(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:rn,toString:rn})),jt(ln,(function(e,t,n,r){return 1===arguments.length?un(e):new ln(e,t,n,r??1)}),$t(Rt,{brighter(e){return e=null==e?Lt:Math.pow(Lt,e),new ln(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=null==e?Nt:Math.pow(Nt,e),new ln(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+360*(this.h<0),t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,i=2*n-r;return new tn(dn(e>=240?e-240:e+120,i,r),dn(e,i,r),dn(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new ln(hn(this.h),fn(this.s),fn(this.l),on(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=on(this.opacity);return`${1===e?"hsl(":"hsla("}${hn(this.h)}, ${100*fn(this.s)}%, ${100*fn(this.l)}%${1===e?")":`, ${e})`}`}}));const gn=e=>()=>e;function pn(e,t){var n=t-e;return n?function(e,t){return function(n){return e+n*t}}(e,n):gn(isNaN(e)?t:e)}const bn=function e(t){var n=function(e){return 1==(e=+e)?pn:function(t,n){return n-t?function(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}(t,n,e):gn(isNaN(t)?n:t)}}(t);function r(e,t){var r=n((e=en(e)).r,(t=en(t)).r),i=n(e.g,t.g),o=n(e.b,t.b),a=pn(e.opacity,t.opacity);return function(t){return e.r=r(t),e.g=i(t),e.b=o(t),e.opacity=a(t),e+""}}return r.gamma=e,r}(1);function mn(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var wn=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,vn=new RegExp(wn.source,"g");function yn(e,t){var n,r,i,o=wn.lastIndex=vn.lastIndex=0,a=-1,s=[],c=[];for(e+="",t+="";(n=wn.exec(e))&&(r=vn.exec(t));)(i=r.index)>o&&(i=t.slice(o,i),s[a]?s[a]+=i:s[++a]=i),(n=n[0])===(r=r[0])?s[a]?s[a]+=r:s[++a]=r:(s[++a]=null,c.push({i:a,x:mn(n,r)})),o=vn.lastIndex;return o<t.length&&(i=t.slice(o),s[a]?s[a]+=i:s[++a]=i),s.length<2?c[0]?function(e){return function(t){return e(t)+""}}(c[0].x):function(e){return function(){return e}}(t):(t=c.length,function(e){for(var n,r=0;r<t;++r)s[(n=c[r]).i]=n.x(e);return s.join("")})}var Sn,kn=180/Math.PI,En={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function xn(e,t,n,r,i,o){var a,s,c;return(a=Math.sqrt(e*e+t*t))&&(e/=a,t/=a),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(s=Math.sqrt(n*n+r*r))&&(n/=s,r/=s,c/=s),e*r<t*n&&(e=-e,t=-t,c=-c,a=-a),{translateX:i,translateY:o,rotate:Math.atan2(t,e)*kn,skewX:Math.atan(c)*kn,scaleX:a,scaleY:s}}function Mn(e,t,n,r){function i(e){return e.length?e.pop()+" ":""}return function(o,a){var s=[],c=[];return o=e(o),a=e(a),function(e,r,i,o,a,s){if(e!==i||r!==o){var c=a.push("translate(",null,t,null,n);s.push({i:c-4,x:mn(e,i)},{i:c-2,x:mn(r,o)})}else(i||o)&&a.push("translate("+i+t+o+n)}(o.translateX,o.translateY,a.translateX,a.translateY,s,c),function(e,t,n,o){e!==t?(e-t>180?t+=360:t-e>180&&(e+=360),o.push({i:n.push(i(n)+"rotate(",null,r)-2,x:mn(e,t)})):t&&n.push(i(n)+"rotate("+t+r)}(o.rotate,a.rotate,s,c),function(e,t,n,o){e!==t?o.push({i:n.push(i(n)+"skewX(",null,r)-2,x:mn(e,t)}):t&&n.push(i(n)+"skewX("+t+r)}(o.skewX,a.skewX,s,c),function(e,t,n,r,o,a){if(e!==n||t!==r){var s=o.push(i(o)+"scale(",null,",",null,")");a.push({i:s-4,x:mn(e,n)},{i:s-2,x:mn(t,r)})}else(1!==n||1!==r)&&o.push(i(o)+"scale("+n+","+r+")")}(o.scaleX,o.scaleY,a.scaleX,a.scaleY,s,c),o=a=null,function(e){for(var t,n=-1,r=c.length;++n<r;)s[(t=c[n]).i]=t.x(e);return s.join("")}}}var Tn=Mn((function(e){const t=new("function"==typeof DOMMatrix?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?En:xn(t.a,t.b,t.c,t.d,t.e,t.f)}),"px, ","px)","deg)"),Cn=Mn((function(e){return null!=e&&(Sn||(Sn=document.createElementNS("http://www.w3.org/2000/svg","g")),Sn.setAttribute("transform",e),e=Sn.transform.baseVal.consolidate())?xn((e=e.matrix).a,e.b,e.c,e.d,e.e,e.f):En}),", ",")",")");function _n(e){return((e=Math.exp(e))+1/e)/2}const Pn=function e(t,n,r){function i(e,i){var o,a,s=e[0],c=e[1],u=e[2],l=i[0],h=i[1],f=i[2],d=l-s,g=h-c,p=d*d+g*g;if(p<1e-12)a=Math.log(f/u)/t,o=function(e){return[s+e*d,c+e*g,u*Math.exp(t*e*a)]};else{var b=Math.sqrt(p),m=(f*f-u*u+r*p)/(2*u*n*b),w=(f*f-u*u-r*p)/(2*f*n*b),v=Math.log(Math.sqrt(m*m+1)-m),y=Math.log(Math.sqrt(w*w+1)-w);a=(y-v)/t,o=function(e){var r=e*a,i=_n(v),o=u/(n*b)*(i*function(e){return((e=Math.exp(2*e))-1)/(e+1)}(t*r+v)-function(e){return((e=Math.exp(e))-1/e)/2}(v));return[s+o*d,c+o*g,u*i/_n(t*r+v)]}}return o.duration=1e3*a*t/Math.SQRT2,o}return i.rho=function(t){var n=Math.max(.001,+t),r=n*n;return e(n,r,r*r)},i}(Math.SQRT2,2,4);var In,An,On=0,jn=0,$n=0,Rn=1e3,Nn=0,Ln=0,Dn=0,Fn="object"==typeof performance&&performance.now?performance:Date,Bn="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function zn(){return Ln||(Bn(Un),Ln=Fn.now()+Dn)}function Un(){Ln=0}function qn(){this._call=this._time=this._next=null}function Hn(e,t,n){var r=new qn;return r.restart(e,t,n),r}function Jn(){Ln=(Nn=Fn.now())+Dn,On=jn=0;try{!function(){zn(),++On;for(var e,t=In;t;)(e=Ln-t._time)>=0&&t._call.call(void 0,e),t=t._next;--On}()}finally{On=0,function(){for(var e,t,n=In,r=1/0;n;)n._call?(r>n._time&&(r=n._time),e=n,n=n._next):(t=n._next,n._next=null,n=e?e._next=t:In=t);An=e,Vn(r)}(),Ln=0}}function Gn(){var e=Fn.now(),t=e-Nn;t>Rn&&(Dn-=t,Nn=e)}function Vn(e){On||(jn&&(jn=clearTimeout(jn)),e-Ln>24?(e<1/0&&(jn=setTimeout(Jn,e-Fn.now()-Dn)),$n&&($n=clearInterval($n))):($n||(Nn=Fn.now(),$n=setInterval(Gn,Rn)),On=1,Bn(Jn)))}function Kn(e,t,n){var r=new qn;return t=null==t?0:+t,r.restart((n=>{r.stop(),e(n+t)}),t,n),r}qn.prototype=Hn.prototype={constructor:qn,restart:function(e,t,n){if("function"!=typeof e)throw new TypeError("callback is not a function");n=(null==n?zn():+n)+(null==t?0:+t),!this._next&&An!==this&&(An?An._next=this:In=this,An=this),this._call=e,this._time=n,Vn()},stop:function(){this._call&&(this._call=null,this._time=1/0,Vn())}};var Wn=re("start","end","cancel","interrupt"),Xn=[],Yn=0,Qn=2,Zn=3,er=5,tr=6;function nr(e,t,n,r,i,o){var a=e.__transition;if(a){if(n in a)return}else e.__transition={};!function(e,t,n){var r,i=e.__transition;function o(c){var u,l,h,f;if(1!==n.state)return s();for(u in i)if((f=i[u]).name===n.name){if(f.state===Zn)return Kn(o);4===f.state?(f.state=tr,f.timer.stop(),f.on.call("interrupt",e,e.__data__,f.index,f.group),delete i[u]):+u<t&&(f.state=tr,f.timer.stop(),f.on.call("cancel",e,e.__data__,f.index,f.group),delete i[u])}if(Kn((function(){n.state===Zn&&(n.state=4,n.timer.restart(a,n.delay,n.time),a(c))})),n.state=Qn,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Qn){for(n.state=Zn,r=new Array(h=n.tween.length),u=0,l=-1;u<h;++u)(f=n.tween[u].value.call(e,e.__data__,n.index,n.group))&&(r[++l]=f);r.length=l+1}}function a(t){for(var i=t<n.duration?n.ease.call(null,t/n.duration):(n.timer.restart(s),n.state=er,1),o=-1,a=r.length;++o<a;)r[o].call(e,i);n.state===er&&(n.on.call("end",e,e.__data__,n.index,n.group),s())}function s(){for(var r in n.state=tr,n.timer.stop(),delete i[t],i)return;delete e.__transition}i[t]=n,n.timer=Hn((function(e){n.state=1,n.timer.restart(o,n.delay,n.time),n.delay<=e&&o(e-n.delay)}),0,n.time)}(e,n,{name:t,index:r,group:i,on:Wn,tween:Xn,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:Yn})}function rr(e,t){var n=or(e,t);if(n.state>Yn)throw new Error("too late; already scheduled");return n}function ir(e,t){var n=or(e,t);if(n.state>Zn)throw new Error("too late; already running");return n}function or(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function ar(e,t){var n,r,i,o=e.__transition,a=!0;if(o){for(i in t=null==t?null:t+"",o)(n=o[i]).name===t?(r=n.state>Qn&&n.state<er,n.state=tr,n.timer.stop(),n.on.call(r?"interrupt":"cancel",e,e.__data__,n.index,n.group),delete o[i]):a=!1;a&&delete e.__transition}}function sr(e,t){var n,r;return function(){var i=ir(this,e),o=i.tween;if(o!==n)for(var a=0,s=(r=n=o).length;a<s;++a)if(r[a].name===t){(r=r.slice()).splice(a,1);break}i.tween=r}}function cr(e,t,n){var r,i;if("function"!=typeof n)throw new Error;return function(){var o=ir(this,e),a=o.tween;if(a!==r){i=(r=a).slice();for(var s={name:t,value:n},c=0,u=i.length;c<u;++c)if(i[c].name===t){i[c]=s;break}c===u&&i.push(s)}o.tween=i}}function ur(e,t,n){var r=e._id;return e.each((function(){var e=ir(this,r);(e.value||(e.value={}))[t]=n.apply(this,arguments)})),function(e){return or(e,r).value[t]}}function lr(e,t){var n;return("number"==typeof t?mn:t instanceof Yt?bn:(n=Yt(t))?(t=n,bn):yn)(e,t)}function hr(e){return function(){this.removeAttribute(e)}}function fr(e){return function(){this.removeAttributeNS(e.space,e.local)}}function dr(e,t,n){var r,i,o=n+"";return function(){var a=this.getAttribute(e);return a===o?null:a===r?i:i=t(r=a,n)}}function gr(e,t,n){var r,i,o=n+"";return function(){var a=this.getAttributeNS(e.space,e.local);return a===o?null:a===r?i:i=t(r=a,n)}}function pr(e,t,n){var r,i,o;return function(){var a,s,c=n(this);return null==c?void this.removeAttribute(e):(a=this.getAttribute(e))===(s=c+"")?null:a===r&&s===i?o:(i=s,o=t(r=a,c))}}function br(e,t,n){var r,i,o;return function(){var a,s,c=n(this);return null==c?void this.removeAttributeNS(e.space,e.local):(a=this.getAttributeNS(e.space,e.local))===(s=c+"")?null:a===r&&s===i?o:(i=s,o=t(r=a,c))}}function mr(e,t){var n,r;function i(){var i=t.apply(this,arguments);return i!==r&&(n=(r=i)&&function(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}(e,i)),n}return i._value=t,i}function wr(e,t){var n,r;function i(){var i=t.apply(this,arguments);return i!==r&&(n=(r=i)&&function(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}(e,i)),n}return i._value=t,i}function vr(e,t){return function(){rr(this,e).delay=+t.apply(this,arguments)}}function yr(e,t){return t=+t,function(){rr(this,e).delay=t}}function Sr(e,t){return function(){ir(this,e).duration=+t.apply(this,arguments)}}function kr(e,t){return t=+t,function(){ir(this,e).duration=t}}var Er=mt.prototype.constructor;function xr(e){return function(){this.style.removeProperty(e)}}var Mr=0;function Tr(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Cr(){return++Mr}var _r=mt.prototype;Tr.prototype={constructor:Tr,select:function(e){var t=this._name,n=this._id;"function"!=typeof e&&(e=ge(e));for(var r=this._groups,i=r.length,o=new Array(i),a=0;a<i;++a)for(var s,c,u=r[a],l=u.length,h=o[a]=new Array(l),f=0;f<l;++f)(s=u[f])&&(c=e.call(s,s.__data__,f,u))&&("__data__"in s&&(c.__data__=s.__data__),h[f]=c,nr(h[f],t,n,f,h,or(s,n)));return new Tr(o,this._parents,t,n)},selectAll:function(e){var t=this._name,n=this._id;"function"!=typeof e&&(e=be(e));for(var r=this._groups,i=r.length,o=[],a=[],s=0;s<i;++s)for(var c,u=r[s],l=u.length,h=0;h<l;++h)if(c=u[h]){for(var f,d=e.call(c,c.__data__,h,u),g=or(c,n),p=0,b=d.length;p<b;++p)(f=d[p])&&nr(f,t,n,p,d,g);o.push(d),a.push(c)}return new Tr(o,a,t,n)},selectChild:_r.selectChild,selectChildren:_r.selectChildren,filter:function(e){"function"!=typeof e&&(e=me(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o,a=t[i],s=a.length,c=r[i]=[],u=0;u<s;++u)(o=a[u])&&e.call(o,o.__data__,u,a)&&c.push(o);return new Tr(r,this._parents,this._name,this._id)},merge:function(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,i=n.length,o=Math.min(r,i),a=new Array(r),s=0;s<o;++s)for(var c,u=t[s],l=n[s],h=u.length,f=a[s]=new Array(h),d=0;d<h;++d)(c=u[d]||l[d])&&(f[d]=c);for(;s<r;++s)a[s]=t[s];return new Tr(a,this._parents,this._name,this._id)},selection:function(){return new Er(this._groups,this._parents)},transition:function(){for(var e=this._name,t=this._id,n=Cr(),r=this._groups,i=r.length,o=0;o<i;++o)for(var a,s=r[o],c=s.length,u=0;u<c;++u)if(a=s[u]){var l=or(a,t);nr(a,e,n,u,s,{time:l.time+l.delay+l.duration,delay:0,duration:l.duration,ease:l.ease})}return new Tr(r,this._parents,e,n)},call:_r.call,nodes:_r.nodes,node:_r.node,size:_r.size,empty:_r.empty,each:_r.each,on:function(e,t){var n=this._id;return arguments.length<2?or(this.node(),n).on.on(e):this.each(function(e,t,n){var r,i,o=function(e){return(e+"").trim().split(/^|\s+/).every((function(e){var t=e.indexOf(".");return t>=0&&(e=e.slice(0,t)),!e||"start"===e}))}(t)?rr:ir;return function(){var a=o(this,e),s=a.on;s!==r&&(i=(r=s).copy()).on(t,n),a.on=i}}(n,e,t))},attr:function(e,t){var n=ue(e),r="transform"===n?Cn:lr;return this.attrTween(e,"function"==typeof t?(n.local?br:pr)(n,r,ur(this,"attr."+e,t)):null==t?(n.local?fr:hr)(n):(n.local?gr:dr)(n,r,t))},attrTween:function(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(null==t)return this.tween(n,null);if("function"!=typeof t)throw new Error;var r=ue(e);return this.tween(n,(r.local?mr:wr)(r,t))},style:function(e,t,n){var r="transform"==(e+="")?Tn:lr;return null==t?this.styleTween(e,function(e,t){var n,r,i;return function(){var o=Be(this,e),a=(this.style.removeProperty(e),Be(this,e));return o===a?null:o===n&&a===r?i:i=t(n=o,r=a)}}(e,r)).on("end.style."+e,xr(e)):"function"==typeof t?this.styleTween(e,function(e,t,n){var r,i,o;return function(){var a=Be(this,e),s=n(this),c=s+"";return null==s&&(this.style.removeProperty(e),c=s=Be(this,e)),a===c?null:a===r&&c===i?o:(i=c,o=t(r=a,s))}}(e,r,ur(this,"style."+e,t))).each(function(e,t){var n,r,i,o,a="style."+t,s="end."+a;return function(){var c=ir(this,e),u=c.on,l=null==c.value[a]?o||(o=xr(t)):void 0;(u!==n||i!==l)&&(r=(n=u).copy()).on(s,i=l),c.on=r}}(this._id,e)):this.styleTween(e,function(e,t,n){var r,i,o=n+"";return function(){var a=Be(this,e);return a===o?null:a===r?i:i=t(r=a,n)}}(e,r,t),n).on("end.style."+e,null)},styleTween:function(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==t)return this.tween(r,null);if("function"!=typeof t)throw new Error;return this.tween(r,function(e,t,n){var r,i;function o(){var o=t.apply(this,arguments);return o!==i&&(r=(i=o)&&function(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}(e,o,n)),r}return o._value=t,o}(e,t,n??""))},text:function(e){return this.tween("text","function"==typeof e?function(e){return function(){var t=e(this);this.textContent=t??""}}(ur(this,"text",e)):function(e){return function(){this.textContent=e}}(null==e?"":e+""))},textTween:function(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(null==e)return this.tween(t,null);if("function"!=typeof e)throw new Error;return this.tween(t,function(e){var t,n;function r(){var r=e.apply(this,arguments);return r!==n&&(t=(n=r)&&function(e){return function(t){this.textContent=e.call(this,t)}}(r)),t}return r._value=e,r}(e))},remove:function(){return this.on("end.remove",(e=this._id,function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}));var e},tween:function(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r,i=or(this.node(),n).tween,o=0,a=i.length;o<a;++o)if((r=i[o]).name===e)return r.value;return null}return this.each((null==t?sr:cr)(n,e,t))},delay:function(e){var t=this._id;return arguments.length?this.each(("function"==typeof e?vr:yr)(t,e)):or(this.node(),t).delay},duration:function(e){var t=this._id;return arguments.length?this.each(("function"==typeof e?Sr:kr)(t,e)):or(this.node(),t).duration},ease:function(e){var t=this._id;return arguments.length?this.each(function(e,t){if("function"!=typeof t)throw new Error;return function(){ir(this,e).ease=t}}(t,e)):or(this.node(),t).ease},easeVarying:function(e){if("function"!=typeof e)throw new Error;return this.each(function(e,t){return function(){var n=t.apply(this,arguments);if("function"!=typeof n)throw new Error;ir(this,e).ease=n}}(this._id,e))},end:function(){var e,t,n=this,r=n._id,i=n.size();return new Promise((function(o,a){var s={value:a},c={value:function(){0==--i&&o()}};n.each((function(){var n=ir(this,r),i=n.on;i!==e&&((t=(e=i).copy())._.cancel.push(s),t._.interrupt.push(s),t._.end.push(c)),n.on=t})),0===i&&o()}))},[Symbol.iterator]:_r[Symbol.iterator]};var Pr={time:null,delay:0,duration:250,ease:function(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}};function Ir(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}mt.prototype.interrupt=function(e){return this.each((function(){ar(this,e)}))},mt.prototype.transition=function(e){var t,n;e instanceof Tr?(t=e._id,e=e._name):(t=Cr(),(n=Pr).time=zn(),e=null==e?null:e+"");for(var r=this._groups,i=r.length,o=0;o<i;++o)for(var a,s=r[o],c=s.length,u=0;u<c;++u)(a=s[u])&&nr(a,e,t,u,s,n||Ir(a,t));return new Tr(r,this._parents,e,t)};const Ar=e=>()=>e;function Or(e,{sourceEvent:t,target:n,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}})}function jr(e,t,n){this.k=e,this.x=t,this.y=n}jr.prototype={constructor:jr,scale:function(e){return 1===e?this:new jr(this.k*e,this.x,this.y)},translate:function(e,t){return 0===e&0===t?this:new jr(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var $r=new jr(1,0,0);function Rr(e){for(;!e.__zoom;)if(!(e=e.parentNode))return $r;return e.__zoom}function Nr(e){e.stopImmediatePropagation()}function Lr(e){e.preventDefault(),e.stopImmediatePropagation()}function Dr(e){return!(e.ctrlKey&&"wheel"!==e.type||e.button)}function Fr(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e).hasAttribute("viewBox")?[[(e=e.viewBox.baseVal).x,e.y],[e.x+e.width,e.y+e.height]]:[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]:[[0,0],[e.clientWidth,e.clientHeight]]}function Br(){return this.__zoom||$r}function zr(e){return-e.deltaY*(1===e.deltaMode?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function Ur(){return navigator.maxTouchPoints||"ontouchstart"in this}function qr(e,t,n){var r=e.invertX(t[0][0])-n[0][0],i=e.invertX(t[1][0])-n[1][0],o=e.invertY(t[0][1])-n[0][1],a=e.invertY(t[1][1])-n[1][1];return e.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),a>o?(o+a)/2:Math.min(0,o)||Math.max(0,a))}function Hr(){var e,t,n,r=Dr,i=Fr,o=qr,a=zr,s=Ur,c=[0,1/0],u=[[-1/0,-1/0],[1/0,1/0]],l=250,h=Pn,f=re("start","zoom","end"),d=500,g=150,p=0,b=10;function m(e){e.property("__zoom",Br).on("wheel.zoom",x,{passive:!1}).on("mousedown.zoom",M).on("dblclick.zoom",T).filter(s).on("touchstart.zoom",C).on("touchmove.zoom",_).on("touchend.zoom touchcancel.zoom",P).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function w(e,t){return(t=Math.max(c[0],Math.min(c[1],t)))===e.k?e:new jr(t,e.x,e.y)}function v(e,t,n){var r=t[0]-n[0]*e.k,i=t[1]-n[1]*e.k;return r===e.x&&i===e.y?e:new jr(e.k,r,i)}function y(e){return[(+e[0][0]+ +e[1][0])/2,(+e[0][1]+ +e[1][1])/2]}function S(e,t,n,r){e.on("start.zoom",(function(){k(this,arguments).event(r).start()})).on("interrupt.zoom end.zoom",(function(){k(this,arguments).event(r).end()})).tween("zoom",(function(){var e=this,o=arguments,a=k(e,o).event(r),s=i.apply(e,o),c=null==n?y(s):"function"==typeof n?n.apply(e,o):n,u=Math.max(s[1][0]-s[0][0],s[1][1]-s[0][1]),l=e.__zoom,f="function"==typeof t?t.apply(e,o):t,d=h(l.invert(c).concat(u/l.k),f.invert(c).concat(u/f.k));return function(e){if(1===e)e=f;else{var t=d(e),n=u/t[2];e=new jr(n,c[0]-t[0]*n,c[1]-t[1]*n)}a.zoom(null,e)}}))}function k(e,t,n){return!n&&e.__zooming||new E(e,t)}function E(e,t){this.that=e,this.args=t,this.active=0,this.sourceEvent=null,this.extent=i.apply(e,t),this.taps=0}function x(e,...t){if(r.apply(this,arguments)){var n=k(this,t).event(e),i=this.__zoom,s=Math.max(c[0],Math.min(c[1],i.k*Math.pow(2,a.apply(this,arguments)))),l=vt(e);if(n.wheel)(n.mouse[0][0]!==l[0]||n.mouse[0][1]!==l[1])&&(n.mouse[1]=i.invert(n.mouse[0]=l)),clearTimeout(n.wheel);else{if(i.k===s)return;n.mouse=[l,i.invert(l)],ar(this),n.start()}Lr(e),n.wheel=setTimeout((function(){n.wheel=null,n.end()}),g),n.zoom("mouse",o(v(w(i,s),n.mouse[0],n.mouse[1]),n.extent,u))}}function M(e,...t){if(!n&&r.apply(this,arguments)){var i=e.currentTarget,a=k(this,t,!0).event(e),s=wt(e.view).on("mousemove.zoom",(function(e){if(Lr(e),!a.moved){var t=e.clientX-l,n=e.clientY-h;a.moved=t*t+n*n>p}a.event(e).zoom("mouse",o(v(a.that.__zoom,a.mouse[0]=vt(e,i),a.mouse[1]),a.extent,u))}),!0).on("mouseup.zoom",(function(e){s.on("mousemove.zoom mouseup.zoom",null),Mt(e.view,a.moved),Lr(e),a.event(e).end()}),!0),c=vt(e,i),l=e.clientX,h=e.clientY;xt(e.view),Nr(e),a.mouse=[c,this.__zoom.invert(c)],ar(this),a.start()}}function T(e,...t){if(r.apply(this,arguments)){var n=this.__zoom,a=vt(e.changedTouches?e.changedTouches[0]:e,this),s=n.invert(a),c=n.k*(e.shiftKey?.5:2),h=o(v(w(n,c),a,s),i.apply(this,t),u);Lr(e),l>0?wt(this).transition().duration(l).call(S,h,a,e):wt(this).call(m.transform,h,a,e)}}function C(n,...i){if(r.apply(this,arguments)){var o,a,s,c,u=n.touches,l=u.length,h=k(this,i,n.changedTouches.length===l).event(n);for(Nr(n),a=0;a<l;++a)c=[c=vt(s=u[a],this),this.__zoom.invert(c),s.identifier],h.touch0?!h.touch1&&h.touch0[2]!==c[2]&&(h.touch1=c,h.taps=0):(h.touch0=c,o=!0,h.taps=1+!!e);e&&(e=clearTimeout(e)),o&&(h.taps<2&&(t=c[0],e=setTimeout((function(){e=null}),d)),ar(this),h.start())}}function _(e,...t){if(this.__zooming){var n,r,i,a,s=k(this,t).event(e),c=e.changedTouches,l=c.length;for(Lr(e),n=0;n<l;++n)i=vt(r=c[n],this),s.touch0&&s.touch0[2]===r.identifier?s.touch0[0]=i:s.touch1&&s.touch1[2]===r.identifier&&(s.touch1[0]=i);if(r=s.that.__zoom,s.touch1){var h=s.touch0[0],f=s.touch0[1],d=s.touch1[0],g=s.touch1[1],p=(p=d[0]-h[0])*p+(p=d[1]-h[1])*p,b=(b=g[0]-f[0])*b+(b=g[1]-f[1])*b;r=w(r,Math.sqrt(p/b)),i=[(h[0]+d[0])/2,(h[1]+d[1])/2],a=[(f[0]+g[0])/2,(f[1]+g[1])/2]}else{if(!s.touch0)return;i=s.touch0[0],a=s.touch0[1]}s.zoom("touch",o(v(r,i,a),s.extent,u))}}function P(e,...r){if(this.__zooming){var i,o,a=k(this,r).event(e),s=e.changedTouches,c=s.length;for(Nr(e),n&&clearTimeout(n),n=setTimeout((function(){n=null}),d),i=0;i<c;++i)o=s[i],a.touch0&&a.touch0[2]===o.identifier?delete a.touch0:a.touch1&&a.touch1[2]===o.identifier&&delete a.touch1;if(a.touch1&&!a.touch0&&(a.touch0=a.touch1,delete a.touch1),a.touch0)a.touch0[1]=this.__zoom.invert(a.touch0[0]);else if(a.end(),2===a.taps&&(o=vt(o,this),Math.hypot(t[0]-o[0],t[1]-o[1])<b)){var u=wt(this).on("dblclick.zoom");u&&u.apply(this,arguments)}}}return m.transform=function(e,t,n,r){var i=e.selection?e.selection():e;i.property("__zoom",Br),e!==i?S(e,t,n,r):i.interrupt().each((function(){k(this,arguments).event(r).start().zoom(null,"function"==typeof t?t.apply(this,arguments):t).end()}))},m.scaleBy=function(e,t,n,r){m.scaleTo(e,(function(){return this.__zoom.k*("function"==typeof t?t.apply(this,arguments):t)}),n,r)},m.scaleTo=function(e,t,n,r){m.transform(e,(function(){var e=i.apply(this,arguments),r=this.__zoom,a=null==n?y(e):"function"==typeof n?n.apply(this,arguments):n,s=r.invert(a),c="function"==typeof t?t.apply(this,arguments):t;return o(v(w(r,c),a,s),e,u)}),n,r)},m.translateBy=function(e,t,n,r){m.transform(e,(function(){return o(this.__zoom.translate("function"==typeof t?t.apply(this,arguments):t,"function"==typeof n?n.apply(this,arguments):n),i.apply(this,arguments),u)}),null,r)},m.translateTo=function(e,t,n,r,a){m.transform(e,(function(){var e=i.apply(this,arguments),a=this.__zoom,s=null==r?y(e):"function"==typeof r?r.apply(this,arguments):r;return o($r.translate(s[0],s[1]).scale(a.k).translate("function"==typeof t?-t.apply(this,arguments):-t,"function"==typeof n?-n.apply(this,arguments):-n),e,u)}),r,a)},E.prototype={event:function(e){return e&&(this.sourceEvent=e),this},start:function(){return 1==++this.active&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(e,t){return this.mouse&&"mouse"!==e&&(this.mouse[1]=t.invert(this.mouse[0])),this.touch0&&"touch"!==e&&(this.touch0[1]=t.invert(this.touch0[0])),this.touch1&&"touch"!==e&&(this.touch1[1]=t.invert(this.touch1[0])),this.that.__zoom=t,this.emit("zoom"),this},end:function(){return 0==--this.active&&(delete this.that.__zooming,this.emit("end")),this},emit:function(e){var t=wt(this.that).datum();f.call(e,this.that,new Or(e,{sourceEvent:this.sourceEvent,target:m,transform:this.that.__zoom,dispatch:f}),t)}},m.wheelDelta=function(e){return arguments.length?(a="function"==typeof e?e:Ar(+e),m):a},m.filter=function(e){return arguments.length?(r="function"==typeof e?e:Ar(!!e),m):r},m.touchable=function(e){return arguments.length?(s="function"==typeof e?e:Ar(!!e),m):s},m.extent=function(e){return arguments.length?(i="function"==typeof e?e:Ar([[+e[0][0],+e[0][1]],[+e[1][0],+e[1][1]]]),m):i},m.scaleExtent=function(e){return arguments.length?(c[0]=+e[0],c[1]=+e[1],m):[c[0],c[1]]},m.translateExtent=function(e){return arguments.length?(u[0][0]=+e[0][0],u[1][0]=+e[1][0],u[0][1]=+e[0][1],u[1][1]=+e[1][1],m):[[u[0][0],u[0][1]],[u[1][0],u[1][1]]]},m.constrain=function(e){return arguments.length?(o=e,m):o},m.duration=function(e){return arguments.length?(l=+e,m):l},m.interpolate=function(e){return arguments.length?(h=e,m):h},m.on=function(){var e=f.on.apply(f,arguments);return e===f?m:e},m.clickDistance=function(e){return arguments.length?(p=(e=+e)*e,m):Math.sqrt(p)},m.tapDistance=function(e){return arguments.length?(b=+e,m):b},m}Rr.prototype=jr.prototype;const Jr={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${"source"===e?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},Gr=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Vr=["Enter"," ","Escape"];var Kr,Wr,Xr,Yr;(Wr=Kr||(Kr={})).Strict="strict",Wr.Loose="loose",function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"}(Xr||(Xr={})),function(e){e.Partial="partial",e.Full="full"}(Yr||(Yr={}));const Qr={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null};var Zr,ei,ti;!function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"}(Zr||(Zr={})),function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"}(ei||(ei={})),function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"}(ti||(ti={}));const ni={[ti.Left]:ti.Right,[ti.Right]:ti.Left,[ti.Top]:ti.Bottom,[ti.Bottom]:ti.Top};function ri(e){return null===e?null:e?"valid":"invalid"}const ii=e=>"id"in e&&"source"in e&&"target"in e,oi=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),ai=(e,t=[0,0])=>{const{width:n,height:r}=$i(e),i=e.origin??t,o=n*i[0],a=r*i[1];return{x:e.position.x-o,y:e.position.y-a}},si=(e,t={nodeOrigin:[0,0],nodeLookup:void 0})=>{if("development"===ee.env.NODE_ENV&&!t.nodeLookup&&console.warn("Please use `getNodesBounds` from `useReactFlow`/`useSvelteFlow` hook to ensure correct values for sub flows. If not possible, you have to provide a nodeLookup to support sub flows."),0===e.length)return{x:0,y:0,width:0,height:0};const n=e.reduce(((e,n)=>{const r="string"==typeof n;let i=t.nodeLookup||r?void 0:n;t.nodeLookup&&(i=r?t.nodeLookup.get(n):oi(n)?n:t.nodeLookup.get(n.id));const o=i?Si(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return mi(e,o)}),{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return vi(n)},ci=(e,t={})=>{if(0===e.size)return{x:0,y:0,width:0,height:0};let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0};return e.forEach((e=>{if(void 0===t.filter||t.filter(e)){const t=Si(e);n=mi(n,t)}})),vi(n)},ui=(e,t,[n,r,i]=[0,0,1],o=!1,a=!1)=>{const s={..._i(t,[n,r,i]),width:t.width/i,height:t.height/i},c=[];for(const t of e.values()){const{measured:e,selectable:n=!0,hidden:r=!1}=t;if(a&&!n||r)continue;const i=e.width??t.width??t.initialWidth??null,u=e.height??t.height??t.initialHeight??null,l=Ei(s,yi(t)),h=(i??0)*(u??0),f=o&&l>0;(!t.internals.handleBounds||f||l>=h||t.dragging)&&c.push(t)}return c},li=(e,t)=>{const n=new Set;return e.forEach((e=>{n.add(e.id)})),t.filter((e=>n.has(e.source)||n.has(e.target)))};function hi({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:i,onError:o}){const a=n.get(e),s=a.parentId?n.get(a.parentId):void 0,{x:c,y:u}=s?s.internals.positionAbsolute:{x:0,y:0},l=a.origin??r;let h=i;if("parent"!==a.extent||a.expandParent)s&&ji(a.extent)&&(h=[[a.extent[0][0]+c,a.extent[0][1]+u],[a.extent[1][0]+c,a.extent[1][1]+u]]);else if(s){const e=s.measured.width,t=s.measured.height;e&&t&&(h=[[c,u],[c+e,u+t]])}else o?.("005",Jr.error005());const f=ji(h)?di(t,h,a.measured):t;return(void 0===a.measured.width||void 0===a.measured.height)&&o?.("015",Jr.error015()),{position:{x:f.x-c+(a.measured.width??0)*l[0],y:f.y-u+(a.measured.height??0)*l[1]},positionAbsolute:f}}const fi=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),di=(e={x:0,y:0},t,n)=>({x:fi(e.x,t[0][0],t[1][0]-(n?.width??0)),y:fi(e.y,t[0][1],t[1][1]-(n?.height??0))});function gi(e,t,n){const{width:r,height:i}=$i(n),{x:o,y:a}=n.internals.positionAbsolute;return di(e,[[o,a],[o+r,a+i]],t)}const pi=(e,t,n)=>e<t?fi(Math.abs(e-t),1,t)/t:e>n?-fi(Math.abs(e-n),1,t)/t:0,bi=(e,t,n=15,r=40)=>[pi(e.x,r,t.width-r)*n,pi(e.y,r,t.height-r)*n],mi=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),wi=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),vi=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),yi=(e,t=[0,0])=>{const{x:n,y:r}=oi(e)?e.internals.positionAbsolute:ai(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},Si=(e,t=[0,0])=>{const{x:n,y:r}=oi(e)?e.internals.positionAbsolute:ai(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},ki=(e,t)=>vi(mi(wi(e),wi(t))),Ei=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},xi=e=>Mi(e.width)&&Mi(e.height)&&Mi(e.x)&&Mi(e.y),Mi=e=>!isNaN(e)&&isFinite(e),Ti=(e,t)=>{"development"===ee.env.NODE_ENV&&console.warn(`[React Flow]: ${t} Help: https://reactflow.dev/error#${e}`)},Ci=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),_i=({x:e,y:t},[n,r,i],o=!1,a=[1,1])=>{const s={x:(e-n)/i,y:(t-r)/i};return o?Ci(s,a):s},Pi=({x:e,y:t},[n,r,i])=>({x:e*i+n,y:t*i+r});function Ii(e,t){if("number"==typeof e)return Math.floor(t-t/(1+e));if("string"==typeof e&&e.endsWith("px")){const t=parseFloat(e);if(!Number.isNaN(t))return Math.floor(t)}if("string"==typeof e&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}const Ai=(e,t,n,r,i,o)=>{const a=function(e,t,n){if("string"==typeof e||"number"==typeof e){const r=Ii(e,n),i=Ii(e,t);return{top:r,right:i,bottom:r,left:i,x:2*i,y:2*r}}if("object"==typeof e){const r=Ii(e.top??e.y??0,n),i=Ii(e.bottom??e.y??0,n),o=Ii(e.left??e.x??0,t),a=Ii(e.right??e.x??0,t);return{top:r,right:a,bottom:i,left:o,x:o+a,y:r+i}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}(o,t,n),s=(t-a.x)/e.width,c=(n-a.y)/e.height,u=Math.min(s,c),l=fi(u,r,i),h=t/2-(e.x+e.width/2)*l,f=n/2-(e.y+e.height/2)*l,d=function(e,t,n,r,i,o){const{x:a,y:s}=Pi(e,[t,n,r]),{x:c,y:u}=Pi({x:e.x+e.width,y:e.y+e.height},[t,n,r]),l=i-c,h=o-u;return{left:Math.floor(a),top:Math.floor(s),right:Math.floor(l),bottom:Math.floor(h)}}(e,h,f,l,t,n),g=Math.min(d.left-a.left,0),p=Math.min(d.top-a.top,0);return{x:h-g+Math.min(d.right-a.right,0),y:f-p+Math.min(d.bottom-a.bottom,0),zoom:l}},Oi=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function ji(e){return void 0!==e&&"parent"!==e}function $i(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function Ri(e){return void 0!==(e.measured?.width??e.width??e.initialWidth)&&void 0!==(e.measured?.height??e.height??e.initialHeight)}function Ni(e,t={width:0,height:0},n,r,i){const o={...e},a=r.get(n);if(a){const e=a.origin||i;o.x+=a.internals.positionAbsolute.x-(t.width??0)*e[0],o.y+=a.internals.positionAbsolute.y-(t.height??0)*e[1]}return o}function Li(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function Di(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:i}){const{x:o,y:a}=Hi(e),s=_i({x:o-(i?.left??0),y:a-(i?.top??0)},r),{x:c,y:u}=n?Ci(s,t):s;return{xSnapped:c,ySnapped:u,...s}}const Fi=e=>({width:e.offsetWidth,height:e.offsetHeight}),Bi=e=>e?.getRootNode?.()||window?.document,zi=["INPUT","SELECT","TEXTAREA"];function Ui(e){const t=e.composedPath?.()?.[0]||e.target;return 1===t?.nodeType&&(zi.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey"))}const qi=e=>"clientX"in e,Hi=(e,t)=>{const n=qi(e),r=n?e.clientX:e.touches?.[0].clientX,i=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:i-(t?.top??0)}},Ji=(e,t,n,r,i)=>{const o=t.querySelectorAll(`.${e}`);return o&&o.length?Array.from(o).map((t=>{const o=t.getBoundingClientRect();return{id:t.getAttribute("data-handleid"),type:e,nodeId:i,position:t.getAttribute("data-handlepos"),x:(o.left-n.left)/r,y:(o.top-n.top)/r,...Fi(t)}})):null};function Gi({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:i,sourceControlY:o,targetControlX:a,targetControlY:s}){const c=.125*e+.375*i+.375*a+.125*n,u=.125*t+.375*o+.375*s+.125*r;return[c,u,Math.abs(c-e),Math.abs(u-t)]}function Vi(e,t){return e>=0?.5*e:25*t*Math.sqrt(-e)}function Ki({pos:e,x1:t,y1:n,x2:r,y2:i,c:o}){switch(e){case ti.Left:return[t-Vi(t-r,o),n];case ti.Right:return[t+Vi(r-t,o),n];case ti.Top:return[t,n-Vi(n-i,o)];case ti.Bottom:return[t,n+Vi(i-n,o)]}}function Wi({sourceX:e,sourceY:t,sourcePosition:n=ti.Bottom,targetX:r,targetY:i,targetPosition:o=ti.Top,curvature:a=.25}){const[s,c]=Ki({pos:n,x1:e,y1:t,x2:r,y2:i,c:a}),[u,l]=Ki({pos:o,x1:r,y1:i,x2:e,y2:t,c:a}),[h,f,d,g]=Gi({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:s,sourceControlY:c,targetControlX:u,targetControlY:l});return[`M${e},${t} C${s},${c} ${u},${l} ${r},${i}`,h,f,d,g]}function Xi({sourceX:e,sourceY:t,targetX:n,targetY:r}){const i=Math.abs(n-e)/2,o=n<e?n+i:n-i,a=Math.abs(r-t)/2;return[o,r<t?r+a:r-a,i,a]}function Yi({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:i=!1}){if(!i)return r;const o=n||t.selected||e.selected,a=Math.max(e.internals.z||0,t.internals.z||0,1e3);return r+(o?a:0)}function Qi({sourceNode:e,targetNode:t,width:n,height:r,transform:i}){const o=mi(Si(e),Si(t));o.x===o.x2&&(o.x2+=1),o.y===o.y2&&(o.y2+=1);const a={x:-i[0]/i[2],y:-i[1]/i[2],width:n/i[2],height:r/i[2]};return Ei(a,vi(o))>0}const Zi=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`;function eo({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[i,o,a,s]=Xi({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,i,o,a,s]}const to={[ti.Left]:{x:-1,y:0},[ti.Right]:{x:1,y:0},[ti.Top]:{x:0,y:-1},[ti.Bottom]:{x:0,y:1}},no=({source:e,sourcePosition:t=ti.Bottom,target:n})=>t===ti.Left||t===ti.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},ro=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function io({sourceX:e,sourceY:t,sourcePosition:n=ti.Bottom,targetX:r,targetY:i,targetPosition:o=ti.Top,borderRadius:a=5,centerX:s,centerY:c,offset:u=20}){const[l,h,f,d,g]=function({source:e,sourcePosition:t=ti.Bottom,target:n,targetPosition:r=ti.Top,center:i,offset:o}){const a=to[t],s=to[r],c={x:e.x+a.x*o,y:e.y+a.y*o},u={x:n.x+s.x*o,y:n.y+s.y*o},l=no({source:c,sourcePosition:t,target:u}),h=0!==l.x?"x":"y",f=l[h];let d,g,p=[];const b={x:0,y:0},m={x:0,y:0},[w,v,y,S]=Xi({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(a[h]*s[h]==-1){d=i.x??w,g=i.y??v;const e=[{x:d,y:c.y},{x:d,y:u.y}],t=[{x:c.x,y:g},{x:u.x,y:g}];p=a[h]===f?"x"===h?e:t:"x"===h?t:e}else{const i=[{x:c.x,y:u.y}],l=[{x:u.x,y:c.y}];if(p="x"===h?a.x===f?l:i:a.y===f?i:l,t===r){const t=Math.abs(e[h]-n[h]);if(t<=o){const r=Math.min(o-1,o-t);a[h]===f?b[h]=(c[h]>e[h]?-1:1)*r:m[h]=(u[h]>n[h]?-1:1)*r}}if(t!==r){const e="x"===h?"y":"x",t=a[h]===s[e],n=c[e]>u[e],r=c[e]<u[e];(1===a[h]&&(!t&&n||t&&r)||1!==a[h]&&(!t&&r||t&&n))&&(p="x"===h?i:l)}const w={x:c.x+b.x,y:c.y+b.y},v={x:u.x+m.x,y:u.y+m.y};Math.max(Math.abs(w.x-p[0].x),Math.abs(v.x-p[0].x))>=Math.max(Math.abs(w.y-p[0].y),Math.abs(v.y-p[0].y))?(d=(w.x+v.x)/2,g=p[0].y):(d=p[0].x,g=(w.y+v.y)/2)}return[[e,{x:c.x+b.x,y:c.y+b.y},...p,{x:u.x+m.x,y:u.y+m.y},n],d,g,y,S]}({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:i},targetPosition:o,center:{x:s,y:c},offset:u});return[l.reduce(((e,t,n)=>{let r="";return r=n>0&&n<l.length-1?function(e,t,n,r){const i=Math.min(ro(e,t)/2,ro(t,n)/2,r),{x:o,y:a}=t;if(e.x===o&&o===n.x||e.y===a&&a===n.y)return`L${o} ${a}`;if(e.y===a)return`L ${o+i*(e.x<n.x?-1:1)},${a}Q ${o},${a} ${o},${a+i*(e.y<n.y?1:-1)}`;const s=e.x<n.x?1:-1;return`L ${o},${a+i*(e.y<n.y?-1:1)}Q ${o},${a} ${o+i*s},${a}`}(l[n-1],t,l[n+1],a):`${0===n?"M":"L"}${t.x} ${t.y}`,e+r}),""),h,f,d,g]}function oo(e){return e&&!(!e.internals.handleBounds&&!e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function ao(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,"source"===r.type?t.push(r):"target"===r.type&&n.push(r);return{source:t,target:n}}function so(e,t,n=ti.Left,r=!1){const i=(t?.x??0)+e.internals.positionAbsolute.x,o=(t?.y??0)+e.internals.positionAbsolute.y,{width:a,height:s}=t??$i(e);if(r)return{x:i+a/2,y:o+s/2};switch(t?.position??n){case ti.Top:return{x:i+a/2,y:o};case ti.Right:return{x:i+a,y:o+s/2};case ti.Bottom:return{x:i+a/2,y:o+s};case ti.Left:return{x:i,y:o+s/2}}}function co(e,t){return e&&(t?e.find((e=>e.id===t)):e[0])||null}function uo(e,t){return e?"string"==typeof e?e:`${t?`${t}__`:""}${Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&")}`:""}const lo={nodeOrigin:[0,0],nodeExtent:Gr,elevateNodesOnSelect:!0,defaults:{}},ho={...lo,checkEquality:!0};function fo(e,t){const n={...e};for(const e in t)void 0!==t[e]&&(n[e]=t[e]);return n}function go(e,t,n,r){const i=fo(ho,r);let o=!0;const a=new Map(t),s=i?.elevateNodesOnSelect?1e3:0;t.clear(),n.clear();for(const c of e){let e=a.get(c.id);if(i.checkEquality&&c===e?.internals.userNode)t.set(c.id,e);else{const n=ai(c,i.nodeOrigin),r=ji(c.extent)?c.extent:i.nodeExtent,o=di(n,r,$i(c));e={...i.defaults,...c,measured:{width:c.measured?.width,height:c.measured?.height},internals:{positionAbsolute:o,handleBounds:c.measured?e?.internals.handleBounds:void 0,z:bo(c,s),userNode:c}},t.set(c.id,e)}e.measured&&e.measured.width&&e.measured.height||e.hidden||(o=!1),c.parentId&&po(e,t,n,r)}return o}function po(e,t,n,r){const{elevateNodesOnSelect:i,nodeOrigin:o,nodeExtent:a}=fo(lo,r),s=e.parentId,c=t.get(s);if(!c)return void console.warn(`Parent node ${s} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);!function(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}(e,n);const u=i?1e3:0,{x:l,y:h,z:f}=function(e,t,n,r,i){const{x:o,y:a}=t.internals.positionAbsolute,s=$i(e),c=ai(e,n),u=ji(e.extent)?di(c,e.extent,s):c;let l=di({x:o+u.x,y:a+u.y},r,s);"parent"===e.extent&&(l=gi(l,s,t));const h=bo(e,i),f=t.internals.z??0;return{x:l.x,y:l.y,z:f>h?f:h}}(e,c,o,a,u),{positionAbsolute:d}=e.internals,g=l!==d.x||h!==d.y;(g||f!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:g?{x:l,y:h}:d,z:f}})}function bo(e,t){return(Mi(e.zIndex)?e.zIndex:0)+(e.selected?t:0)}function mo(e,t,n,r=[0,0]){const i=[],o=new Map;for(const n of e){const e=t.get(n.parentId);if(!e)continue;const r=o.get(n.parentId)?.expandedRect??yi(e),i=ki(r,n.rect);o.set(n.parentId,{expandedRect:i,parent:e})}return o.size>0&&o.forEach((({expandedRect:t,parent:o},a)=>{const s=o.internals.positionAbsolute,c=$i(o),u=o.origin??r,l=t.x<s.x?Math.round(Math.abs(s.x-t.x)):0,h=t.y<s.y?Math.round(Math.abs(s.y-t.y)):0,f=Math.max(c.width,Math.round(t.width)),d=Math.max(c.height,Math.round(t.height)),g=(f-c.width)*u[0],p=(d-c.height)*u[1];(l>0||h>0||g||p)&&(i.push({id:a,type:"position",position:{x:o.position.x-l+g,y:o.position.y-h+p}}),n.get(a)?.forEach((t=>{e.some((e=>e.id===t.id))||i.push({id:t.id,type:"position",position:{x:t.position.x+l,y:t.position.y+h}})}))),(c.width<t.width||c.height<t.height||l||h)&&i.push({id:a,type:"dimensions",setAttributes:!0,dimensions:{width:f+(l?u[0]*l-g:0),height:d+(h?u[1]*h-p:0)}})})),i}function wo(e,t,n,r,i,o){let a=i;const s=r.get(a)||new Map;r.set(a,s.set(n,t)),a=`${i}-${e}`;const c=r.get(a)||new Map;if(r.set(a,c.set(n,t)),o){a=`${i}-${e}-${o}`;const s=r.get(a)||new Map;r.set(a,s.set(n,t))}}function vo(e,t,n){e.clear(),t.clear();for(const r of n){const{source:n,target:i,sourceHandle:o=null,targetHandle:a=null}=r,s={edgeId:r.id,source:n,target:i,sourceHandle:o,targetHandle:a},c=`${n}-${o}--${i}-${a}`;wo("source",s,`${i}-${a}--${n}-${o}`,e,n,o),wo("target",s,c,e,i,a),t.set(r.id,r)}}function yo(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return!!n&&(!!n.selected||yo(n,t))}function So(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function ko({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const i=[];for(const[e,o]of t){const t=n.get(e)?.internals.userNode;t&&i.push({...t,position:o.position,dragging:r})}if(!e)return[i[0],i];const o=n.get(e)?.internals.userNode;return[o?{...o,position:t.get(e)?.position||o.position,dragging:r}:i[0],i]}function Eo(e,t,n,r,i,o=!1){const a=r.get(e);if(!a)return null;const s="strict"===i?a.internals.handleBounds?.[t]:[...a.internals.handleBounds?.source??[],...a.internals.handleBounds?.target??[]],c=(n?s?.find((e=>e.id===n)):s?.[0])??null;return c&&o?{...c,...so(a,c,c.position,!0)}:c}function xo(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}const Mo=()=>!0;function To(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:i,fromType:o,doc:a,lib:s,flowId:c,isValidConnection:u=Mo,nodeLookup:l}){const h="target"===o,f=t?a.querySelector(`.${s}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:d,y:g}=Hi(e),p=a.elementFromPoint(d,g),b=p?.classList.contains(`${s}-flow__handle`)?p:f,m={handleDomNode:b,isValid:!1,connection:null,toHandle:null};if(b){const e=xo(void 0,b),t=b.getAttribute("data-nodeid"),o=b.getAttribute("data-handleid"),a=b.classList.contains("connectable"),s=b.classList.contains("connectableend");if(!t||!e)return m;const c={source:h?t:r,sourceHandle:h?o:i,target:h?r:t,targetHandle:h?i:o};m.connection=c;const f=a&&s&&(n===Kr.Strict?h&&"source"===e||!h&&"target"===e:t!==r||o!==i);m.isValid=f&&u(c),m.toHandle=Eo(t,e,o,l,n,!1)}return m}const Co={onPointerDown:function(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:i,edgeUpdaterType:o,isTarget:a,domNode:s,nodeLookup:c,lib:u,autoPanOnConnect:l,flowId:h,panBy:f,cancelConnection:d,onConnectStart:g,onConnect:p,onConnectEnd:b,isValidConnection:m=Mo,onReconnectEnd:w,updateConnection:v,getTransform:y,getFromHandle:S,autoPanSpeed:k}){const E=Bi(e.target);let x,M=0;const{x:T,y:C}=Hi(e),_=E?.elementFromPoint(T,C),P=xo(o,_),I=s?.getBoundingClientRect();if(!I||!P)return;const A=Eo(i,P,r,c,t);if(!A)return;let O=Hi(e,I),j=!1,$=null,R=!1,N=null;function L(){if(!l||!I)return;const[e,t]=bi(O,I,k);f({x:e,y:t}),M=requestAnimationFrame(L)}const D={...A,nodeId:i,type:P,position:A.position},F=c.get(i),B={inProgress:!0,isValid:null,from:so(F,D,ti.Left,!0),fromHandle:D,fromPosition:D.position,fromNode:F,to:O,toHandle:null,toPosition:ni[D.position],toNode:null};v(B);let z=B;function U(e){if(!S()||!D)return void q(e);const o=y();O=Hi(e,I),x=function(e,t,n,r){let i=[],o=1/0;const a=function(e,t,n){const r=[],i={x:e.x-n,y:e.y-n,width:2*n,height:2*n};for(const e of t.values())Ei(i,yi(e))>0&&r.push(e);return r}(e,n,t+250);for(const n of a){const a=[...n.internals.handleBounds?.source??[],...n.internals.handleBounds?.target??[]];for(const s of a){if(r.nodeId===s.nodeId&&r.type===s.type&&r.id===s.id)continue;const{x:a,y:c}=so(n,s,s.position,!0),u=Math.sqrt(Math.pow(a-e.x,2)+Math.pow(c-e.y,2));u>t||(u<o?(i=[{...s,x:a,y:c}],o=u):u===o&&i.push({...s,x:a,y:c}))}}if(!i.length)return null;if(i.length>1){const e="source"===r.type?"target":"source";return i.find((t=>t.type===e))??i[0]}return i[0]}(_i(O,o,!1,[1,1]),n,c,D),j||(L(),j=!0);const s=To(e,{handle:x,connectionMode:t,fromNodeId:i,fromHandleId:r,fromType:a?"target":"source",isValidConnection:m,doc:E,lib:u,flowId:h,nodeLookup:c});N=s.handleDomNode,$=s.connection,R=function(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}(!!x,s.isValid);const l={...z,isValid:R,to:x&&R?Pi({x:x.x,y:x.y},o):O,toHandle:s.toHandle,toPosition:R&&s.toHandle?s.toHandle.position:ni[D.position],toNode:s.toHandle?c.get(s.toHandle.nodeId):null};R&&x&&z.toHandle&&l.toHandle&&z.toHandle.type===l.toHandle.type&&z.toHandle.nodeId===l.toHandle.nodeId&&z.toHandle.id===l.toHandle.id&&z.to.x===l.to.x&&z.to.y===l.to.y||(v(l),z=l)}function q(e){(x||N)&&$&&R&&p?.($);const{inProgress:t,...n}=z,r={...n,toPosition:z.toHandle?z.toPosition:null};b?.(e,r),o&&w?.(e,r),d(),cancelAnimationFrame(M),j=!1,R=!1,$=null,N=null,E.removeEventListener("mousemove",U),E.removeEventListener("mouseup",q),E.removeEventListener("touchmove",U),E.removeEventListener("touchend",q)}g?.(e,{nodeId:i,handleId:r,handleType:P}),E.addEventListener("mousemove",U),E.addEventListener("mouseup",q),E.addEventListener("touchmove",U),E.addEventListener("touchend",q)},isValid:To},_o=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,Po=e=>({x:e.x,y:e.y,zoom:e.k}),Io=({x:e,y:t,zoom:n})=>$r.translate(e,t).scale(n),Ao=(e,t)=>e.target.closest(`.${t}`),Oo=(e,t)=>2===t&&Array.isArray(e)&&e.includes(2),jo=(e,t=0,n=()=>{})=>{const r="number"==typeof t&&t>0;return r||n(),r?e.transition().duration(t).on("end",n):e},$o=e=>{const t=e.ctrlKey&&Oi()?10:1;return-e.deltaY*(1===e.deltaMode?.05:e.deltaMode?1:.002)*t};var Ro;function No(e,t){return Math.max(0,t-e)}function Lo(e,t){return Math.max(0,e-t)}function Do(e,t,n){return Math.max(0,t-e,e-n)}function Fo(e,t){return e?!t:t}!function(e){e.Line="line",e.Handle="handle"}(Ro||(Ro={}));const Bo={width:0,height:0,x:0,y:0},zo={...Bo,pointerX:0,pointerY:0,aspectRatio:1};function Uo(e,t,n){const r=t.position.x+e.position.x,i=t.position.y+e.position.y,o=e.measured.width??0,a=e.measured.height??0,s=n[0]*o,c=n[1]*a;return[[r-s,i-c],[r+o-s,i+a-c]]}var qo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof n.g<"u"?n.g:typeof self<"u"?self:{};function Ho(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Jo,Go,Vo,Ko,Wo={exports:{}},Xo={},Yo={exports:{}},Qo={},Zo={};function ea(){return Vo||(Vo=1,"production"===ee.env.NODE_ENV?Yo.exports=function(){if(Jo)return Qo;Jo=1;var e=c(),t="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},n=e.useState,r=e.useEffect,i=e.useLayoutEffect,o=e.useDebugValue;function a(e){var n=e.getSnapshot;e=e.value;try{var r=n();return!t(e,r)}catch{return!0}}var s=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?function(e,t){return t()}:function(e,t){var s=t(),c=n({inst:{value:s,getSnapshot:t}}),u=c[0].inst,l=c[1];return i((function(){u.value=s,u.getSnapshot=t,a(u)&&l({inst:u})}),[e,s,t]),r((function(){return a(u)&&l({inst:u}),e((function(){a(u)&&l({inst:u})}))}),[e]),o(s),s};return Qo.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:s,Qo}():Yo.exports=(Go||(Go=1,"production"!==ee.env.NODE_ENV&&function(){function e(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!n(e,r)}catch{return!0}}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var t=c(),n="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=t.useState,i=t.useEffect,o=t.useLayoutEffect,a=t.useDebugValue,s=!1,u=!1,l=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?function(e,t){return t()}:function(c,l){s||void 0===t.startTransition||(s=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var h=l();if(!u){var f=l();n(h,f)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),u=!0)}var d=(f=r({inst:{value:h,getSnapshot:l}}))[0].inst,g=f[1];return o((function(){d.value=h,d.getSnapshot=l,e(d)&&g({inst:d})}),[c,h,l]),i((function(){return e(d)&&g({inst:d}),c((function(){e(d)&&g({inst:d})}))}),[c]),a(h),h};Zo.useSyncExternalStore=void 0!==t.useSyncExternalStore?t.useSyncExternalStore:l,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),Zo)),Yo.exports}var ta,na,ra={},ia=(na||(na=1,"production"===ee.env.NODE_ENV?Wo.exports=function(){if(Ko)return Xo;Ko=1;var e=c(),t=ea(),n="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=t.useSyncExternalStore,i=e.useRef,o=e.useEffect,a=e.useMemo,s=e.useDebugValue;return Xo.useSyncExternalStoreWithSelector=function(e,t,c,u,l){var h=i(null);if(null===h.current){var f={hasValue:!1,value:null};h.current=f}else f=h.current;h=a((function(){function e(e){if(!o){if(o=!0,r=e,e=u(e),void 0!==l&&f.hasValue){var t=f.value;if(l(t,e))return i=t}return i=e}if(t=i,n(r,e))return t;var a=u(e);return void 0!==l&&l(t,a)?(r=e,t):(r=e,i=a)}var r,i,o=!1,a=void 0===c?null:c;return[function(){return e(t())},null===a?void 0:function(){return e(a())}]}),[t,c,u,l]);var d=r(e,h[0],h[1]);return o((function(){f.hasValue=!0,f.value=d}),[d]),s(d),d},Xo}():Wo.exports=(ta||(ta=1,"production"!==ee.env.NODE_ENV&&function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var e=c(),t=ea(),n="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=t.useSyncExternalStore,i=e.useRef,o=e.useEffect,a=e.useMemo,s=e.useDebugValue;ra.useSyncExternalStoreWithSelector=function(e,t,c,u,l){var h=i(null);if(null===h.current){var f={hasValue:!1,value:null};h.current=f}else f=h.current;h=a((function(){function e(e){if(!o){if(o=!0,r=e,e=u(e),void 0!==l&&f.hasValue){var t=f.value;if(l(t,e))return i=t}return i=e}if(t=i,n(r,e))return t;var a=u(e);return void 0!==l&&l(t,a)?(r=e,t):(r=e,i=a)}var r,i,o=!1,a=void 0===c?null:c;return[function(){return e(t())},null===a?void 0:function(){return e(a())}]}),[t,c,u,l]);var d=r(e,h[0],h[1]);return o((function(){f.hasValue=!0,f.value=d}),[d]),s(d),d},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),ra)),Wo.exports);const oa=Ho(ia),aa={},sa=e=>{let t;const n=new Set,r=(e,r)=>{const i="function"==typeof e?e(t):e;if(!Object.is(i,t)){const e=t;t=r??("object"!=typeof i||null===i)?i:Object.assign({},t,i),n.forEach((n=>n(t,e)))}},i=()=>t,o={setState:r,getState:i,getInitialState:()=>a,subscribe:e=>(n.add(e),()=>n.delete(e)),destroy:()=>{"production"!==(aa?"production":void 0)&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},a=t=e(r,i,o);return o},{useDebugValue:ca}=c(),{useSyncExternalStoreWithSelector:ua}=oa,la=e=>e;function ha(e,t=la,n){const r=ua(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return ca(r),r}const fa=(e,t)=>{const n=(e=>e?sa(e):sa)(e),r=(e,r=t)=>ha(n,e,r);return Object.assign(r,n),r};function da(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[n,r]of e)if(!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}const ga=(0,s.createContext)(null),pa=ga.Provider,ba=Jr.error001();function ma(e,t){const n=(0,s.useContext)(ga);if(null===n)throw new Error(ba);return ha(n,e,t)}function wa(){const e=(0,s.useContext)(ga);if(null===e)throw new Error(ba);return(0,s.useMemo)((()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe})),[e])}const va={display:"none"},ya={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},Sa="react-flow__node-desc",ka="react-flow__edge-desc",Ea="react-flow__aria-live",xa=e=>e.ariaLiveMessage;function Ma({rfId:e}){const t=ma(xa);return(0,r.jsx)("div",{id:`${Ea}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:ya,children:t})}function Ta({rfId:e,disableKeyboardA11y:t}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{id:`${Sa}-${e}`,style:va,children:["Press enter or space to select a node.",!t&&"You can then use the arrow keys to move the node around."," Press delete to remove it and escape to cancel."," "]}),(0,r.jsx)("div",{id:`${ka}-${e}`,style:va,children:"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."}),!t&&(0,r.jsx)(Ma,{rfId:e})]})}const Ca=e=>e.userSelectionActive?"none":"all",_a=(0,s.forwardRef)((({position:e="top-left",children:t,className:n,style:i,...o},a)=>{const s=ma(Ca),c=`${e}`.split("-");return(0,r.jsx)("div",{className:te(["react-flow__panel",n,...c]),style:{...i,pointerEvents:s},ref:a,...o,children:t})}));function Pa({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:(0,r.jsx)(_a,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:(0,r.jsx)("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}_a.displayName="Panel";const Ia=e=>{const t=[],n=[];for(const[,n]of e.nodeLookup)n.selected&&t.push(n.internals.userNode);for(const[,t]of e.edgeLookup)t.selected&&n.push(t);return{selectedNodes:t,selectedEdges:n}},Aa=e=>e.id;function Oa(e,t){return da(e.selectedNodes.map(Aa),t.selectedNodes.map(Aa))&&da(e.selectedEdges.map(Aa),t.selectedEdges.map(Aa))}function ja({onSelectionChange:e}){const t=wa(),{selectedNodes:n,selectedEdges:r}=ma(Ia,Oa);return(0,s.useEffect)((()=>{const i={nodes:n,edges:r};e?.(i),t.getState().onSelectionChangeHandlers.forEach((e=>e(i)))}),[n,r,e]),null}const $a=e=>!!e.onSelectionChangeHandlers;function Ra({onSelectionChange:e}){const t=ma($a);return e||t?(0,r.jsx)(ja,{onSelectionChange:e}):null}const Na=[0,0],La={x:0,y:0,zoom:1},Da=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","onBeforeDelete","debug","autoPanSpeed","paneClickDistance","rfId"],Fa=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges,setPaneClickDistance:e.setPaneClickDistance}),Ba={translateExtent:Gr,nodeOrigin:Na,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1",paneClickDistance:0};function za(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:i,setTranslateExtent:o,setNodeExtent:a,reset:c,setDefaultNodesAndEdges:u,setPaneClickDistance:l}=ma(Fa,da),h=wa();(0,s.useEffect)((()=>(u(e.defaultNodes,e.defaultEdges),()=>{f.current=Ba,c()})),[]);const f=(0,s.useRef)(Ba);return(0,s.useEffect)((()=>{for(const s of Da){const c=e[s];c!==f.current[s]&&(typeof e[s]>"u"||("nodes"===s?t(c):"edges"===s?n(c):"minZoom"===s?r(c):"maxZoom"===s?i(c):"translateExtent"===s?o(c):"nodeExtent"===s?a(c):"paneClickDistance"===s?l(c):"fitView"===s?h.setState({fitViewQueued:c}):"fitViewOptions"===s?h.setState({fitViewOptions:c}):h.setState({[s]:c})))}f.current=e}),Da.map((t=>e[t]))),null}function Ua(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}const qa=typeof document<"u"?document:null;function Ha(e=null,t={target:qa,actInsideInputWithModifier:!0}){const[n,r]=(0,s.useState)(!1),i=(0,s.useRef)(!1),o=(0,s.useRef)(new Set([])),[a,c]=(0,s.useMemo)((()=>{if(null!==e){const t=(Array.isArray(e)?e:[e]).filter((e=>"string"==typeof e)).map((e=>e.replace("+","\n").replace("\n\n","\n+").split("\n"))),n=t.reduce(((e,t)=>e.concat(...t)),[]);return[t,n]}return[[],[]]}),[e]);return(0,s.useEffect)((()=>{const n=t?.target||qa;if(null!==e){const e=e=>{if(i.current=e.ctrlKey||e.metaKey||e.shiftKey||e.altKey,(!i.current||i.current&&!t.actInsideInputWithModifier)&&Ui(e))return!1;const n=Ga(e.code,c);if(o.current.add(e[n]),Ja(a,o.current,!1)){const n=e.composedPath?.()?.[0]||e.target,o="BUTTON"===n?.nodeName||"A"===n?.nodeName;!1!==t.preventDefault&&(i.current||!o)&&e.preventDefault(),r(!0)}},s=e=>{const t=Ga(e.code,c);Ja(a,o.current,!0)?(r(!1),o.current.clear()):o.current.delete(e[t]),"Meta"===e.key&&o.current.clear(),i.current=!1},u=()=>{o.current.clear(),r(!1)};return n?.addEventListener("keydown",e),n?.addEventListener("keyup",s),window.addEventListener("blur",u),window.addEventListener("contextmenu",u),()=>{n?.removeEventListener("keydown",e),n?.removeEventListener("keyup",s),window.removeEventListener("blur",u),window.removeEventListener("contextmenu",u)}}}),[e,r]),n}function Ja(e,t,n){return e.filter((e=>n||e.length===t.size)).some((e=>e.every((e=>t.has(e)))))}function Ga(e,t){return t.includes(e)?"code":"key"}const Va=()=>{const e=wa();return(0,s.useMemo)((()=>({zoomIn:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1.2,{duration:t?.duration}):Promise.resolve(!1)},zoomOut:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,{duration:t?.duration}):Promise.resolve(!1)},zoomTo:(t,n)=>{const{panZoom:r}=e.getState();return r?r.scaleTo(t,{duration:n?.duration}):Promise.resolve(!1)},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{const{transform:[r,i,o],panZoom:a}=e.getState();return a?(await a.setViewport({x:t.x??r,y:t.y??i,zoom:t.zoom??o},{duration:n?.duration}),Promise.resolve(!0)):Promise.resolve(!1)},getViewport:()=>{const[t,n,r]=e.getState().transform;return{x:t,y:n,zoom:r}},setCenter:async(t,n,r)=>{const{width:i,height:o,maxZoom:a,panZoom:s}=e.getState(),c=typeof r?.zoom<"u"?r.zoom:a,u=i/2-t*c,l=o/2-n*c;return s?(await s.setViewport({x:u,y:l,zoom:c},{duration:r?.duration}),Promise.resolve(!0)):Promise.resolve(!1)},fitBounds:async(t,n)=>{const{width:r,height:i,minZoom:o,maxZoom:a,panZoom:s}=e.getState(),c=Ai(t,r,i,o,a,n?.padding??.1);return s?(await s.setViewport(c,{duration:n?.duration}),Promise.resolve(!0)):Promise.resolve(!1)},screenToFlowPosition:(t,n={})=>{const{transform:r,snapGrid:i,snapToGrid:o,domNode:a}=e.getState();if(!a)return t;const{x:s,y:c}=a.getBoundingClientRect(),u={x:t.x-s,y:t.y-c},l=n.snapGrid??i,h=n.snapToGrid??o;return _i(u,r,h,l)},flowToScreenPosition:t=>{const{transform:n,domNode:r}=e.getState();if(!r)return t;const{x:i,y:o}=r.getBoundingClientRect(),a=Pi(t,n);return{x:a.x+i,y:a.y+o}}})),[])};function Ka(e,t){const n=[],r=new Map,i=[];for(const t of e)if("add"!==t.type)if("remove"===t.type||"replace"===t.type)r.set(t.id,[t]);else{const e=r.get(t.id);e?e.push(t):r.set(t.id,[t])}else i.push(t);for(const e of t){const t=r.get(e.id);if(!t){n.push(e);continue}if("remove"===t[0].type)continue;if("replace"===t[0].type){n.push({...t[0].item});continue}const i={...e};for(const e of t)Wa(e,i);n.push(i)}return i.length&&i.forEach((e=>{void 0!==e.index?n.splice(e.index,0,{...e.item}):n.push({...e.item})})),n}function Wa(e,t){switch(e.type){case"select":t.selected=e.selected;break;case"position":typeof e.position<"u"&&(t.position=e.position),typeof e.dragging<"u"&&(t.dragging=e.dragging);break;case"dimensions":typeof e.dimensions<"u"&&(t.measured??={},t.measured.width=e.dimensions.width,t.measured.height=e.dimensions.height,e.setAttributes&&(t.width=e.dimensions.width,t.height=e.dimensions.height)),"boolean"==typeof e.resizing&&(t.resizing=e.resizing)}}function Xa(e,t){return Ka(e,t)}function Ya(e,t){return Ka(e,t)}function Qa(e,t){return{id:e,type:"select",selected:t}}function Za(e,t=new Set,n=!1){const r=[];for(const[i,o]of e){const e=t.has(i);(void 0!==o.selected||e)&&o.selected!==e&&(n&&(o.selected=e),r.push(Qa(o.id,e)))}return r}function es({items:e=[],lookup:t}){const n=[],r=new Map(e.map((e=>[e.id,e])));for(const[r,i]of e.entries()){const e=t.get(i.id),o=e?.internals?.userNode??e;void 0!==o&&o!==i&&n.push({id:i.id,item:i,type:"replace"}),void 0===o&&n.push({item:i,type:"add",index:r})}for(const[e]of t)void 0===r.get(e)&&n.push({id:e,type:"remove"});return n}function ts(e){return{id:e.id,type:"remove"}}const ns=e=>(e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e))(e),rs=e=>ii(e);function is(e){return(0,s.forwardRef)(e)}const os=typeof window<"u"?s.useLayoutEffect:s.useEffect;function as(e){const[t,n]=(0,s.useState)(BigInt(0)),[r]=(0,s.useState)((()=>function(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}((()=>n((e=>e+BigInt(1)))))));return os((()=>{const t=r.get();t.length&&(e(t),r.reset())}),[t]),r}const ss=(0,s.createContext)(null);function cs({children:e}){const t=wa(),n=as((0,s.useCallback)((e=>{const{nodes:n=[],setNodes:r,hasDefaultNodes:i,onNodesChange:o,nodeLookup:a}=t.getState();let s=n;for(const t of e)s="function"==typeof t?t(s):t;i?r(s):o&&o(es({items:s,lookup:a}))}),[])),i=as((0,s.useCallback)((e=>{const{edges:n=[],setEdges:r,hasDefaultEdges:i,onEdgesChange:o,edgeLookup:a}=t.getState();let s=n;for(const t of e)s="function"==typeof t?t(s):t;i?r(s):o&&o(es({items:s,lookup:a}))}),[])),o=(0,s.useMemo)((()=>({nodeQueue:n,edgeQueue:i})),[]);return(0,r.jsx)(ss.Provider,{value:o,children:e})}const us=e=>!!e.panZoom;function ls(){const e=Va(),t=wa(),n=function(){const e=(0,s.useContext)(ss);if(!e)throw new Error("useBatchContext must be used within a BatchProvider");return e}(),r=ma(us),i=(0,s.useMemo)((()=>{const e=e=>t.getState().nodeLookup.get(e),r=e=>{n.nodeQueue.push(e)},i=e=>{n.edgeQueue.push(e)},o=e=>{const{nodeLookup:n,nodeOrigin:r}=t.getState(),i=ns(e)?e:n.get(e.id),o=i.parentId?Ni(i.position,i.measured,i.parentId,n,r):i.position,a={...i,position:o,width:i.measured?.width??i.width,height:i.measured?.height??i.height};return yi(a)},a=(e,t,n={replace:!1})=>{r((r=>r.map((r=>{if(r.id===e){const e="function"==typeof t?t(r):t;return n.replace&&ns(e)?e:{...r,...e}}return r}))))},s=(e,t,n={replace:!1})=>{i((r=>r.map((r=>{if(r.id===e){const e="function"==typeof t?t(r):t;return n.replace&&rs(e)?e:{...r,...e}}return r}))))};return{getNodes:()=>t.getState().nodes.map((e=>({...e}))),getNode:t=>e(t)?.internals.userNode,getInternalNode:e,getEdges:()=>{const{edges:e=[]}=t.getState();return e.map((e=>({...e})))},getEdge:e=>t.getState().edgeLookup.get(e),setNodes:r,setEdges:i,addNodes:e=>{const t=Array.isArray(e)?e:[e];n.nodeQueue.push((e=>[...e,...t]))},addEdges:e=>{const t=Array.isArray(e)?e:[e];n.edgeQueue.push((e=>[...e,...t]))},toObject:()=>{const{nodes:e=[],edges:n=[],transform:r}=t.getState(),[i,o,a]=r;return{nodes:e.map((e=>({...e}))),edges:n.map((e=>({...e}))),viewport:{x:i,y:o,zoom:a}}},deleteElements:async({nodes:e=[],edges:n=[]})=>{const{nodes:r,edges:i,onNodesDelete:o,onEdgesDelete:a,triggerNodeChanges:s,triggerEdgeChanges:c,onDelete:u,onBeforeDelete:l}=t.getState(),{nodes:h,edges:f}=await async function({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:i}){const o=new Set(e.map((e=>e.id))),a=[];for(const e of n){if(!1===e.deletable)continue;const t=o.has(e.id),n=!t&&e.parentId&&a.find((t=>t.id===e.parentId));(t||n)&&a.push(e)}const s=new Set(t.map((e=>e.id))),c=r.filter((e=>!1!==e.deletable)),u=li(a,c);for(const e of c)s.has(e.id)&&!u.find((t=>t.id===e.id))&&u.push(e);if(!i)return{edges:u,nodes:a};const l=await i({nodes:a,edges:u});return"boolean"==typeof l?l?{edges:u,nodes:a}:{edges:[],nodes:[]}:l}({nodesToRemove:e,edgesToRemove:n,nodes:r,edges:i,onBeforeDelete:l}),d=f.length>0,g=h.length>0;if(d){const e=f.map(ts);a?.(f),c(e)}if(g){const e=h.map(ts);o?.(h),s(e)}return(g||d)&&u?.({nodes:h,edges:f}),{deletedNodes:h,deletedEdges:f}},getIntersectingNodes:(e,n=!0,r)=>{const i=xi(e),a=i?e:o(e),s=void 0!==r;return a?(r||t.getState().nodes).filter((r=>{const o=t.getState().nodeLookup.get(r.id);if(o&&!i&&(r.id===e.id||!o.internals.positionAbsolute))return!1;const c=yi(s?r:o),u=Ei(c,a);return n&&u>0||u>=a.width*a.height})):[]},isNodeIntersecting:(e,t,n=!0)=>{const r=xi(e)?e:o(e);if(!r)return!1;const i=Ei(r,t);return n&&i>0||i>=r.width*r.height},updateNode:a,updateNodeData:(e,t,n={replace:!1})=>{a(e,(e=>{const r="function"==typeof t?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}}),n)},updateEdge:s,updateEdgeData:(e,t,n={replace:!1})=>{s(e,(e=>{const r="function"==typeof t?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}}),n)},getNodesBounds:e=>{const{nodeLookup:n,nodeOrigin:r}=t.getState();return si(e,{nodeLookup:n,nodeOrigin:r})},getHandleConnections:({type:e,id:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}-${e}${n?`-${n}`:""}`)?.values()??[]),getNodeConnections:({type:e,handleId:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}${e?n?`-${e}-${n}`:`-${e}`:""}`)?.values()??[]),fitView:async e=>{const r=t.getState().fitViewResolver??Promise.withResolvers();return t.setState({fitViewQueued:!0,fitViewOptions:e,fitViewResolver:r}),n.nodeQueue.push((e=>[...e])),r.promise}}}),[]);return(0,s.useMemo)((()=>({...i,...e,viewportInitialized:r})),[r])}const hs=e=>e.selected,fs={actInsideInputWithModifier:!1},ds=typeof window<"u"?window:void 0,gs={position:"absolute",width:"100%",height:"100%",top:0,left:0},ps=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib});function bs({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:i=!1,panOnScrollSpeed:o=.5,panOnScrollMode:a=Xr.Free,zoomOnDoubleClick:c=!0,panOnDrag:u=!0,defaultViewport:l,translateExtent:h,minZoom:f,maxZoom:d,zoomActivationKeyCode:g,preventScrolling:p=!0,children:b,noWheelClassName:m,noPanClassName:w,onViewportChange:v,isControlledViewport:y,paneClickDistance:S}){const k=wa(),E=(0,s.useRef)(null),{userSelectionActive:x,lib:M}=ma(ps,da),T=Ha(g),C=(0,s.useRef)();!function(e){const t=wa();(0,s.useEffect)((()=>{const n=()=>{if(!e.current)return!1;const n=Fi(e.current);(0===n.height||0===n.width)&&t.getState().onError?.("004",Jr.error004()),t.setState({width:n.width||500,height:n.height||500})};if(e.current){n(),window.addEventListener("resize",n);const t=new ResizeObserver((()=>n()));return t.observe(e.current),()=>{window.removeEventListener("resize",n),t&&e.current&&t.unobserve(e.current)}}}),[])}(E);const _=(0,s.useCallback)((e=>{v?.({x:e[0],y:e[1],zoom:e[2]}),y||k.setState({transform:e})}),[v,y]);return(0,s.useEffect)((()=>{if(E.current){C.current=function({domNode:e,minZoom:t,maxZoom:n,paneClickDistance:r,translateExtent:i,viewport:o,onPanZoom:a,onPanZoomStart:s,onPanZoomEnd:c,onDraggingChange:u}){const l={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{x:0,y:0,zoom:0},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},h=e.getBoundingClientRect(),f=Hr().clickDistance(!Mi(r)||r<0?0:r).scaleExtent([t,n]).translateExtent(i),d=wt(e).call(f);w({x:o.x,y:o.y,zoom:fi(o.zoom,t,n)},[[0,0],[h.width,h.height]],i);const g=d.on("wheel.zoom"),p=d.on("dblclick.zoom");function b(e,t){return d?new Promise((n=>{f?.transform(jo(d,t?.duration,(()=>n(!0))),e)})):Promise.resolve(!1)}function m(){f.on("zoom",null)}async function w(e,t,n){const r=Io(e),i=f?.constrain()(r,t,n);return i&&await b(i),new Promise((e=>e(i)))}return f.wheelDelta($o),{update:function({noWheelClassName:e,noPanClassName:t,onPaneContextMenu:n,userSelectionActive:r,panOnScroll:i,panOnDrag:o,panOnScrollMode:h,panOnScrollSpeed:b,preventScrolling:w,zoomOnPinch:v,zoomOnScroll:y,zoomOnDoubleClick:S,zoomActivationKeyPressed:k,lib:E,onTransformChange:x}){r&&!l.isZoomingOrPanning&&m();const M=!i||k||r?function({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,i){if(!t&&"wheel"===r.type&&!r.ctrlKey||Ao(r,e))return null;r.preventDefault(),n.call(this,r,i)}}({noWheelClassName:e,preventScrolling:w,d3ZoomHandler:g}):function({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:i,panOnScrollSpeed:o,zoomOnPinch:a,onPanZoomStart:s,onPanZoom:c,onPanZoomEnd:u}){return l=>{if(Ao(l,t))return!1;l.preventDefault(),l.stopImmediatePropagation();const h=n.property("__zoom").k||1;if(l.ctrlKey&&a){const e=vt(l),t=$o(l),i=h*Math.pow(2,t);return void r.scaleTo(n,i,e,l)}const f=1===l.deltaMode?20:1;let d=i===Xr.Vertical?0:l.deltaX*f,g=i===Xr.Horizontal?0:l.deltaY*f;!Oi()&&l.shiftKey&&i!==Xr.Vertical&&(d=l.deltaY*f,g=0),r.translateBy(n,-d/h*o,-g/h*o,{internal:!0});const p=Po(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling||(e.isPanScrolling=!0,s?.(l,p)),e.isPanScrolling&&(c?.(l,p),e.panScrollTimeout=setTimeout((()=>{u?.(l,p),e.isPanScrolling=!1}),150))}}({zoomPanValues:l,noWheelClassName:e,d3Selection:d,d3Zoom:f,panOnScrollMode:h,panOnScrollSpeed:b,zoomOnPinch:v,onPanZoomStart:s,onPanZoom:a,onPanZoomEnd:c});if(d.on("wheel.zoom",M,{passive:!1}),!r){const e=function({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const i=Po(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=i,"mousedown"===r.sourceEvent?.type&&t(!0),n&&n?.(r.sourceEvent,i)}}({zoomPanValues:l,onDraggingChange:u,onPanZoomStart:s});f.on("start",e);const t=function({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:i}){return o=>{e.usedRightMouseButton=!(!n||!Oo(t,e.mouseButton??0)),o.sourceEvent?.sync||r([o.transform.x,o.transform.y,o.transform.k]),i&&!o.sourceEvent?.internal&&i?.(o.sourceEvent,Po(o.transform))}}({zoomPanValues:l,panOnDrag:o,onPaneContextMenu:!!n,onPanZoom:a,onTransformChange:x});f.on("zoom",t);const r=function({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:i,onPaneContextMenu:o}){return a=>{if(!a.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,o&&Oo(t,e.mouseButton??0)&&!e.usedRightMouseButton&&a.sourceEvent&&o(a.sourceEvent),e.usedRightMouseButton=!1,r(!1),i&&_o(e.prevViewport,a.transform))){const t=Po(a.transform);e.prevViewport=t,clearTimeout(e.timerId),e.timerId=setTimeout((()=>{i?.(a.sourceEvent,t)}),n?150:0)}}}({zoomPanValues:l,panOnDrag:o,panOnScroll:i,onPaneContextMenu:n,onPanZoomEnd:c,onDraggingChange:u});f.on("end",r)}const T=function({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:i,zoomOnDoubleClick:o,userSelectionActive:a,noWheelClassName:s,noPanClassName:c,lib:u}){return l=>{const h=e||t,f=n&&l.ctrlKey;if(1===l.button&&"mousedown"===l.type&&(Ao(l,`${u}-flow__node`)||Ao(l,`${u}-flow__edge`)))return!0;if(!r&&!h&&!i&&!o&&!n||a||Ao(l,s)&&"wheel"===l.type||Ao(l,c)&&("wheel"!==l.type||i&&"wheel"===l.type&&!e)||!n&&l.ctrlKey&&"wheel"===l.type)return!1;if(!n&&"touchstart"===l.type&&l.touches?.length>1)return l.preventDefault(),!1;if(!h&&!i&&!f&&"wheel"===l.type||!r&&("mousedown"===l.type||"touchstart"===l.type)||Array.isArray(r)&&!r.includes(l.button)&&"mousedown"===l.type)return!1;const d=Array.isArray(r)&&r.includes(l.button)||!l.button||l.button<=1;return(!l.ctrlKey||"wheel"===l.type)&&d}}({zoomActivationKeyPressed:k,panOnDrag:o,zoomOnScroll:y,panOnScroll:i,zoomOnDoubleClick:S,zoomOnPinch:v,userSelectionActive:r,noPanClassName:t,noWheelClassName:e,lib:E});f.filter(T),S?d.on("dblclick.zoom",p):d.on("dblclick.zoom",null)},destroy:m,setViewport:async function(e,t){const n=Io(e);return await b(n,t),new Promise((e=>e(n)))},setViewportConstrained:w,getViewport:function(){const e=d?Rr(d.node()):{x:0,y:0,k:1};return{x:e.x,y:e.y,zoom:e.k}},scaleTo:function(e,t){return d?new Promise((n=>{f?.scaleTo(jo(d,t?.duration,(()=>n(!0))),e)})):Promise.resolve(!1)},scaleBy:function(e,t){return d?new Promise((n=>{f?.scaleBy(jo(d,t?.duration,(()=>n(!0))),e)})):Promise.resolve(!1)},setScaleExtent:function(e){f?.scaleExtent(e)},setTranslateExtent:function(e){f?.translateExtent(e)},syncViewport:function(e){if(d){const t=Io(e),n=d.property("__zoom");(n.k!==e.zoom||n.x!==e.x||n.y!==e.y)&&f?.transform(d,t,null,{sync:!0})}},setClickDistance:function(e){const t=!Mi(e)||e<0?0:e;f?.clickDistance(t)}}}({domNode:E.current,minZoom:f,maxZoom:d,translateExtent:h,viewport:l,paneClickDistance:S,onDraggingChange:e=>k.setState({paneDragging:e}),onPanZoomStart:(e,t)=>{const{onViewportChangeStart:n,onMoveStart:r}=k.getState();r?.(e,t),n?.(t)},onPanZoom:(e,t)=>{const{onViewportChange:n,onMove:r}=k.getState();r?.(e,t),n?.(t)},onPanZoomEnd:(e,t)=>{const{onViewportChangeEnd:n,onMoveEnd:r}=k.getState();r?.(e,t),n?.(t)}});const{x:e,y:t,zoom:n}=C.current.getViewport();return k.setState({panZoom:C.current,transform:[e,t,n],domNode:E.current.closest(".react-flow")}),()=>{C.current?.destroy()}}}),[]),(0,s.useEffect)((()=>{C.current?.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:i,panOnScrollSpeed:o,panOnScrollMode:a,zoomOnDoubleClick:c,panOnDrag:u,zoomActivationKeyPressed:T,preventScrolling:p,noPanClassName:w,userSelectionActive:x,noWheelClassName:m,lib:M,onTransformChange:_})}),[e,t,n,i,o,a,c,u,T,p,w,x,m,M,_]),(0,r.jsx)("div",{className:"react-flow__renderer",ref:E,style:gs,children:b})}const ms=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function ws(){const{userSelectionActive:e,userSelectionRect:t}=ma(ms,da);return e&&t?(0,r.jsx)("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}const vs=(e,t)=>n=>{n.target===t.current&&e?.(n)},ys=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function Ss({isSelecting:e,selectionKeyPressed:t,selectionMode:n=Yr.Full,panOnDrag:i,selectionOnDrag:o,onSelectionStart:a,onSelectionEnd:c,onPaneClick:u,onPaneContextMenu:l,onPaneScroll:h,onPaneMouseEnter:f,onPaneMouseMove:d,onPaneMouseLeave:g,children:p}){const b=wa(),{userSelectionActive:m,elementsSelectable:w,dragging:v,connectionInProgress:y}=ma(ys,da),S=w&&(e||m),k=(0,s.useRef)(null),E=(0,s.useRef)(),x=(0,s.useRef)(new Set),M=(0,s.useRef)(new Set),T=(0,s.useRef)(!1),C=(0,s.useRef)(!1),_=e=>{T.current||y?T.current=!1:(u?.(e),b.getState().resetSelectedElements(),b.setState({nodesSelectionActive:!1}))},P=h?e=>h(e):void 0,I=!0===i||Array.isArray(i)&&i.includes(0);return(0,r.jsxs)("div",{className:te(["react-flow__pane",{draggable:I,dragging:v,selection:e}]),onClick:S?void 0:vs(_,k),onContextMenu:vs((e=>{Array.isArray(i)&&i?.includes(2)?e.preventDefault():l?.(e)}),k),onWheel:vs(P,k),onPointerEnter:S?void 0:f,onPointerDown:S?t=>{const{resetSelectedElements:n,domNode:r}=b.getState();if(E.current=r?.getBoundingClientRect(),!w||!e||0!==t.button||t.target!==k.current||!E.current)return;t.target?.setPointerCapture?.(t.pointerId),C.current=!0,T.current=!1;const{x:i,y:o}=Hi(t.nativeEvent,E.current);n(),b.setState({userSelectionRect:{width:0,height:0,startX:i,startY:o,x:i,y:o}}),a?.(t)}:d,onPointerMove:S?e=>{const{userSelectionRect:t,transform:r,nodeLookup:i,edgeLookup:o,connectionLookup:a,triggerNodeChanges:s,triggerEdgeChanges:c,defaultEdgeOptions:u}=b.getState();if(!E.current||!t)return;T.current=!0;const{x:l,y:h}=Hi(e.nativeEvent,E.current),{startX:f,startY:d}=t,g={startX:f,startY:d,x:l<f?l:f,y:h<d?h:d,width:Math.abs(l-f),height:Math.abs(h-d)},p=x.current,m=M.current;x.current=new Set(ui(i,g,r,n===Yr.Partial,!0).map((e=>e.id))),M.current=new Set;const w=u?.selectable??!0;for(const e of x.current){const t=a.get(e);if(t)for(const{edgeId:e}of t.values()){const t=o.get(e);t&&(t.selectable??w)&&M.current.add(e)}}Li(p,x.current)||s(Za(i,x.current,!0)),Li(m,M.current)||c(Za(o,M.current)),b.setState({userSelectionRect:g,userSelectionActive:!0,nodesSelectionActive:!1})}:d,onPointerUp:S?e=>{if(0!==e.button||!C.current)return;e.target?.releasePointerCapture?.(e.pointerId);const{userSelectionRect:n}=b.getState();!m&&n&&e.target===k.current&&_?.(e),b.setState({userSelectionActive:!1,userSelectionRect:null,nodesSelectionActive:x.current.size>0}),c?.(e),(t||o)&&(T.current=!1),C.current=!1}:void 0,onPointerLeave:g,ref:k,style:gs,children:[p,(0,r.jsx)(ws,{})]})}function ks({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:i,unselectNodesAndEdges:o,multiSelectionActive:a,nodeLookup:s,onError:c}=t.getState(),u=s.get(e);u?(t.setState({nodesSelectionActive:!1}),u.selected?(n||u.selected&&a)&&(o({nodes:[u],edges:[]}),requestAnimationFrame((()=>r?.current?.blur()))):i([e])):c?.("012",Jr.error012(e))}function Es({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:i,isSelectable:o,nodeClickDistance:a}){const c=wa(),[u,l]=(0,s.useState)(!1),h=(0,s.useRef)();return(0,s.useEffect)((()=>{h.current=function({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:i}){let o={x:null,y:null},a=0,s=new Map,c=!1,u={x:0,y:0},l=null,h=!1,f=null,d=!1;return{update:function({noDragClassName:g,handleSelector:p,domNode:b,isSelectable:m,nodeId:w,nodeClickDistance:v=0}){function y({x:e,y:n},i){const{nodeLookup:a,nodeExtent:c,snapGrid:u,snapToGrid:l,nodeOrigin:h,onNodeDrag:f,onSelectionDrag:d,onError:g,updateNodePositions:p}=t();o={x:e,y:n};let b=!1,m={x:0,y:0,x2:0,y2:0};if(s.size>1&&c){const e=ci(s);m=wi(e)}for(const[t,r]of s){if(!a.has(t))continue;let i={x:e-r.distance.x,y:n-r.distance.y};l&&(i=Ci(i,u));let o=[[c[0][0],c[0][1]],[c[1][0],c[1][1]]];if(s.size>1&&c&&!r.extent){const{positionAbsolute:e}=r.internals,t=e.x-m.x+c[0][0],n=e.x+r.measured.width-m.x2+c[1][0];o=[[t,e.y-m.y+c[0][1]],[n,e.y+r.measured.height-m.y2+c[1][1]]]}const{position:f,positionAbsolute:d}=hi({nodeId:t,nextPosition:i,nodeLookup:a,nodeExtent:o,nodeOrigin:h,onError:g});b=b||r.position.x!==f.x||r.position.y!==f.y,r.position=f,r.internals.positionAbsolute=d}if(b&&(p(s,!0),i&&(r||f||!w&&d))){const[e,t]=ko({nodeId:w,dragItems:s,nodeLookup:a});r?.(i,s,e,t),f?.(i,e,t),w||d?.(i,t)}}async function S(){if(!l)return;const{transform:e,panBy:n,autoPanSpeed:r,autoPanOnNodeDrag:i}=t();if(!i)return c=!1,void cancelAnimationFrame(a);const[s,h]=bi(u,l,r);(0!==s||0!==h)&&(o.x=(o.x??0)-s/e[2],o.y=(o.y??0)-h/e[2],await n({x:s,y:h})&&y(o,null)),a=requestAnimationFrame(S)}function k(r){const{nodeLookup:i,multiSelectionActive:a,nodesDraggable:c,transform:u,snapGrid:f,snapToGrid:d,selectNodesOnDrag:g,onNodeDragStart:p,onSelectionDragStart:b,unselectNodesAndEdges:v}=t();h=!0,(!g||!m)&&!a&&w&&(i.get(w)?.selected||v()),m&&g&&w&&e?.(w);const y=Di(r.sourceEvent,{transform:u,snapGrid:f,snapToGrid:d,containerBounds:l});if(o=y,s=function(e,t,n,r){const i=new Map;for(const[o,a]of e)if((a.selected||a.id===r)&&(!a.parentId||!yo(a,e))&&(a.draggable||t&&typeof a.draggable>"u")){const t=e.get(o);t&&i.set(o,{id:o,position:t.position||{x:0,y:0},distance:{x:n.x-t.internals.positionAbsolute.x,y:n.y-t.internals.positionAbsolute.y},extent:t.extent,parentId:t.parentId,origin:t.origin,expandParent:t.expandParent,internals:{positionAbsolute:t.internals.positionAbsolute||{x:0,y:0}},measured:{width:t.measured.width??0,height:t.measured.height??0}})}return i}(i,c,y,w),s.size>0&&(n||p||!w&&b)){const[e,t]=ko({nodeId:w,dragItems:s,nodeLookup:i});n?.(r.sourceEvent,s,e,t),p?.(r.sourceEvent,e,t),w||b?.(r.sourceEvent,t)}}f=wt(b);const E=Ot().clickDistance(v).on("start",(e=>{const{domNode:n,nodeDragThreshold:r,transform:i,snapGrid:a,snapToGrid:s}=t();l=n?.getBoundingClientRect()||null,d=!1,0===r&&k(e),o=Di(e.sourceEvent,{transform:i,snapGrid:a,snapToGrid:s,containerBounds:l}),u=Hi(e.sourceEvent,l)})).on("drag",(e=>{const{autoPanOnNodeDrag:n,transform:r,snapGrid:i,snapToGrid:a,nodeDragThreshold:f,nodeLookup:g}=t(),p=Di(e.sourceEvent,{transform:r,snapGrid:i,snapToGrid:a,containerBounds:l});if(("touchmove"===e.sourceEvent.type&&e.sourceEvent.touches.length>1||w&&!g.has(w))&&(d=!0),!d){if(!c&&n&&h&&(c=!0,S()),!h){const t=p.xSnapped-(o.x??0),n=p.ySnapped-(o.y??0);Math.sqrt(t*t+n*n)>f&&k(e)}(o.x!==p.xSnapped||o.y!==p.ySnapped)&&s&&h&&(u=Hi(e.sourceEvent,l),y(p,e.sourceEvent))}})).on("end",(e=>{if(h&&!d&&(c=!1,h=!1,cancelAnimationFrame(a),s.size>0)){const{nodeLookup:n,updateNodePositions:r,onNodeDragStop:o,onSelectionDragStop:a}=t();if(r(s,!1),i||o||!w&&a){const[t,r]=ko({nodeId:w,dragItems:s,nodeLookup:n,dragging:!1});i?.(e.sourceEvent,s,t,r),o?.(e.sourceEvent,t,r),w||a?.(e.sourceEvent,r)}}})).filter((e=>{const t=e.target;return!e.button&&(!g||!So(t,`.${g}`,b))&&(!p||So(t,p,b))}));f.call(E)},destroy:function(){f?.on(".drag",null)}}}({getStoreItems:()=>c.getState(),onNodeMouseDown:t=>{ks({id:t,store:c,nodeRef:e})},onDragStart:()=>{l(!0)},onDragStop:()=>{l(!1)}})}),[]),(0,s.useEffect)((()=>{if(t)h.current?.destroy();else if(e.current)return h.current?.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:o,nodeId:i,nodeClickDistance:a}),()=>{h.current?.destroy()}}),[n,r,t,o,e,i]),u}const xs=e=>t=>t.selected&&(t.draggable||e&&typeof t.draggable>"u");function Ms(){const e=wa();return(0,s.useCallback)((t=>{const{nodeExtent:n,snapToGrid:r,snapGrid:i,nodesDraggable:o,onError:a,updateNodePositions:s,nodeLookup:c,nodeOrigin:u}=e.getState(),l=new Map,h=xs(o),f=r?i[0]:5,d=r?i[1]:5,g=t.direction.x*f*t.factor,p=t.direction.y*d*t.factor;for(const[,e]of c){if(!h(e))continue;let t={x:e.internals.positionAbsolute.x+g,y:e.internals.positionAbsolute.y+p};r&&(t=Ci(t,i));const{position:o,positionAbsolute:s}=hi({nodeId:e.id,nextPosition:t,nodeLookup:c,nodeExtent:n,nodeOrigin:u,onError:a});e.position=o,e.internals.positionAbsolute=s,l.set(e.id,e)}s(l)}),[])}const Ts=(0,s.createContext)(null),Cs=Ts.Provider;Ts.Consumer;const _s=()=>(0,s.useContext)(Ts),Ps=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),Is=(0,s.memo)(is((function({type:e="source",position:t=ti.Top,isValidConnection:n,isConnectable:i=!0,isConnectableStart:o=!0,isConnectableEnd:a=!0,id:s,onConnect:c,children:u,className:l,onMouseDown:h,onTouchStart:f,...d},g){const p=s||null,b="target"===e,m=wa(),w=_s(),{connectOnClick:v,noPanClassName:y,rfId:S}=ma(Ps,da),{connectingFrom:k,connectingTo:E,clickConnecting:x,isPossibleEndHandle:M,connectionInProcess:T,clickConnectionInProcess:C,valid:_}=ma(((e,t,n)=>r=>{const{connectionClickStartHandle:i,connectionMode:o,connection:a}=r,{fromHandle:s,toHandle:c,isValid:u}=a,l=c?.nodeId===e&&c?.id===t&&c?.type===n;return{connectingFrom:s?.nodeId===e&&s?.id===t&&s?.type===n,connectingTo:l,clickConnecting:i?.nodeId===e&&i?.id===t&&i?.type===n,isPossibleEndHandle:o===Kr.Strict?s?.type!==n:e!==s?.nodeId||t!==s?.id,connectionInProcess:!!s,clickConnectionInProcess:!!i,valid:l&&u}})(w,p,e),da);w||m.getState().onError?.("010",Jr.error010());const P=e=>{const{defaultEdgeOptions:t,onConnect:n,hasDefaultEdges:r}=m.getState(),i={...t,...e};if(r){const{edges:e,setEdges:t}=m.getState();t(((e,t)=>{if(!e.source||!e.target)return Ti("006",Jr.error006()),t;let n;return n=ii(e)?{...e}:{...e,id:Zi(e)},((e,t)=>t.some((t=>!(t.source!==e.source||t.target!==e.target||t.sourceHandle!==e.sourceHandle&&(t.sourceHandle||e.sourceHandle)||t.targetHandle!==e.targetHandle&&(t.targetHandle||e.targetHandle)))))(n,t)?t:(null===n.sourceHandle&&delete n.sourceHandle,null===n.targetHandle&&delete n.targetHandle,t.concat(n))})(i,e))}n?.(i),c?.(i)},I=e=>{if(!w)return;const t=qi(e.nativeEvent);if(o&&(t&&0===e.button||!t)){const t=m.getState();Co.onPointerDown(e.nativeEvent,{autoPanOnConnect:t.autoPanOnConnect,connectionMode:t.connectionMode,connectionRadius:t.connectionRadius,domNode:t.domNode,nodeLookup:t.nodeLookup,lib:t.lib,isTarget:b,handleId:p,nodeId:w,flowId:t.rfId,panBy:t.panBy,cancelConnection:t.cancelConnection,onConnectStart:t.onConnectStart,onConnectEnd:t.onConnectEnd,updateConnection:t.updateConnection,onConnect:P,isValidConnection:n||t.isValidConnection,getTransform:()=>m.getState().transform,getFromHandle:()=>m.getState().connection.fromHandle,autoPanSpeed:t.autoPanSpeed})}t?h?.(e):f?.(e)};return(0,r.jsx)("div",{"data-handleid":p,"data-nodeid":w,"data-handlepos":t,"data-id":`${S}-${w}-${p}-${e}`,className:te(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",y,l,{source:!b,target:b,connectable:i,connectablestart:o,connectableend:a,clickconnecting:x,connectingfrom:k,connectingto:E,valid:_,connectionindicator:i&&(!T||M)&&(T||C?a:o)}]),onMouseDown:I,onTouchStart:I,onClick:v?t=>{const{onClickConnectStart:r,onClickConnectEnd:i,connectionClickStartHandle:a,connectionMode:s,isValidConnection:c,lib:u,rfId:l,nodeLookup:h,connection:f}=m.getState();if(!w||!a&&!o)return;if(!a)return r?.(t.nativeEvent,{nodeId:w,handleId:p,handleType:e}),void m.setState({connectionClickStartHandle:{nodeId:w,type:e,id:p}});const d=Bi(t.target),g=n||c,{connection:b,isValid:v}=Co.isValid(t.nativeEvent,{handle:{nodeId:w,id:p,type:e},connectionMode:s,fromNodeId:a.nodeId,fromHandleId:a.id||null,fromType:a.type,isValidConnection:g,flowId:l,doc:d,lib:u,nodeLookup:h});v&&b&&P(b);const y=structuredClone(f);delete y.inProgress,y.toPosition=y.toHandle?y.toHandle.position:null,i?.(t,y),m.setState({connectionClickStartHandle:null})}:void 0,ref:g,...d,children:u})}))),As={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},Os={input:function({data:e,isConnectable:t,sourcePosition:n=ti.Bottom}){return(0,r.jsxs)(r.Fragment,{children:[e?.label,(0,r.jsx)(Is,{type:"source",position:n,isConnectable:t})]})},default:function({data:e,isConnectable:t,targetPosition:n=ti.Top,sourcePosition:i=ti.Bottom}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(Is,{type:"target",position:n,isConnectable:t}),e?.label,(0,r.jsx)(Is,{type:"source",position:i,isConnectable:t})]})},output:function({data:e,isConnectable:t,targetPosition:n=ti.Top}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(Is,{type:"target",position:n,isConnectable:t}),e?.label]})},group:function(){return null}},js=e=>{const{width:t,height:n,x:r,y:i}=ci(e.nodeLookup,{filter:e=>!!e.selected});return{width:Mi(t)?t:null,height:Mi(n)?n:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${r}px,${i}px)`}};function $s({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const i=wa(),{width:o,height:a,transformString:c,userSelectionActive:u}=ma(js,da),l=Ms(),h=(0,s.useRef)(null);if((0,s.useEffect)((()=>{n||h.current?.focus({preventScroll:!0})}),[n]),Es({nodeRef:h}),u||!o||!a)return null;const f=e?t=>{const n=i.getState().nodes.filter((e=>e.selected));e(t,n)}:void 0;return(0,r.jsx)("div",{className:te(["react-flow__nodesselection","react-flow__container",t]),style:{transform:c},children:(0,r.jsx)("div",{ref:h,className:"react-flow__nodesselection-rect",onContextMenu:f,tabIndex:n?void 0:-1,onKeyDown:n?void 0:e=>{Object.prototype.hasOwnProperty.call(As,e.key)&&(e.preventDefault(),l({direction:As[e.key],factor:e.shiftKey?4:1}))},style:{width:o,height:a}})})}const Rs=typeof window<"u"?window:void 0,Ns=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function Ls({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:i,onPaneMouseLeave:o,onPaneContextMenu:a,onPaneScroll:c,paneClickDistance:u,deleteKeyCode:l,selectionKeyCode:h,selectionOnDrag:f,selectionMode:d,onSelectionStart:g,onSelectionEnd:p,multiSelectionKeyCode:b,panActivationKeyCode:m,zoomActivationKeyCode:w,elementsSelectable:v,zoomOnScroll:y,zoomOnPinch:S,panOnScroll:k,panOnScrollSpeed:E,panOnScrollMode:x,zoomOnDoubleClick:M,panOnDrag:T,defaultViewport:C,translateExtent:_,minZoom:P,maxZoom:I,preventScrolling:A,onSelectionContextMenu:O,noWheelClassName:j,noPanClassName:$,disableKeyboardA11y:R,onViewportChange:N,isControlledViewport:L}){const{nodesSelectionActive:D,userSelectionActive:F}=ma(Ns),B=Ha(h,{target:Rs}),z=Ha(m,{target:Rs}),U=z||T,q=z||k,H=f&&!0!==U,J=B||F||H;return function({deleteKeyCode:e,multiSelectionKeyCode:t}){const n=wa(),{deleteElements:r}=ls(),i=Ha(e,fs),o=Ha(t,{target:ds});(0,s.useEffect)((()=>{if(i){const{edges:e,nodes:t}=n.getState();r({nodes:t.filter(hs),edges:e.filter(hs)}),n.setState({nodesSelectionActive:!1})}}),[i]),(0,s.useEffect)((()=>{n.setState({multiSelectionActive:o})}),[o])}({deleteKeyCode:l,multiSelectionKeyCode:b}),(0,r.jsx)(bs,{onPaneContextMenu:a,elementsSelectable:v,zoomOnScroll:y,zoomOnPinch:S,panOnScroll:q,panOnScrollSpeed:E,panOnScrollMode:x,zoomOnDoubleClick:M,panOnDrag:!B&&U,defaultViewport:C,translateExtent:_,minZoom:P,maxZoom:I,zoomActivationKeyCode:w,preventScrolling:A,noWheelClassName:j,noPanClassName:$,onViewportChange:N,isControlledViewport:L,paneClickDistance:u,children:(0,r.jsxs)(Ss,{onSelectionStart:g,onSelectionEnd:p,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:i,onPaneMouseLeave:o,onPaneContextMenu:a,onPaneScroll:c,panOnDrag:U,isSelecting:!!J,selectionMode:d,selectionKeyPressed:B,selectionOnDrag:H,children:[e,D&&(0,r.jsx)($s,{onSelectionContextMenu:O,noPanClassName:$,disableKeyboardA11y:R})]})})}Ls.displayName="FlowRenderer";const Ds=(0,s.memo)(Ls),Fs=e=>e.updateNodeInternals;function Bs({id:e,onClick:t,onMouseEnter:n,onMouseMove:i,onMouseLeave:o,onContextMenu:a,onDoubleClick:c,nodesDraggable:u,elementsSelectable:l,nodesConnectable:h,nodesFocusable:f,resizeObserver:d,noDragClassName:g,noPanClassName:p,disableKeyboardA11y:b,rfId:m,nodeTypes:w,nodeClickDistance:v,onError:y}){const{node:S,internals:k,isParent:E}=ma((t=>{const n=t.nodeLookup.get(e),r=t.parentLookup.has(e);return{node:n,internals:n.internals,isParent:r}}),da);let x=S.type||"default",M=w?.[x]||Os[x];void 0===M&&(y?.("003",Jr.error003(x)),x="default",M=Os.default);const T=!!(S.draggable||u&&typeof S.draggable>"u"),C=!!(S.selectable||l&&typeof S.selectable>"u"),_=!!(S.connectable||h&&typeof S.connectable>"u"),P=!!(S.focusable||f&&typeof S.focusable>"u"),I=wa(),A=Ri(S),O=function({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){const i=wa(),o=(0,s.useRef)(null),a=(0,s.useRef)(null),c=(0,s.useRef)(e.sourcePosition),u=(0,s.useRef)(e.targetPosition),l=(0,s.useRef)(t),h=n&&!!e.internals.handleBounds;return(0,s.useEffect)((()=>{o.current&&!e.hidden&&(!h||a.current!==o.current)&&(a.current&&r?.unobserve(a.current),r?.observe(o.current),a.current=o.current)}),[h,e.hidden]),(0,s.useEffect)((()=>()=>{a.current&&(r?.unobserve(a.current),a.current=null)}),[]),(0,s.useEffect)((()=>{if(o.current){const n=l.current!==t,r=c.current!==e.sourcePosition,a=u.current!==e.targetPosition;(n||r||a)&&(l.current=t,c.current=e.sourcePosition,u.current=e.targetPosition,i.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:o.current,force:!0}]])))}}),[e.id,t,e.sourcePosition,e.targetPosition]),o}({node:S,nodeType:x,hasDimensions:A,resizeObserver:d}),j=Es({nodeRef:O,disabled:S.hidden||!T,noDragClassName:g,handleSelector:S.dragHandle,nodeId:e,isSelectable:C,nodeClickDistance:v}),$=Ms();if(S.hidden)return null;const R=$i(S),N=function(e){return void 0===e.internals.handleBounds?{width:e.width??e.initialWidth??e.style?.width,height:e.height??e.initialHeight??e.style?.height}:{width:e.width??e.style?.width,height:e.height??e.style?.height}}(S),L=C||T||t||n||i||o,D=n?e=>n(e,{...k.userNode}):void 0,F=i?e=>i(e,{...k.userNode}):void 0,B=o?e=>o(e,{...k.userNode}):void 0,z=a?e=>a(e,{...k.userNode}):void 0,U=c?e=>c(e,{...k.userNode}):void 0;return(0,r.jsx)("div",{className:te(["react-flow__node",`react-flow__node-${x}`,{[p]:T},S.className,{selected:S.selected,selectable:C,parent:E,draggable:T,dragging:j}]),ref:O,style:{zIndex:k.z,transform:`translate(${k.positionAbsolute.x}px,${k.positionAbsolute.y}px)`,pointerEvents:L?"all":"none",visibility:A?"visible":"hidden",...S.style,...N},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:D,onMouseMove:F,onMouseLeave:B,onContextMenu:z,onClick:n=>{const{selectNodesOnDrag:r,nodeDragThreshold:i}=I.getState();C&&(!r||!T||i>0)&&ks({id:e,store:I,nodeRef:O}),t&&t(n,{...k.userNode})},onDoubleClick:U,onKeyDown:P?t=>{if(!Ui(t.nativeEvent)&&!b)if(Vr.includes(t.key)&&C){const n="Escape"===t.key;ks({id:e,store:I,unselect:n,nodeRef:O})}else T&&S.selected&&Object.prototype.hasOwnProperty.call(As,t.key)&&(t.preventDefault(),I.setState({ariaLiveMessage:`Moved selected node ${t.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~k.positionAbsolute.x}, y: ${~~k.positionAbsolute.y}`}),$({direction:As[t.key],factor:t.shiftKey?4:1}))}:void 0,tabIndex:P?0:void 0,role:P?"button":void 0,"aria-describedby":b?void 0:`${Sa}-${m}`,"aria-label":S.ariaLabel,children:(0,r.jsx)(Cs,{value:e,children:(0,r.jsx)(M,{id:e,data:S.data,type:x,positionAbsoluteX:k.positionAbsolute.x,positionAbsoluteY:k.positionAbsolute.y,selected:S.selected??!1,selectable:C,draggable:T,deletable:S.deletable??!0,isConnectable:_,sourcePosition:S.sourcePosition,targetPosition:S.targetPosition,dragging:j,dragHandle:S.dragHandle,zIndex:k.z,parentId:S.parentId,...R})})})}const zs=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function Us(e){const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:i,elementsSelectable:o,onError:a}=ma(zs,da),c=function(e){return ma((0,s.useCallback)((e=>t=>e?ui(t.nodeLookup,{x:0,y:0,width:t.width,height:t.height},t.transform,!0).map((e=>e.id)):Array.from(t.nodeLookup.keys()))(e),[e]),da)}(e.onlyRenderVisibleElements),u=function(){const e=ma(Fs),[t]=(0,s.useState)((()=>typeof ResizeObserver>"u"?null:new ResizeObserver((t=>{const n=new Map;t.forEach((e=>{const t=e.target.getAttribute("data-id");n.set(t,{id:t,nodeElement:e.target,force:!0})})),e(n)}))));return(0,s.useEffect)((()=>()=>{t?.disconnect()}),[t]),t}();return(0,r.jsx)("div",{className:"react-flow__nodes",style:gs,children:c.map((s=>(0,r.jsx)(Bs,{id:s,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:u,nodesDraggable:t,nodesConnectable:n,nodesFocusable:i,elementsSelectable:o,nodeClickDistance:e.nodeClickDistance,onError:a},s)))})}Us.displayName="NodeRenderer";const qs=(0,s.memo)(Us),Hs={[ei.Arrow]:({color:e="none",strokeWidth:t=1})=>(0,r.jsx)("polyline",{style:{stroke:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",fill:"none",points:"-5,-4 0,0 -5,4"}),[ei.ArrowClosed]:({color:e="none",strokeWidth:t=1})=>(0,r.jsx)("polyline",{style:{stroke:e,fill:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},Js=({id:e,type:t,color:n,width:i=12.5,height:o=12.5,markerUnits:a="strokeWidth",strokeWidth:c,orient:u="auto-start-reverse"})=>{const l=function(e){const t=wa();return(0,s.useMemo)((()=>Object.prototype.hasOwnProperty.call(Hs,e)?Hs[e]:(t.getState().onError?.("009",Jr.error009(e)),null)),[e])}(t);return l?(0,r.jsx)("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${i}`,markerHeight:`${o}`,viewBox:"-10 -10 20 20",markerUnits:a,orient:u,refX:"0",refY:"0",children:(0,r.jsx)(l,{color:n,strokeWidth:c})}):null},Gs=({defaultColor:e,rfId:t})=>{const n=ma((e=>e.edges)),i=ma((e=>e.defaultEdgeOptions)),o=(0,s.useMemo)((()=>function(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:i}){const o=new Set;return e.reduce(((e,a)=>([a.markerStart||r,a.markerEnd||i].forEach((r=>{if(r&&"object"==typeof r){const i=uo(r,t);o.has(i)||(e.push({id:i,color:r.color||n,...r}),o.add(i))}})),e)),[]).sort(((e,t)=>e.id.localeCompare(t.id)))}(n,{id:t,defaultColor:e,defaultMarkerStart:i?.markerStart,defaultMarkerEnd:i?.markerEnd})),[n,i,t,e]);return o.length?(0,r.jsx)("svg",{className:"react-flow__marker",children:(0,r.jsx)("defs",{children:o.map((e=>(0,r.jsx)(Js,{id:e.id,type:e.type,color:e.color,width:e.width,height:e.height,markerUnits:e.markerUnits,strokeWidth:e.strokeWidth,orient:e.orient},e.id)))})}):null};Gs.displayName="MarkerDefinitions";var Vs=(0,s.memo)(Gs);function Ks({x:e,y:t,label:n,labelStyle:i,labelShowBg:o=!0,labelBgStyle:a,labelBgPadding:c=[2,4],labelBgBorderRadius:u=2,children:l,className:h,...f}){const[d,g]=(0,s.useState)({x:1,y:0,width:0,height:0}),p=te(["react-flow__edge-textwrapper",h]),b=(0,s.useRef)(null);return(0,s.useEffect)((()=>{if(b.current){const e=b.current.getBBox();g({x:e.x,y:e.y,width:e.width,height:e.height})}}),[n]),n?(0,r.jsxs)("g",{transform:`translate(${e-d.width/2} ${t-d.height/2})`,className:p,visibility:d.width?"visible":"hidden",...f,children:[o&&(0,r.jsx)("rect",{width:d.width+2*c[0],x:-c[0],y:-c[1],height:d.height+2*c[1],className:"react-flow__edge-textbg",style:a,rx:u,ry:u}),(0,r.jsx)("text",{className:"react-flow__edge-text",y:d.height/2,dy:"0.3em",ref:b,style:i,children:n}),l]}):null}Ks.displayName="EdgeText";const Ws=(0,s.memo)(Ks);function Xs({path:e,labelX:t,labelY:n,label:i,labelStyle:o,labelShowBg:a,labelBgStyle:s,labelBgPadding:c,labelBgBorderRadius:u,interactionWidth:l=20,...h}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{...h,d:e,fill:"none",className:te(["react-flow__edge-path",h.className])}),l&&(0,r.jsx)("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:l,className:"react-flow__edge-interaction"}),i&&Mi(t)&&Mi(n)?(0,r.jsx)(Ws,{x:t,y:n,label:i,labelStyle:o,labelShowBg:a,labelBgStyle:s,labelBgPadding:c,labelBgBorderRadius:u}):null]})}function Ys({pos:e,x1:t,y1:n,x2:r,y2:i}){return e===ti.Left||e===ti.Right?[.5*(t+r),n]:[t,.5*(n+i)]}function Qs({sourceX:e,sourceY:t,sourcePosition:n=ti.Bottom,targetX:r,targetY:i,targetPosition:o=ti.Top}){const[a,s]=Ys({pos:n,x1:e,y1:t,x2:r,y2:i}),[c,u]=Ys({pos:o,x1:r,y1:i,x2:e,y2:t}),[l,h,f,d]=Gi({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:a,sourceControlY:s,targetControlX:c,targetControlY:u});return[`M${e},${t} C${a},${s} ${c},${u} ${r},${i}`,l,h,f,d]}function Zs(e){return(0,s.memo)((({id:t,sourceX:n,sourceY:i,targetX:o,targetY:a,sourcePosition:s=ti.Bottom,targetPosition:c=ti.Top,label:u,labelStyle:l,labelShowBg:h,labelBgStyle:f,labelBgPadding:d,labelBgBorderRadius:g,style:p,markerEnd:b,markerStart:m,interactionWidth:w})=>{const[v,y,S]=Qs({sourceX:n,sourceY:i,sourcePosition:s,targetX:o,targetY:a,targetPosition:c}),k=e.isInternal?void 0:t;return(0,r.jsx)(Xs,{id:k,path:v,labelX:y,labelY:S,label:u,labelStyle:l,labelShowBg:h,labelBgStyle:f,labelBgPadding:d,labelBgBorderRadius:g,style:p,markerEnd:b,markerStart:m,interactionWidth:w})}))}const ec=Zs({isInternal:!1}),tc=Zs({isInternal:!0});function nc(e){return(0,s.memo)((({id:t,sourceX:n,sourceY:i,targetX:o,targetY:a,label:s,labelStyle:c,labelShowBg:u,labelBgStyle:l,labelBgPadding:h,labelBgBorderRadius:f,style:d,sourcePosition:g=ti.Bottom,targetPosition:p=ti.Top,markerEnd:b,markerStart:m,pathOptions:w,interactionWidth:v})=>{const[y,S,k]=io({sourceX:n,sourceY:i,sourcePosition:g,targetX:o,targetY:a,targetPosition:p,borderRadius:w?.borderRadius,offset:w?.offset}),E=e.isInternal?void 0:t;return(0,r.jsx)(Xs,{id:E,path:y,labelX:S,labelY:k,label:s,labelStyle:c,labelShowBg:u,labelBgStyle:l,labelBgPadding:h,labelBgBorderRadius:f,style:d,markerEnd:b,markerStart:m,interactionWidth:v})}))}ec.displayName="SimpleBezierEdge",tc.displayName="SimpleBezierEdgeInternal";const rc=nc({isInternal:!1}),ic=nc({isInternal:!0});function oc(e){return(0,s.memo)((({id:t,...n})=>{const i=e.isInternal?void 0:t;return(0,r.jsx)(rc,{...n,id:i,pathOptions:(0,s.useMemo)((()=>({borderRadius:0,offset:n.pathOptions?.offset})),[n.pathOptions?.offset])})}))}rc.displayName="SmoothStepEdge",ic.displayName="SmoothStepEdgeInternal";const ac=oc({isInternal:!1}),sc=oc({isInternal:!0});function cc(e){return(0,s.memo)((({id:t,sourceX:n,sourceY:i,targetX:o,targetY:a,label:s,labelStyle:c,labelShowBg:u,labelBgStyle:l,labelBgPadding:h,labelBgBorderRadius:f,style:d,markerEnd:g,markerStart:p,interactionWidth:b})=>{const[m,w,v]=eo({sourceX:n,sourceY:i,targetX:o,targetY:a}),y=e.isInternal?void 0:t;return(0,r.jsx)(Xs,{id:y,path:m,labelX:w,labelY:v,label:s,labelStyle:c,labelShowBg:u,labelBgStyle:l,labelBgPadding:h,labelBgBorderRadius:f,style:d,markerEnd:g,markerStart:p,interactionWidth:b})}))}ac.displayName="StepEdge",sc.displayName="StepEdgeInternal";const uc=cc({isInternal:!1}),lc=cc({isInternal:!0});function hc(e){return(0,s.memo)((({id:t,sourceX:n,sourceY:i,targetX:o,targetY:a,sourcePosition:s=ti.Bottom,targetPosition:c=ti.Top,label:u,labelStyle:l,labelShowBg:h,labelBgStyle:f,labelBgPadding:d,labelBgBorderRadius:g,style:p,markerEnd:b,markerStart:m,pathOptions:w,interactionWidth:v})=>{const[y,S,k]=Wi({sourceX:n,sourceY:i,sourcePosition:s,targetX:o,targetY:a,targetPosition:c,curvature:w?.curvature}),E=e.isInternal?void 0:t;return(0,r.jsx)(Xs,{id:E,path:y,labelX:S,labelY:k,label:u,labelStyle:l,labelShowBg:h,labelBgStyle:f,labelBgPadding:d,labelBgBorderRadius:g,style:p,markerEnd:b,markerStart:m,interactionWidth:v})}))}uc.displayName="StraightEdge",lc.displayName="StraightEdgeInternal";const fc=hc({isInternal:!1}),dc=hc({isInternal:!0});fc.displayName="BezierEdge",dc.displayName="BezierEdgeInternal";const gc={default:dc,straight:lc,step:sc,smoothstep:ic,simplebezier:tc},pc={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},bc=(e,t,n)=>n===ti.Left?e-t:n===ti.Right?e+t:e,mc=(e,t,n)=>n===ti.Top?e-t:n===ti.Bottom?e+t:e,wc="react-flow__edgeupdater";function vc({position:e,centerX:t,centerY:n,radius:i=10,onMouseDown:o,onMouseEnter:a,onMouseOut:s,type:c}){return(0,r.jsx)("circle",{onMouseDown:o,onMouseEnter:a,onMouseOut:s,className:te([wc,`${wc}-${c}`]),cx:bc(t,i,e),cy:mc(n,i,e),r:i,stroke:"transparent",fill:"transparent"})}function yc({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:i,sourceY:o,targetX:a,targetY:s,sourcePosition:c,targetPosition:u,onReconnect:l,onReconnectStart:h,onReconnectEnd:f,setReconnecting:d,setUpdateHover:g}){const p=wa(),b=(e,t)=>{if(0!==e.button)return;const{autoPanOnConnect:r,domNode:i,isValidConnection:o,connectionMode:a,connectionRadius:s,lib:c,onConnectStart:u,onConnectEnd:g,cancelConnection:b,nodeLookup:m,rfId:w,panBy:v,updateConnection:y}=p.getState(),S="target"===t.type;d(!0),h?.(e,n,t.type),Co.onPointerDown(e.nativeEvent,{autoPanOnConnect:r,connectionMode:a,connectionRadius:s,domNode:i,handleId:t.id,nodeId:t.nodeId,nodeLookup:m,isTarget:S,edgeUpdaterType:t.type,lib:c,flowId:w,cancelConnection:b,panBy:v,isValidConnection:o,onConnect:e=>l?.(n,e),onConnectStart:u,onConnectEnd:g,onReconnectEnd:(e,r)=>{d(!1),f?.(e,n,t.type,r)},updateConnection:y,getTransform:()=>p.getState().transform,getFromHandle:()=>p.getState().connection.fromHandle})},m=()=>g(!0),w=()=>g(!1);return(0,r.jsxs)(r.Fragment,{children:[(!0===e||"source"===e)&&(0,r.jsx)(vc,{position:c,centerX:i,centerY:o,radius:t,onMouseDown:e=>b(e,{nodeId:n.target,id:n.targetHandle??null,type:"target"}),onMouseEnter:m,onMouseOut:w,type:"source"}),(!0===e||"target"===e)&&(0,r.jsx)(vc,{position:u,centerX:a,centerY:s,radius:t,onMouseDown:e=>b(e,{nodeId:n.source,id:n.sourceHandle??null,type:"source"}),onMouseEnter:m,onMouseOut:w,type:"target"})]})}function Sc({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:i,onClick:o,onDoubleClick:a,onContextMenu:c,onMouseEnter:u,onMouseMove:l,onMouseLeave:h,reconnectRadius:f,onReconnect:d,onReconnectStart:g,onReconnectEnd:p,rfId:b,edgeTypes:m,noPanClassName:w,onError:v,disableKeyboardA11y:y}){let S=ma((t=>t.edgeLookup.get(e)));const k=ma((e=>e.defaultEdgeOptions));S=k?{...k,...S}:S;let E=S.type||"default",x=m?.[E]||gc[E];void 0===x&&(v?.("011",Jr.error011(E)),E="default",x=gc.default);const M=!!(S.focusable||t&&typeof S.focusable>"u"),T=typeof d<"u"&&(S.reconnectable||n&&typeof S.reconnectable>"u"),C=!!(S.selectable||i&&typeof S.selectable>"u"),_=(0,s.useRef)(null),[P,I]=(0,s.useState)(!1),[A,O]=(0,s.useState)(!1),j=wa(),{zIndex:$,sourceX:R,sourceY:N,targetX:L,targetY:D,sourcePosition:F,targetPosition:B}=ma((0,s.useCallback)((t=>{const n=t.nodeLookup.get(S.source),r=t.nodeLookup.get(S.target);if(!n||!r)return{zIndex:S.zIndex,...pc};const i=function(e){const{sourceNode:t,targetNode:n}=e;if(!oo(t)||!oo(n))return null;const r=t.internals.handleBounds||ao(t.handles),i=n.internals.handleBounds||ao(n.handles),o=co(r?.source??[],e.sourceHandle),a=co(e.connectionMode===Kr.Strict?i?.target??[]:(i?.target??[]).concat(i?.source??[]),e.targetHandle);if(!o||!a)return e.onError?.("008",Jr.error008(o?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const s=o?.position||ti.Bottom,c=a?.position||ti.Top,u=so(t,o,s),l=so(n,a,c);return{sourceX:u.x,sourceY:u.y,targetX:l.x,targetY:l.y,sourcePosition:s,targetPosition:c}}({id:e,sourceNode:n,targetNode:r,sourceHandle:S.sourceHandle||null,targetHandle:S.targetHandle||null,connectionMode:t.connectionMode,onError:v});return{zIndex:Yi({selected:S.selected,zIndex:S.zIndex,sourceNode:n,targetNode:r,elevateOnSelect:t.elevateEdgesOnSelect}),...i||pc}}),[S.source,S.target,S.sourceHandle,S.targetHandle,S.selected,S.zIndex]),da),z=(0,s.useMemo)((()=>S.markerStart?`url('#${uo(S.markerStart,b)}')`:void 0),[S.markerStart,b]),U=(0,s.useMemo)((()=>S.markerEnd?`url('#${uo(S.markerEnd,b)}')`:void 0),[S.markerEnd,b]);if(S.hidden||null===R||null===N||null===L||null===D)return null;const q=a?e=>{a(e,{...S})}:void 0,H=c?e=>{c(e,{...S})}:void 0,J=u?e=>{u(e,{...S})}:void 0,G=l?e=>{l(e,{...S})}:void 0,V=h?e=>{h(e,{...S})}:void 0;return(0,r.jsx)("svg",{style:{zIndex:$},children:(0,r.jsxs)("g",{className:te(["react-flow__edge",`react-flow__edge-${E}`,S.className,w,{selected:S.selected,animated:S.animated,inactive:!C&&!o,updating:P,selectable:C}]),onClick:t=>{const{addSelectedEdges:n,unselectNodesAndEdges:r,multiSelectionActive:i}=j.getState();C&&(j.setState({nodesSelectionActive:!1}),S.selected&&i?(r({nodes:[],edges:[S]}),_.current?.blur()):n([e])),o&&o(t,S)},onDoubleClick:q,onContextMenu:H,onMouseEnter:J,onMouseMove:G,onMouseLeave:V,onKeyDown:M?t=>{if(!y&&Vr.includes(t.key)&&C){const{unselectNodesAndEdges:n,addSelectedEdges:r}=j.getState();"Escape"===t.key?(_.current?.blur(),n({edges:[S]})):r([e])}}:void 0,tabIndex:M?0:void 0,role:M?"button":"img","data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":null===S.ariaLabel?void 0:S.ariaLabel||`Edge from ${S.source} to ${S.target}`,"aria-describedby":M?`${ka}-${b}`:void 0,ref:_,children:[!A&&(0,r.jsx)(x,{id:e,source:S.source,target:S.target,type:S.type,selected:S.selected,animated:S.animated,selectable:C,deletable:S.deletable??!0,label:S.label,labelStyle:S.labelStyle,labelShowBg:S.labelShowBg,labelBgStyle:S.labelBgStyle,labelBgPadding:S.labelBgPadding,labelBgBorderRadius:S.labelBgBorderRadius,sourceX:R,sourceY:N,targetX:L,targetY:D,sourcePosition:F,targetPosition:B,data:S.data,style:S.style,sourceHandleId:S.sourceHandle,targetHandleId:S.targetHandle,markerStart:z,markerEnd:U,pathOptions:"pathOptions"in S?S.pathOptions:void 0,interactionWidth:S.interactionWidth}),T&&(0,r.jsx)(yc,{edge:S,isReconnectable:T,reconnectRadius:f,onReconnect:d,onReconnectStart:g,onReconnectEnd:p,sourceX:R,sourceY:N,targetX:L,targetY:D,sourcePosition:F,targetPosition:B,setUpdateHover:I,setReconnecting:O})]})})}const kc=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function Ec({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:i,noPanClassName:o,onReconnect:a,onEdgeContextMenu:c,onEdgeMouseEnter:u,onEdgeMouseMove:l,onEdgeMouseLeave:h,onEdgeClick:f,reconnectRadius:d,onEdgeDoubleClick:g,onReconnectStart:p,onReconnectEnd:b,disableKeyboardA11y:m}){const{edgesFocusable:w,edgesReconnectable:v,elementsSelectable:y,onError:S}=ma(kc,da),k=function(e){return ma((0,s.useCallback)((t=>{if(!e)return t.edges.map((e=>e.id));const n=[];if(t.width&&t.height)for(const e of t.edges){const r=t.nodeLookup.get(e.source),i=t.nodeLookup.get(e.target);r&&i&&Qi({sourceNode:r,targetNode:i,width:t.width,height:t.height,transform:t.transform})&&n.push(e.id)}return n}),[e]),da)}(t);return(0,r.jsxs)("div",{className:"react-flow__edges",children:[(0,r.jsx)(Vs,{defaultColor:e,rfId:n}),k.map((e=>(0,r.jsx)(Sc,{id:e,edgesFocusable:w,edgesReconnectable:v,elementsSelectable:y,noPanClassName:o,onReconnect:a,onContextMenu:c,onMouseEnter:u,onMouseMove:l,onMouseLeave:h,onClick:f,reconnectRadius:d,onDoubleClick:g,onReconnectStart:p,onReconnectEnd:b,rfId:n,onError:S,edgeTypes:i,disableKeyboardA11y:m},e)))]})}Ec.displayName="EdgeRenderer";const xc=(0,s.memo)(Ec),Mc=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function Tc({children:e}){const t=ma(Mc);return(0,r.jsx)("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:t},children:e})}const Cc=e=>e.panZoom?.syncViewport;function _c(e){return e.connection.inProgress?{...e.connection,to:_i(e.connection.to,e.transform)}:{...e.connection}}const Pc=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function Ic({containerStyle:e,style:t,type:n,component:i}){const{nodesConnectable:o,width:a,height:s,isValid:c,inProgress:u}=ma(Pc,da);return a&&o&&u?(0,r.jsx)("svg",{style:e,width:a,height:s,className:"react-flow__connectionline react-flow__container",children:(0,r.jsx)("g",{className:te(["react-flow__connection",ri(c)]),children:(0,r.jsx)(Ac,{style:t,type:n,CustomComponent:i,isValid:c})})}):null}const Ac=({style:e,type:t=Zr.Bezier,CustomComponent:n,isValid:i})=>{const{inProgress:o,from:a,fromNode:s,fromHandle:c,fromPosition:u,to:l,toNode:h,toHandle:f,toPosition:d}=ma(_c,da);if(!o)return;if(n)return(0,r.jsx)(n,{connectionLineType:t,connectionLineStyle:e,fromNode:s,fromHandle:c,fromX:a.x,fromY:a.y,toX:l.x,toY:l.y,fromPosition:u,toPosition:d,connectionStatus:ri(i),toNode:h,toHandle:f});let g="";const p={sourceX:a.x,sourceY:a.y,sourcePosition:u,targetX:l.x,targetY:l.y,targetPosition:d};switch(t){case Zr.Bezier:[g]=Wi(p);break;case Zr.SimpleBezier:[g]=Qs(p);break;case Zr.Step:[g]=io({...p,borderRadius:0});break;case Zr.SmoothStep:[g]=io(p);break;default:[g]=eo(p)}return(0,r.jsx)("path",{d:g,fill:"none",className:"react-flow__connection-path",style:e})};Ac.displayName="ConnectionLine";const Oc={};function jc(e=Oc){const t=(0,s.useRef)(e),n=wa();(0,s.useEffect)((()=>{if("development"===ee.env.NODE_ENV){const r=new Set([...Object.keys(t.current),...Object.keys(e)]);for(const i of r)if(t.current[i]!==e[i]){n.getState().onError?.("002",Jr.error002());break}t.current=e}}),[e])}function $c({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:i,onEdgeClick:o,onNodeDoubleClick:a,onEdgeDoubleClick:c,onNodeMouseEnter:u,onNodeMouseMove:l,onNodeMouseLeave:h,onNodeContextMenu:f,onSelectionContextMenu:d,onSelectionStart:g,onSelectionEnd:p,connectionLineType:b,connectionLineStyle:m,connectionLineComponent:w,connectionLineContainerStyle:v,selectionKeyCode:y,selectionOnDrag:S,selectionMode:k,multiSelectionKeyCode:E,panActivationKeyCode:x,zoomActivationKeyCode:M,deleteKeyCode:T,onlyRenderVisibleElements:C,elementsSelectable:_,defaultViewport:P,translateExtent:I,minZoom:A,maxZoom:O,preventScrolling:j,defaultMarkerColor:$,zoomOnScroll:R,zoomOnPinch:N,panOnScroll:L,panOnScrollSpeed:D,panOnScrollMode:F,zoomOnDoubleClick:B,panOnDrag:z,onPaneClick:U,onPaneMouseEnter:q,onPaneMouseMove:H,onPaneMouseLeave:J,onPaneScroll:G,onPaneContextMenu:V,paneClickDistance:K,nodeClickDistance:W,onEdgeContextMenu:X,onEdgeMouseEnter:Y,onEdgeMouseMove:Q,onEdgeMouseLeave:Z,reconnectRadius:te,onReconnect:ne,onReconnectStart:re,onReconnectEnd:ie,noDragClassName:oe,noWheelClassName:ae,noPanClassName:se,disableKeyboardA11y:ce,nodeExtent:ue,rfId:le,viewport:he,onViewportChange:fe}){return jc(e),jc(t),function(){const e=wa(),t=(0,s.useRef)(!1);(0,s.useEffect)((()=>{if("development"===ee.env.NODE_ENV&&!t.current){const n=document.querySelector(".react-flow__pane");n&&"1"!==window.getComputedStyle(n).zIndex&&e.getState().onError?.("013",Jr.error013("react")),t.current=!0}}),[])}(),function(e){const t=ls(),n=(0,s.useRef)(!1);(0,s.useEffect)((()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout((()=>e(t)),1),n.current=!0)}),[e,t.viewportInitialized])}(n),function(e){const t=ma(Cc),n=wa();(0,s.useEffect)((()=>{e&&(t?.(e),n.setState({transform:[e.x,e.y,e.zoom]}))}),[e,t])}(he),(0,r.jsx)(Ds,{onPaneClick:U,onPaneMouseEnter:q,onPaneMouseMove:H,onPaneMouseLeave:J,onPaneContextMenu:V,onPaneScroll:G,paneClickDistance:K,deleteKeyCode:T,selectionKeyCode:y,selectionOnDrag:S,selectionMode:k,onSelectionStart:g,onSelectionEnd:p,multiSelectionKeyCode:E,panActivationKeyCode:x,zoomActivationKeyCode:M,elementsSelectable:_,zoomOnScroll:R,zoomOnPinch:N,zoomOnDoubleClick:B,panOnScroll:L,panOnScrollSpeed:D,panOnScrollMode:F,panOnDrag:z,defaultViewport:P,translateExtent:I,minZoom:A,maxZoom:O,onSelectionContextMenu:d,preventScrolling:j,noDragClassName:oe,noWheelClassName:ae,noPanClassName:se,disableKeyboardA11y:ce,onViewportChange:fe,isControlledViewport:!!he,children:(0,r.jsxs)(Tc,{children:[(0,r.jsx)(xc,{edgeTypes:t,onEdgeClick:o,onEdgeDoubleClick:c,onReconnect:ne,onReconnectStart:re,onReconnectEnd:ie,onlyRenderVisibleElements:C,onEdgeContextMenu:X,onEdgeMouseEnter:Y,onEdgeMouseMove:Q,onEdgeMouseLeave:Z,reconnectRadius:te,defaultMarkerColor:$,noPanClassName:se,disableKeyboardA11y:ce,rfId:le}),(0,r.jsx)(Ic,{style:m,type:b,component:w,containerStyle:v}),(0,r.jsx)("div",{className:"react-flow__edgelabel-renderer"}),(0,r.jsx)(qs,{nodeTypes:e,onNodeClick:i,onNodeDoubleClick:a,onNodeMouseEnter:u,onNodeMouseMove:l,onNodeMouseLeave:h,onNodeContextMenu:f,nodeClickDistance:W,onlyRenderVisibleElements:C,noPanClassName:se,noDragClassName:oe,disableKeyboardA11y:ce,nodeExtent:ue,rfId:le}),(0,r.jsx)("div",{className:"react-flow__viewport-portal"})]})})}$c.displayName="GraphView";const Rc=(0,s.memo)($c),Nc=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:o,fitView:a,nodeOrigin:s,nodeExtent:c}={})=>{const u=new Map,l=new Map,h=new Map,f=new Map,d=r??t??[],g=n??e??[],p=s??[0,0],b=c??Gr;vo(h,f,d),go(g,u,l,{nodeOrigin:p,nodeExtent:b,elevateNodesOnSelect:!1});let m=[0,0,1];if(a&&i&&o){const e=ci(u,{filter:e=>!(!e.width&&!e.initialWidth||!e.height&&!e.initialHeight)}),{x:t,y:n,zoom:r}=Ai(e,i,o,.5,2,.1);m=[t,n,r]}return{rfId:"1",width:0,height:0,transform:m,nodes:g,nodeLookup:u,parentLookup:l,edges:d,edgeLookup:f,connectionLookup:h,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:void 0!==n,hasDefaultEdges:void 0!==r,panZoom:null,minZoom:.5,maxZoom:2,translateExtent:Gr,nodeExtent:b,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:Kr.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:p,nodeDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!1,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:a??!1,fitViewOptions:void 0,fitViewResolver:null,connection:{...Qr},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanSpeed:15,connectionRadius:20,onError:Ti,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1}},Lc=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:o,fitView:a,nodeOrigin:s,nodeExtent:c})=>((e,t)=>e?fa(e,t):fa)(((u,l)=>{async function h(){const{nodeLookup:e,panZoom:t,fitViewOptions:n,fitViewResolver:r,width:i,height:o,minZoom:a,maxZoom:s}=l();t&&(await async function({nodes:e,width:t,height:n,panZoom:r,minZoom:i,maxZoom:o},a){if(0===e.size)return Promise.resolve(!0);const s=function(e,t){const n=new Map,r=t?.nodes?new Set(t.nodes.map((e=>e.id))):null;return e.forEach((e=>{e.measured.width&&e.measured.height&&(t?.includeHiddenNodes||!e.hidden)&&(!r||r.has(e.id))&&n.set(e.id,e)})),n}(e,a),c=ci(s),u=Ai(c,t,n,a?.minZoom??i,a?.maxZoom??o,a?.padding??.1);return await r.setViewport(u,{duration:a?.duration}),Promise.resolve(!0)}({nodes:e,width:i,height:o,panZoom:t,minZoom:a,maxZoom:s},n),r?.resolve(!0),u({fitViewResolver:null}))}return{...Nc({nodes:e,edges:t,width:i,height:o,fitView:a,nodeOrigin:s,nodeExtent:c,defaultNodes:n,defaultEdges:r}),setNodes:e=>{const{nodeLookup:t,parentLookup:n,nodeOrigin:r,elevateNodesOnSelect:i,fitViewQueued:o}=l(),a=go(e,t,n,{nodeOrigin:r,nodeExtent:c,elevateNodesOnSelect:i,checkEquality:!0});o&&a?(h(),u({nodes:e,fitViewQueued:!1,fitViewOptions:void 0})):u({nodes:e})},setEdges:e=>{const{connectionLookup:t,edgeLookup:n}=l();vo(t,n,e),u({edges:e})},setDefaultNodesAndEdges:(e,t)=>{if(e){const{setNodes:t}=l();t(e),u({hasDefaultNodes:!0})}if(t){const{setEdges:e}=l();e(t),u({hasDefaultEdges:!0})}},updateNodeInternals:e=>{const{triggerNodeChanges:t,nodeLookup:n,parentLookup:r,domNode:i,nodeOrigin:o,nodeExtent:a,debug:s,fitViewQueued:c}=l(),{changes:f,updatedInternals:d}=function(e,t,n,r,i,o){const a=r?.querySelector(".xyflow__viewport");let s=!1;if(!a)return{changes:[],updatedInternals:s};const c=[],u=window.getComputedStyle(a),{m22:l}=new window.DOMMatrixReadOnly(u.transform),h=[];for(const r of e.values()){const e=t.get(r.id);if(!e)continue;if(e.hidden){t.set(e.id,{...e,internals:{...e.internals,handleBounds:void 0}}),s=!0;continue}const a=Fi(r.nodeElement),u=e.measured.width!==a.width||e.measured.height!==a.height;if(a.width&&a.height&&(u||!e.internals.handleBounds||r.force)){const f=r.nodeElement.getBoundingClientRect(),d=ji(e.extent)?e.extent:o;let{positionAbsolute:g}=e.internals;e.parentId&&"parent"===e.extent?g=gi(g,a,t.get(e.parentId)):d&&(g=di(g,d,a));const p={...e,measured:a,internals:{...e.internals,positionAbsolute:g,handleBounds:{source:Ji("source",r.nodeElement,f,l,e.id),target:Ji("target",r.nodeElement,f,l,e.id)}}};t.set(e.id,p),e.parentId&&po(p,t,n,{nodeOrigin:i}),s=!0,u&&(c.push({id:e.id,type:"dimensions",dimensions:a}),e.expandParent&&e.parentId&&h.push({id:e.id,parentId:e.parentId,rect:yi(p,i)}))}}if(h.length>0){const e=mo(h,t,n,i);c.push(...e)}return{changes:c,updatedInternals:s}}(e,n,r,i,o,a);d&&(function(e,t,n){const r=fo(lo,n);for(const n of e.values())if(n.parentId)po(n,e,t,r);else{const e=ai(n,r.nodeOrigin),t=ji(n.extent)?n.extent:r.nodeExtent,i=di(e,t,$i(n));n.internals.positionAbsolute=i}}(n,r,{nodeOrigin:o,nodeExtent:a}),c?(h(),u({fitViewQueued:!1,fitViewOptions:void 0})):u({}),f?.length>0&&(s&&console.log("React Flow: trigger node changes",f),t?.(f)))},updateNodePositions:(e,t=!1)=>{const n=[],r=[],{nodeLookup:i,triggerNodeChanges:o}=l();for(const[o,a]of e){const e=i.get(o),s=!!(e?.expandParent&&e?.parentId&&a?.position),c={id:o,type:"position",position:s?{x:Math.max(0,a.position.x),y:Math.max(0,a.position.y)}:a.position,dragging:t};s&&e.parentId&&n.push({id:o,parentId:e.parentId,rect:{...a.internals.positionAbsolute,width:a.measured.width??0,height:a.measured.height??0}}),r.push(c)}if(n.length>0){const{parentLookup:e,nodeOrigin:t}=l(),o=mo(n,i,e,t);r.push(...o)}o(r)},triggerNodeChanges:e=>{const{onNodesChange:t,setNodes:n,nodes:r,hasDefaultNodes:i,debug:o}=l();e?.length&&(i&&n(Xa(e,r)),o&&console.log("React Flow: trigger node changes",e),t?.(e))},triggerEdgeChanges:e=>{const{onEdgesChange:t,setEdges:n,edges:r,hasDefaultEdges:i,debug:o}=l();e?.length&&(i&&n(Ya(e,r)),o&&console.log("React Flow: trigger edge changes",e),t?.(e))},addSelectedNodes:e=>{const{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:o}=l();t?i(e.map((e=>Qa(e,!0)))):(i(Za(r,new Set([...e]),!0)),o(Za(n)))},addSelectedEdges:e=>{const{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:o}=l();t?o(e.map((e=>Qa(e,!0)))):(o(Za(n,new Set([...e]))),i(Za(r,new Set,!0)))},unselectNodesAndEdges:({nodes:e,edges:t}={})=>{const{edges:n,nodes:r,nodeLookup:i,triggerNodeChanges:o,triggerEdgeChanges:a}=l(),s=t||n,c=(e||r).map((e=>{const t=i.get(e.id);return t&&(t.selected=!1),Qa(e.id,!1)})),u=s.map((e=>Qa(e.id,!1)));o(c),a(u)},setMinZoom:e=>{const{panZoom:t,maxZoom:n}=l();t?.setScaleExtent([e,n]),u({minZoom:e})},setMaxZoom:e=>{const{panZoom:t,minZoom:n}=l();t?.setScaleExtent([n,e]),u({maxZoom:e})},setTranslateExtent:e=>{l().panZoom?.setTranslateExtent(e),u({translateExtent:e})},setPaneClickDistance:e=>{l().panZoom?.setClickDistance(e)},resetSelectedElements:()=>{const{edges:e,nodes:t,triggerNodeChanges:n,triggerEdgeChanges:r}=l(),i=t.reduce(((e,t)=>t.selected?[...e,Qa(t.id,!1)]:e),[]),o=e.reduce(((e,t)=>t.selected?[...e,Qa(t.id,!1)]:e),[]);n(i),r(o)},setNodeExtent:e=>{const{nodes:t,nodeLookup:n,parentLookup:r,nodeOrigin:i,elevateNodesOnSelect:o,nodeExtent:a}=l();e[0][0]===a[0][0]&&e[0][1]===a[0][1]&&e[1][0]===a[1][0]&&e[1][1]===a[1][1]||(go(t,n,r,{nodeOrigin:i,nodeExtent:e,elevateNodesOnSelect:o,checkEquality:!1}),u({nodeExtent:e}))},panBy:e=>{const{transform:t,width:n,height:r,panZoom:i,translateExtent:o}=l();return async function({delta:e,panZoom:t,transform:n,translateExtent:r,width:i,height:o}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const a=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[i,o]],r),s=!!a&&(a.x!==n[0]||a.y!==n[1]||a.k!==n[2]);return Promise.resolve(s)}({delta:e,panZoom:i,transform:t,translateExtent:o,width:n,height:r})},cancelConnection:()=>{u({connection:{...Qr}})},updateConnection:e=>{u({connection:e})},reset:()=>u({...Nc()})}}),Object.is);function Dc({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:i,initialWidth:o,initialHeight:a,fitView:c,nodeOrigin:u,nodeExtent:l,children:h}){const[f]=(0,s.useState)((()=>Lc({nodes:e,edges:t,defaultNodes:n,defaultEdges:i,width:o,height:a,fitView:c,nodeOrigin:u,nodeExtent:l})));return(0,r.jsx)(pa,{value:f,children:(0,r.jsx)(cs,{children:h})})}function Fc({children:e,nodes:t,edges:n,defaultNodes:i,defaultEdges:o,width:a,height:c,fitView:u,nodeOrigin:l,nodeExtent:h}){return(0,s.useContext)(ga)?(0,r.jsx)(r.Fragment,{children:e}):(0,r.jsx)(Dc,{initialNodes:t,initialEdges:n,defaultNodes:i,defaultEdges:o,initialWidth:a,initialHeight:c,fitView:u,nodeOrigin:l,nodeExtent:h,children:e})}const Bc={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};var zc=is((function({nodes:e,edges:t,defaultNodes:n,defaultEdges:i,className:o,nodeTypes:a,edgeTypes:c,onNodeClick:u,onEdgeClick:l,onInit:h,onMove:f,onMoveStart:d,onMoveEnd:g,onConnect:p,onConnectStart:b,onConnectEnd:m,onClickConnectStart:w,onClickConnectEnd:v,onNodeMouseEnter:y,onNodeMouseMove:S,onNodeMouseLeave:k,onNodeContextMenu:E,onNodeDoubleClick:x,onNodeDragStart:M,onNodeDrag:T,onNodeDragStop:C,onNodesDelete:_,onEdgesDelete:P,onDelete:I,onSelectionChange:A,onSelectionDragStart:O,onSelectionDrag:j,onSelectionDragStop:$,onSelectionContextMenu:R,onSelectionStart:N,onSelectionEnd:L,onBeforeDelete:D,connectionMode:F,connectionLineType:B=Zr.Bezier,connectionLineStyle:z,connectionLineComponent:U,connectionLineContainerStyle:q,deleteKeyCode:H="Backspace",selectionKeyCode:J="Shift",selectionOnDrag:G=!1,selectionMode:V=Yr.Full,panActivationKeyCode:K="Space",multiSelectionKeyCode:W=(Oi()?"Meta":"Control"),zoomActivationKeyCode:X=(Oi()?"Meta":"Control"),snapToGrid:Y,snapGrid:Q,onlyRenderVisibleElements:Z=!1,selectNodesOnDrag:ee,nodesDraggable:ne,nodesConnectable:re,nodesFocusable:ie,nodeOrigin:oe=Na,edgesFocusable:ae,edgesReconnectable:se,elementsSelectable:ce=!0,defaultViewport:ue=La,minZoom:le=.5,maxZoom:he=2,translateExtent:fe=Gr,preventScrolling:de=!0,nodeExtent:ge,defaultMarkerColor:pe="#b1b1b7",zoomOnScroll:be=!0,zoomOnPinch:me=!0,panOnScroll:we=!1,panOnScrollSpeed:ve=.5,panOnScrollMode:ye=Xr.Free,zoomOnDoubleClick:Se=!0,panOnDrag:ke=!0,onPaneClick:Ee,onPaneMouseEnter:xe,onPaneMouseMove:Me,onPaneMouseLeave:Te,onPaneScroll:Ce,onPaneContextMenu:_e,paneClickDistance:Pe=0,nodeClickDistance:Ie=0,children:Ae,onReconnect:Oe,onReconnectStart:je,onReconnectEnd:$e,onEdgeContextMenu:Re,onEdgeDoubleClick:Ne,onEdgeMouseEnter:Le,onEdgeMouseMove:De,onEdgeMouseLeave:Fe,reconnectRadius:Be=10,onNodesChange:ze,onEdgesChange:Ue,noDragClassName:qe="nodrag",noWheelClassName:He="nowheel",noPanClassName:Je="nopan",fitView:Ge,fitViewOptions:Ve,connectOnClick:Ke,attributionPosition:We,proOptions:Xe,defaultEdgeOptions:Ye,elevateNodesOnSelect:Qe,elevateEdgesOnSelect:Ze,disableKeyboardA11y:et=!1,autoPanOnConnect:tt,autoPanOnNodeDrag:nt,autoPanSpeed:rt,connectionRadius:it,isValidConnection:ot,onError:at,style:st,id:ct,nodeDragThreshold:ut,viewport:lt,onViewportChange:ht,width:ft,height:dt,colorMode:gt="light",debug:pt,onScroll:bt,...mt},wt){const vt=ct||"1",yt=function(e){const[t,n]=(0,s.useState)("system"===e?null:e);return(0,s.useEffect)((()=>{if("system"!==e)return void n(e);const t=Ua(),r=()=>n(t?.matches?"dark":"light");return r(),t?.addEventListener("change",r),()=>{t?.removeEventListener("change",r)}}),[e]),null!==t?t:Ua()?.matches?"dark":"light"}(gt),St=(0,s.useCallback)((e=>{e.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),bt?.(e)}),[bt]);return(0,r.jsx)("div",{"data-testid":"rf__wrapper",...mt,onScroll:St,style:{...st,...Bc},ref:wt,className:te(["react-flow",o,yt]),id:ct,children:(0,r.jsxs)(Fc,{nodes:e,edges:t,width:ft,height:dt,fitView:Ge,nodeOrigin:oe,nodeExtent:ge,children:[(0,r.jsx)(Rc,{onInit:h,onNodeClick:u,onEdgeClick:l,onNodeMouseEnter:y,onNodeMouseMove:S,onNodeMouseLeave:k,onNodeContextMenu:E,onNodeDoubleClick:x,nodeTypes:a,edgeTypes:c,connectionLineType:B,connectionLineStyle:z,connectionLineComponent:U,connectionLineContainerStyle:q,selectionKeyCode:J,selectionOnDrag:G,selectionMode:V,deleteKeyCode:H,multiSelectionKeyCode:W,panActivationKeyCode:K,zoomActivationKeyCode:X,onlyRenderVisibleElements:Z,defaultViewport:ue,translateExtent:fe,minZoom:le,maxZoom:he,preventScrolling:de,zoomOnScroll:be,zoomOnPinch:me,zoomOnDoubleClick:Se,panOnScroll:we,panOnScrollSpeed:ve,panOnScrollMode:ye,panOnDrag:ke,onPaneClick:Ee,onPaneMouseEnter:xe,onPaneMouseMove:Me,onPaneMouseLeave:Te,onPaneScroll:Ce,onPaneContextMenu:_e,paneClickDistance:Pe,nodeClickDistance:Ie,onSelectionContextMenu:R,onSelectionStart:N,onSelectionEnd:L,onReconnect:Oe,onReconnectStart:je,onReconnectEnd:$e,onEdgeContextMenu:Re,onEdgeDoubleClick:Ne,onEdgeMouseEnter:Le,onEdgeMouseMove:De,onEdgeMouseLeave:Fe,reconnectRadius:Be,defaultMarkerColor:pe,noDragClassName:qe,noWheelClassName:He,noPanClassName:Je,rfId:vt,disableKeyboardA11y:et,nodeExtent:ge,viewport:lt,onViewportChange:ht}),(0,r.jsx)(za,{nodes:e,edges:t,defaultNodes:n,defaultEdges:i,onConnect:p,onConnectStart:b,onConnectEnd:m,onClickConnectStart:w,onClickConnectEnd:v,nodesDraggable:ne,nodesConnectable:re,nodesFocusable:ie,edgesFocusable:ae,edgesReconnectable:se,elementsSelectable:ce,elevateNodesOnSelect:Qe,elevateEdgesOnSelect:Ze,minZoom:le,maxZoom:he,nodeExtent:ge,onNodesChange:ze,onEdgesChange:Ue,snapToGrid:Y,snapGrid:Q,connectionMode:F,translateExtent:fe,connectOnClick:Ke,defaultEdgeOptions:Ye,fitView:Ge,fitViewOptions:Ve,onNodesDelete:_,onEdgesDelete:P,onDelete:I,onNodeDragStart:M,onNodeDrag:T,onNodeDragStop:C,onSelectionDrag:j,onSelectionDragStart:O,onSelectionDragStop:$,onMove:f,onMoveStart:d,onMoveEnd:g,noPanClassName:Je,nodeOrigin:oe,rfId:vt,autoPanOnConnect:tt,autoPanOnNodeDrag:nt,autoPanSpeed:rt,onError:at,connectionRadius:it,isValidConnection:ot,selectNodesOnDrag:ee,nodeDragThreshold:ut,onBeforeDelete:D,paneClickDistance:Pe,debug:pt}),(0,r.jsx)(Ra,{onSelectionChange:A}),Ae,(0,r.jsx)(Pa,{proOptions:Xe,position:We}),(0,r.jsx)(Ta,{rfId:vt,disableKeyboardA11y:et})]})})}));const Uc=e=>e.nodes;function qc(){return ma(Uc,da)}const Hc=e=>({x:e.transform[0],y:e.transform[1],zoom:e.transform[2]});function Jc(){return ma(Hc,da)}function Gc({dimensions:e,lineWidth:t,variant:n,className:i}){return(0,r.jsx)("path",{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:te(["react-flow__background-pattern",n,i])})}function Vc({radius:e,className:t}){return(0,r.jsx)("circle",{cx:e,cy:e,r:e,className:te(["react-flow__background-pattern","dots",t])})}var Kc;!function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"}(Kc||(Kc={}));const Wc={[Kc.Dots]:1,[Kc.Lines]:1,[Kc.Cross]:6},Xc=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Yc({id:e,variant:t=Kc.Dots,gap:n=20,size:i,lineWidth:o=1,offset:a=0,color:c,bgColor:u,style:l,className:h,patternClassName:f}){const d=(0,s.useRef)(null),{transform:g,patternId:p}=ma(Xc,da),b=i||Wc[t],m=t===Kc.Dots,w=t===Kc.Cross,v=Array.isArray(n)?n:[n,n],y=[v[0]*g[2]||1,v[1]*g[2]||1],S=b*g[2],k=Array.isArray(a)?a:[a,a],E=w?[S,S]:y,x=[k[0]*g[2]||1+E[0]/2,k[1]*g[2]||1+E[1]/2],M=`${p}${e||""}`;return(0,r.jsxs)("svg",{className:te(["react-flow__background",h]),style:{...l,...gs,"--xy-background-color-props":u,"--xy-background-pattern-color-props":c},ref:d,"data-testid":"rf__background",children:[(0,r.jsx)("pattern",{id:M,x:g[0]%y[0],y:g[1]%y[1],width:y[0],height:y[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${x[0]},-${x[1]})`,children:m?(0,r.jsx)(Vc,{radius:S/2,className:f}):(0,r.jsx)(Gc,{dimensions:E,lineWidth:o,variant:t,className:f})}),(0,r.jsx)("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${M})`})]})}Yc.displayName="Background";const Qc=(0,s.memo)(Yc);function Zc(){return(0,r.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:(0,r.jsx)("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function eu(){return(0,r.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:(0,r.jsx)("path",{d:"M0 0h32v4.2H0z"})})}function tu(){return(0,r.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:(0,r.jsx)("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"})})}function nu(){return(0,r.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:(0,r.jsx)("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"})})}function ru(){return(0,r.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:(0,r.jsx)("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"})})}function iu({children:e,className:t,...n}){return(0,r.jsx)("button",{type:"button",className:te(["react-flow__controls-button",t]),...n,children:e})}const ou=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom});function au({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:i=!0,fitViewOptions:o,onZoomIn:a,onZoomOut:s,onFitView:c,onInteractiveChange:u,className:l,children:h,position:f="bottom-left",orientation:d="vertical","aria-label":g="React Flow controls"}){const p=wa(),{isInteractive:b,minZoomReached:m,maxZoomReached:w}=ma(ou,da),{zoomIn:v,zoomOut:y,fitView:S}=ls();return(0,r.jsxs)(_a,{className:te(["react-flow__controls","horizontal"===d?"horizontal":"vertical",l]),position:f,style:e,"data-testid":"rf__controls","aria-label":g,children:[t&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(iu,{onClick:()=>{v(),a?.()},className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:w,children:(0,r.jsx)(Zc,{})}),(0,r.jsx)(iu,{onClick:()=>{y(),s?.()},className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:m,children:(0,r.jsx)(eu,{})})]}),n&&(0,r.jsx)(iu,{className:"react-flow__controls-fitview",onClick:()=>{S(o),c?.()},title:"fit view","aria-label":"fit view",children:(0,r.jsx)(tu,{})}),i&&(0,r.jsx)(iu,{className:"react-flow__controls-interactive",onClick:()=>{p.setState({nodesDraggable:!b,nodesConnectable:!b,elementsSelectable:!b}),u?.(!b)},title:"toggle interactivity","aria-label":"toggle interactivity",children:b?(0,r.jsx)(ru,{}):(0,r.jsx)(nu,{})}),h]})}au.displayName="Controls";const su=(0,s.memo)(au),cu=(0,s.memo)((function({id:e,x:t,y:n,width:i,height:o,style:a,color:s,strokeColor:c,strokeWidth:u,className:l,borderRadius:h,shapeRendering:f,selected:d,onClick:g}){const{background:p,backgroundColor:b}=a||{},m=s||p||b;return(0,r.jsx)("rect",{className:te(["react-flow__minimap-node",{selected:d},l]),x:t,y:n,rx:h,ry:h,width:i,height:o,style:{fill:m,stroke:c,strokeWidth:u},shapeRendering:f,onClick:g?t=>g(t,e):void 0})})),uu=e=>e.nodes.map((e=>e.id)),lu=e=>e instanceof Function?e:()=>e,hu=(0,s.memo)((function({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:i,nodeBorderRadius:o,nodeStrokeWidth:a,shapeRendering:s,NodeComponent:c,onClick:u}){const{node:l,x:h,y:f,width:d,height:g}=ma((t=>{const n=t.nodeLookup.get(e),{x:r,y:i}=n.internals.positionAbsolute,{width:o,height:a}=$i(n);return{node:n,x:r,y:i,width:o,height:a}}),da);return l&&!l.hidden&&Ri(l)?(0,r.jsx)(c,{x:h,y:f,width:d,height:g,style:l.style,selected:!!l.selected,className:i(l),color:t(l),borderRadius:o,strokeColor:n(l),strokeWidth:a,shapeRendering:s,onClick:u,id:l.id}):null}));var fu=(0,s.memo)((function({nodeStrokeColor:e,nodeColor:t,nodeClassName:n="",nodeBorderRadius:i=5,nodeStrokeWidth:o,nodeComponent:a=cu,onClick:s}){const c=ma(uu,da),u=lu(t),l=lu(e),h=lu(n),f=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return(0,r.jsx)(r.Fragment,{children:c.map((e=>(0,r.jsx)(hu,{id:e,nodeColorFunc:u,nodeStrokeColorFunc:l,nodeClassNameFunc:h,nodeBorderRadius:i,nodeStrokeWidth:o,NodeComponent:a,onClick:s,shapeRendering:f},e)))})}));const du=e=>!e.hidden,gu=e=>{const t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};return{viewBB:t,boundingRect:e.nodeLookup.size>0?ki(ci(e.nodeLookup,{filter:du}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height}};function pu({style:e,className:t,nodeStrokeColor:n,nodeColor:i,nodeClassName:o="",nodeBorderRadius:a=5,nodeStrokeWidth:c,nodeComponent:u,bgColor:l,maskColor:h,maskStrokeColor:f,maskStrokeWidth:d,position:g="bottom-right",onClick:p,onNodeClick:b,pannable:m=!1,zoomable:w=!1,ariaLabel:v="React Flow mini map",inversePan:y,zoomStep:S=10,offsetScale:k=5}){const E=wa(),x=(0,s.useRef)(null),{boundingRect:M,viewBB:T,rfId:C,panZoom:_,translateExtent:P,flowWidth:I,flowHeight:A}=ma(gu,da),O=e?.width??200,j=e?.height??150,$=M.width/O,R=M.height/j,N=Math.max($,R),L=N*O,D=N*j,F=k*N,B=M.x-(L-M.width)/2-F,z=M.y-(D-M.height)/2-F,U=L+2*F,q=D+2*F,H=`react-flow__minimap-desc-${C}`,J=(0,s.useRef)(0),G=(0,s.useRef)();J.current=N,(0,s.useEffect)((()=>{if(x.current&&_)return G.current=function({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const i=wt(e);return{update:function({translateExtent:e,width:o,height:a,zoomStep:s=10,pannable:c=!0,zoomable:u=!0,inversePan:l=!1}){let h=[0,0];const f=Hr().on("start",(e=>{("mousedown"===e.sourceEvent.type||"touchstart"===e.sourceEvent.type)&&(h=[e.sourceEvent.clientX??e.sourceEvent.touches[0].clientX,e.sourceEvent.clientY??e.sourceEvent.touches[0].clientY])})).on("zoom",c?i=>{const s=n();if("mousemove"!==i.sourceEvent.type&&"touchmove"!==i.sourceEvent.type||!t)return;const c=[i.sourceEvent.clientX??i.sourceEvent.touches[0].clientX,i.sourceEvent.clientY??i.sourceEvent.touches[0].clientY],u=[c[0]-h[0],c[1]-h[1]];h=c;const f=r()*Math.max(s[2],Math.log(s[2]))*(l?-1:1),d={x:s[0]-u[0]*f,y:s[1]-u[1]*f},g=[[0,0],[o,a]];t.setViewportConstrained({x:d.x,y:d.y,zoom:s[2]},g,e)}:null).on("zoom.wheel",u?e=>{const r=n();if("wheel"!==e.sourceEvent.type||!t)return;const i=-e.sourceEvent.deltaY*(1===e.sourceEvent.deltaMode?.05:e.sourceEvent.deltaMode?1:.002)*s,o=r[2]*Math.pow(2,i);t.scaleTo(o)}:null);i.call(f,{})},destroy:function(){i.on("zoom",null)},pointer:vt}}({domNode:x.current,panZoom:_,getTransform:()=>E.getState().transform,getViewScale:()=>J.current}),()=>{G.current?.destroy()}}),[_]),(0,s.useEffect)((()=>{G.current?.update({translateExtent:P,width:I,height:A,inversePan:y,pannable:m,zoomStep:S,zoomable:w})}),[m,w,y,S,P,I,A]);const V=p?e=>{const[t,n]=G.current?.pointer(e)||[0,0];p(e,{x:t,y:n})}:void 0,K=b?(0,s.useCallback)(((e,t)=>{const n=E.getState().nodeLookup.get(t);b(e,n)}),[]):void 0;return(0,r.jsx)(_a,{position:g,style:{...e,"--xy-minimap-background-color-props":"string"==typeof l?l:void 0,"--xy-minimap-mask-background-color-props":"string"==typeof h?h:void 0,"--xy-minimap-mask-stroke-color-props":"string"==typeof f?f:void 0,"--xy-minimap-mask-stroke-width-props":"number"==typeof d?d*N:void 0,"--xy-minimap-node-background-color-props":"string"==typeof i?i:void 0,"--xy-minimap-node-stroke-color-props":"string"==typeof n?n:void 0,"--xy-minimap-node-stroke-width-props":"string"==typeof c?c:void 0},className:te(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:(0,r.jsxs)("svg",{width:O,height:j,viewBox:`${B} ${z} ${U} ${q}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":H,ref:x,onClick:V,children:[v&&(0,r.jsx)("title",{id:H,children:v}),(0,r.jsx)(fu,{onClick:K,nodeColor:i,nodeStrokeColor:n,nodeBorderRadius:a,nodeClassName:o,nodeStrokeWidth:c,nodeComponent:u}),(0,r.jsx)("path",{className:"react-flow__minimap-mask",d:`M${B-F},${z-F}h${U+2*F}v${q+2*F}h${-U-2*F}z\n M${T.x},${T.y}h${T.width}v${T.height}h${-T.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}pu.displayName="MiniMap";const bu=(0,s.memo)(pu);(0,s.memo)((function({nodeId:e,position:t,variant:n=Ro.Handle,className:i,style:o={},children:a,color:c,minWidth:u=10,minHeight:l=10,maxWidth:h=Number.MAX_VALUE,maxHeight:f=Number.MAX_VALUE,keepAspectRatio:d=!1,shouldResize:g,onResizeStart:p,onResize:b,onResizeEnd:m}){const w=_s(),v="string"==typeof e?e:w,y=wa(),S=(0,s.useRef)(null),k=n===Ro.Line?"right":"bottom-right",E=t??k,x=(0,s.useRef)(null);(0,s.useEffect)((()=>{if(S.current&&v)return x.current||(x.current=function({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:i}){const o=wt(e);return{update:function({controlPosition:e,boundaries:a,keepAspectRatio:s,onResizeStart:c,onResize:u,onResizeEnd:l,shouldResize:h}){let f={...Bo},d={...zo};const g=function(e){return{isHorizontal:e.includes("right")||e.includes("left"),isVertical:e.includes("bottom")||e.includes("top"),affectsX:e.includes("left"),affectsY:e.includes("top")}}(e);let p,b,m,w,v=null,y=[];const S=Ot().on("start",(e=>{const{nodeLookup:r,transform:i,snapGrid:o,snapToGrid:a,nodeOrigin:s,paneDomNode:u}=n();if(p=r.get(t),!p)return;v=u?.getBoundingClientRect()??null;const{xSnapped:l,ySnapped:h}=Di(e.sourceEvent,{transform:i,snapGrid:o,snapToGrid:a,containerBounds:v});f={width:p.measured.width??0,height:p.measured.height??0,x:p.position.x??0,y:p.position.y??0},d={...f,pointerX:l,pointerY:h,aspectRatio:f.width/f.height},b=void 0,p.parentId&&("parent"===p.extent||p.expandParent)&&(b=r.get(p.parentId),m=b&&"parent"===p.extent?function(e){return[[0,0],[e.measured.width,e.measured.height]]}(b):void 0),y=[],w=void 0;for(const[e,n]of r)if(n.parentId===t&&(y.push({id:e,position:{...n.position},extent:n.extent}),"parent"===n.extent||n.expandParent)){const e=Uo(n,p,n.origin??s);w=w?[[Math.min(e[0][0],w[0][0]),Math.min(e[0][1],w[0][1])],[Math.max(e[1][0],w[1][0]),Math.max(e[1][1],w[1][1])]]:e}c?.(e,{...f})})).on("drag",(e=>{const{transform:t,snapGrid:i,snapToGrid:o,nodeOrigin:c}=n(),l=Di(e.sourceEvent,{transform:t,snapGrid:i,snapToGrid:o,containerBounds:v}),S=[];if(!p)return;const{x:k,y:E,width:x,height:M}=f,T={},C=p.origin??c,{width:_,height:P,x:I,y:A}=function(e,t,n,r,i,o,a,s){let{affectsX:c,affectsY:u}=t;const{isHorizontal:l,isVertical:h}=t,f=l&&h,{xSnapped:d,ySnapped:g}=n,{minWidth:p,maxWidth:b,minHeight:m,maxHeight:w}=r,{x:v,y,width:S,height:k,aspectRatio:E}=e;let x=Math.floor(l?d-e.pointerX:0),M=Math.floor(h?g-e.pointerY:0);const T=S+(c?-x:x),C=k+(u?-M:M),_=-o[0]*S,P=-o[1]*k;let I=Do(T,p,b),A=Do(C,m,w);if(a){let e=0,t=0;c&&x<0?e=No(v+x+_,a[0][0]):!c&&x>0&&(e=Lo(v+T+_,a[1][0])),u&&M<0?t=No(y+M+P,a[0][1]):!u&&M>0&&(t=Lo(y+C+P,a[1][1])),I=Math.max(I,e),A=Math.max(A,t)}if(s){let e=0,t=0;c&&x>0?e=Lo(v+x,s[0][0]):!c&&x<0&&(e=No(v+T,s[1][0])),u&&M>0?t=Lo(y+M,s[0][1]):!u&&M<0&&(t=No(y+C,s[1][1])),I=Math.max(I,e),A=Math.max(A,t)}if(i){if(l){const e=Do(T/E,m,w)*E;if(I=Math.max(I,e),a){let e=0;e=!c&&!u||c&&!u&&f?Lo(y+P+T/E,a[1][1])*E:No(y+P+(c?x:-x)/E,a[0][1])*E,I=Math.max(I,e)}if(s){let e=0;e=!c&&!u||c&&!u&&f?No(y+T/E,s[1][1])*E:Lo(y+(c?x:-x)/E,s[0][1])*E,I=Math.max(I,e)}}if(h){const e=Do(C*E,p,b)/E;if(A=Math.max(A,e),a){let e=0;e=!c&&!u||u&&!c&&f?Lo(v+C*E+_,a[1][0])/E:No(v+(u?M:-M)*E+_,a[0][0])/E,A=Math.max(A,e)}if(s){let e=0;e=!c&&!u||u&&!c&&f?No(v+C*E,s[1][0])/E:Lo(v+(u?M:-M)*E,s[0][0])/E,A=Math.max(A,e)}}}M+=M<0?A:-A,x+=x<0?I:-I,i&&(f?T>C*E?M=(Fo(c,u)?-x:x)/E:x=(Fo(c,u)?-M:M)*E:l?(M=x/E,u=c):(x=M*E,c=u));const O=c?v+x:v,j=u?y+M:y;return{width:S+(c?-x:x),height:k+(u?-M:M),x:o[0]*x*(c?-1:1)+O,y:o[1]*M*(u?-1:1)+j}}(d,g,l,a,s,C,m,w),O=_!==x,j=P!==M,$=I!==k&&O,R=A!==E&&j;if(!($||R||O||j))return;if(($||R||1===C[0]||1===C[1])&&(T.x=$?I:f.x,T.y=R?A:f.y,f.x=T.x,f.y=T.y,y.length>0)){const e=I-k,t=A-E;for(const n of y)n.position={x:n.position.x-e+C[0]*(_-x),y:n.position.y-t+C[1]*(P-M)},S.push(n)}if((O||j)&&(T.width=O?_:f.width,T.height=j?P:f.height,f.width=T.width,f.height=T.height),b&&p.expandParent){const e=C[0]*(T.width??0);T.x&&T.x<e&&(f.x=e,d.x=d.x-(T.x-e));const t=C[1]*(T.height??0);T.y&&T.y<t&&(f.y=t,d.y=d.y-(T.y-t))}const N=function({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:i,affectsY:o}){const a=e-t,s=n-r,c=[a>0?1:a<0?-1:0,s>0?1:s<0?-1:0];return a&&i&&(c[0]=-1*c[0]),s&&o&&(c[1]=-1*c[1]),c}({width:f.width,prevWidth:x,height:f.height,prevHeight:M,affectsX:g.affectsX,affectsY:g.affectsY}),L={...f,direction:N};!1!==h?.(e,L)&&(u?.(e,L),r(T,S))})).on("end",(e=>{l?.(e,{...f}),i?.()}));o.call(S)},destroy:function(){o.on(".drag",null)}}}({domNode:S.current,nodeId:v,getStoreItems:()=>{const{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,domNode:o}=y.getState();return{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,paneDomNode:o}},onChange:(e,t)=>{const{triggerNodeChanges:n,nodeLookup:r,parentLookup:i,nodeOrigin:o}=y.getState(),a=[],s={x:e.x,y:e.y},c=r.get(v);if(c&&c.expandParent&&c.parentId){const t=c.origin??o,n=e.width??c.measured.width??0,u=e.height??c.measured.height??0,l=mo([{id:c.id,parentId:c.parentId,rect:{width:n,height:u,...Ni({x:e.x??c.position.x,y:e.y??c.position.y},{width:n,height:u},c.parentId,r,t)}}],r,i,o);a.push(...l),s.x=e.x?Math.max(t[0]*n,e.x):void 0,s.y=e.y?Math.max(t[1]*u,e.y):void 0}if(void 0!==s.x&&void 0!==s.y){const e={id:v,type:"position",position:{...s}};a.push(e)}if(void 0!==e.width&&void 0!==e.height){const t={id:v,type:"dimensions",resizing:!0,setAttributes:!0,dimensions:{width:e.width,height:e.height}};a.push(t)}for(const e of t){const t={...e,type:"position"};a.push(t)}n(a)},onEnd:()=>{const e={id:v,type:"dimensions",resizing:!1};y.getState().triggerNodeChanges([e])}})),x.current.update({controlPosition:E,boundaries:{minWidth:u,minHeight:l,maxWidth:h,maxHeight:f},keepAspectRatio:d,onResizeStart:p,onResize:b,onResizeEnd:m,shouldResize:g}),()=>{x.current?.destroy()}}),[E,u,l,h,f,d,p,b,m,g]);const M=E.split("-"),T=n===Ro.Line?"borderColor":"backgroundColor",C=c?{...o,[T]:c}:o;return(0,r.jsx)("div",{className:te(["react-flow__resize-control","nodrag",...M,n,i]),ref:S,style:C,children:a})}));const mu=()=>{const e=(0,o.u)();return(0,r.jsx)(bu,{maskColor:e.minimap.mask,nodeColor:e.minimap.node,style:{width:200,height:100,background:e.minimap.selectionArea}})},wu=e=>{const{data:t,...n}=e;return{...n,...t,fields:t.fields.map((({isVisible:e,hasChildren:t,...n})=>n)),type:e.type}},vu=e=>e.map((e=>wu(e)));function yu(e,t,n){const r=e.depth??0,i=n.length>t+1?n[t+1]:null;return!!i&&void 0!==i.depth&&i.depth>r}function Su(e){const t=new Set;return e.map(((n,r)=>{const i=n.depth??0,o=n.id?.slice(0,-1),a=0===i||t.has(JSON.stringify(o)),s=n.expanded??!0;return a&&s&&t.add(JSON.stringify(n.id)),{...n,hasChildren:yu(n,r,e),isVisible:a}}))}const ku=e=>e.map((e=>(e=>{const{title:t,fields:n,borderVariant:r,disabled:i,connectable:o,variant:a,...s}=e;return{...s,connectable:o??!1,data:{title:t,disabled:i,fields:Su(n),borderVariant:r,variant:a}}})(e))),Eu=e=>{const{markerStart:t,markerEnd:n,type:r,data:i,...o}=e;return{...o,markerStart:t?.replace(/^start-/,""),markerEnd:n?.replace(/^end-/,""),...void 0!==i?.sourceFieldId?{sourceFieldId:i?.sourceFieldId}:{},...void 0!==i?.targetFieldId?{targetFieldId:i?.targetFieldId}:{}}},xu=e=>e.map((e=>Eu(e))),Mu=e=>e.map((e=>(e=>{const{sourceFieldId:t,targetFieldId:n,...r}=e;return{...r,markerStart:`start-${e.markerStart}`,markerEnd:`end-${e.markerEnd}`,type:e.source===e.target?"selfReferencingEdge":void 0!==t&&void 0!==n?"fieldEdge":"floatingEdge",data:{...void 0!==t?{sourceFieldId:t}:{},...void 0!==n?{targetFieldId:n}:{}}}})(e)));function Tu(){const e=ls();return{...e,getNode:t=>{const n=e.getNode(t);if(n)return wu(n)},getNodes:()=>{const t=e.getNodes();return vu(t)},addNodes:t=>{const n=ku(t);e.addNodes(n)},setNodes:t=>{const n=ku(t);e.setNodes(n)},getEdge:t=>{const n=e.getEdge(t);if(n)return Eu(n)},getEdges:()=>e.getEdges().map(Eu),addEdges:t=>{const n=Mu(t);e.addEdges(n)},setEdges:t=>{const n=Mu(t);e.setEdges(n)}}}const Cu={duration:500},_u=L(su)`
6
6
  box-shadow: unset;
7
7
  display: flex;
8
8
  flex-direction: row;
@@ -145,7 +145,7 @@ export const __webpack_esm_id__=400;export const __webpack_esm_ids__=[400];expor
145
145
  text-wrap: wrap;
146
146
  text-align: left;
147
147
  font-style: normal;
148
- `,Zu=L(p.A)`
148
+ `,Zu=L(p.Ay)`
149
149
  font-style: italic;
150
150
  text-decoration-color: inherit;
151
151
  text-underline-offset: 0.25em;