@sequenzy/mcp 0.0.140 → 0.0.141

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,32 +1,32 @@
1
1
  #!/usr/bin/env node
2
- var u3=Object.create;var{getPrototypeOf:f3,defineProperty:A4,getOwnPropertyNames:c3}=Object;var m3=Object.prototype.hasOwnProperty;function l3(w){return this[w]}var g3,i3,DW=(w,b,$)=>{var W=w!=null&&typeof w==="object";if(W){var Q=b?g3??=new WeakMap:i3??=new WeakMap,X=Q.get(w);if(X)return X}$=w!=null?u3(f3(w)):{};let G=b||!w||!w.__esModule?A4($,"default",{value:w,enumerable:!0}):$;for(let J of c3(w))if(!m3.call(G,J))A4(G,J,{get:l3.bind(w,J),enumerable:!0});if(W)Q.set(w,G);return G};var I=(w,b)=>()=>(b||w((b={exports:{}}).exports,b),b.exports);var n3=(w)=>w;function p3(w,b){this[w]=n3.bind(null,b)}var BW=(w,b)=>{for(var $ in b)A4(w,$,{get:b[$],enumerable:!0,configurable:!0,set:p3.bind(b,$)})};var d0=I((AG)=>{Object.defineProperty(AG,"__esModule",{value:!0});AG.regexpCode=AG.getEsmExportName=AG.getProperty=AG.safeStringify=AG.stringify=AG.strConcat=AG.addCodeArg=AG.str=AG._=AG.nil=AG._Code=AG.Name=AG.IDENTIFIER=AG._CodeOrName=void 0;class Y6{}AG._CodeOrName=Y6;AG.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class e1 extends Y6{constructor(w){super();if(!AG.IDENTIFIER.test(w))throw Error("CodeGen: name must be a valid identifier");this.str=w}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}AG.Name=e1;class mw extends Y6{constructor(w){super();this._items=typeof w==="string"?[w]:w}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let w=this._items[0];return w===""||w==='""'}get str(){var w;return(w=this._str)!==null&&w!==void 0?w:this._str=this._items.reduce((b,$)=>`${b}${$}`,"")}get names(){var w;return(w=this._names)!==null&&w!==void 0?w:this._names=this._items.reduce((b,$)=>{if($ instanceof e1)b[$.str]=(b[$.str]||0)+1;return b},{})}}AG._Code=mw;AG.nil=new mw("");function DG(w,...b){let $=[w[0]],W=0;while(W<b.length)j$($,b[W]),$.push(w[++W]);return new mw($)}AG._=DG;var V$=new mw("+");function BG(w,...b){let $=[p0(w[0])],W=0;while(W<b.length)$.push(V$),j$($,b[W]),$.push(V$,p0(w[++W]));return LA($),new mw($)}AG.str=BG;function j$(w,b){if(b instanceof mw)w.push(...b._items);else if(b instanceof e1)w.push(b);else w.push(OA(b))}AG.addCodeArg=j$;function LA(w){let b=1;while(b<w.length-1){if(w[b]===V$){let $=UA(w[b-1],w[b+1]);if($!==void 0){w.splice(b-1,3,$);continue}w[b++]="+"}b++}}function UA(w,b){if(b==='""')return w;if(w==='""')return b;if(typeof w=="string"){if(b instanceof e1||w[w.length-1]!=='"')return;if(typeof b!="string")return`${w.slice(0,-1)}${b}"`;if(b[0]==='"')return w.slice(0,-1)+b.slice(1);return}if(typeof b=="string"&&b[0]==='"'&&!(w instanceof e1))return`"${w}${b.slice(1)}`;return}function KA(w,b){return b.emptyStr()?w:w.emptyStr()?b:BG`${w}${b}`}AG.strConcat=KA;function OA(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:p0(Array.isArray(w)?w.join(","):w)}function ZA(w){return new mw(p0(w))}AG.stringify=ZA;function p0(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}AG.safeStringify=p0;function MA(w){return typeof w=="string"&&AG.IDENTIFIER.test(w)?new mw(`.${w}`):DG`[${w}]`}AG.getProperty=MA;function VA(w){if(typeof w=="string"&&AG.IDENTIFIER.test(w))return new mw(`${w}`);throw Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}AG.getEsmExportName=VA;function jA(w){return new mw(w.toString())}AG.regexpCode=jA});var N$=I((KG)=>{Object.defineProperty(KG,"__esModule",{value:!0});KG.ValueScope=KG.ValueScopeName=KG.Scope=KG.varKinds=KG.UsedValueState=void 0;var Iw=d0();class LG extends Error{constructor(w){super(`CodeGen: "code" for ${w} not defined`);this.value=w.value}}var z6;(function(w){w[w.Started=0]="Started",w[w.Completed=1]="Completed"})(z6||(KG.UsedValueState=z6={}));KG.varKinds={const:new Iw.Name("const"),let:new Iw.Name("let"),var:new Iw.Name("var")};class P${constructor({prefixes:w,parent:b}={}){this._names={},this._prefixes=w,this._parent=b}toName(w){return w instanceof Iw.Name?w:this.name(w)}name(w){return new Iw.Name(this._newName(w))}_newName(w){let b=this._names[w]||this._nameGroup(w);return`${w}${b.index++}`}_nameGroup(w){var b,$;if((($=(b=this._parent)===null||b===void 0?void 0:b._prefixes)===null||$===void 0?void 0:$.has(w))||this._prefixes&&!this._prefixes.has(w))throw Error(`CodeGen: prefix "${w}" is not allowed in this scope`);return this._names[w]={prefix:w,index:0}}}KG.Scope=P$;class I$ extends Iw.Name{constructor(w,b){super(b);this.prefix=w}setValue(w,{property:b,itemIndex:$}){this.value=w,this.scopePath=Iw._`.${new Iw.Name(b)}[${$}]`}}KG.ValueScopeName=I$;var xA=Iw._`\n`;class UG extends P${constructor(w){super(w);this._values={},this._scope=w.scope,this.opts={...w,_n:w.lines?xA:Iw.nil}}get(){return this._scope}name(w){return new I$(w,this._newName(w))}value(w,b){var $;if(b.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName(w),{prefix:Q}=W,X=($=b.key)!==null&&$!==void 0?$:b.ref,G=this._values[Q];if(G){let H=G.get(X);if(H)return H}else G=this._values[Q]=new Map;G.set(X,W);let J=this._scope[Q]||(this._scope[Q]=[]),Y=J.length;return J[Y]=b.ref,W.setValue(b,{property:Q,itemIndex:Y}),W}getValue(w,b){let $=this._values[w];if(!$)return;return $.get(b)}scopeRefs(w,b=this._values){return this._reduceValues(b,($)=>{if($.scopePath===void 0)throw Error(`CodeGen: name "${$}" has no value`);return Iw._`${w}${$.scopePath}`})}scopeCode(w=this._values,b,$){return this._reduceValues(w,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},b,$)}_reduceValues(w,b,$={},W){let Q=Iw.nil;for(let X in w){let G=w[X];if(!G)continue;let J=$[X]=$[X]||new Map;G.forEach((Y)=>{if(J.has(Y))return;J.set(Y,z6.Started);let H=b(Y);if(H){let z=this.opts.es5?KG.varKinds.var:KG.varKinds.const;Q=Iw._`${Q}${z} ${Y} = ${H};${this.opts._n}`}else if(H=W===null||W===void 0?void 0:W(Y))Q=Iw._`${Q}${H}${this.opts._n}`;else throw new LG(Y);J.set(Y,z6.Completed)})}return Q}}KG.ValueScope=UG});var f=I((Nw)=>{Object.defineProperty(Nw,"__esModule",{value:!0});Nw.or=Nw.and=Nw.not=Nw.CodeGen=Nw.operators=Nw.varKinds=Nw.ValueScopeName=Nw.ValueScope=Nw.Scope=Nw.Name=Nw.regexpCode=Nw.stringify=Nw.getProperty=Nw.nil=Nw.strConcat=Nw.str=Nw._=void 0;var i=d0(),lw=N$(),I1=d0();Object.defineProperty(Nw,"_",{enumerable:!0,get:function(){return I1._}});Object.defineProperty(Nw,"str",{enumerable:!0,get:function(){return I1.str}});Object.defineProperty(Nw,"strConcat",{enumerable:!0,get:function(){return I1.strConcat}});Object.defineProperty(Nw,"nil",{enumerable:!0,get:function(){return I1.nil}});Object.defineProperty(Nw,"getProperty",{enumerable:!0,get:function(){return I1.getProperty}});Object.defineProperty(Nw,"stringify",{enumerable:!0,get:function(){return I1.stringify}});Object.defineProperty(Nw,"regexpCode",{enumerable:!0,get:function(){return I1.regexpCode}});Object.defineProperty(Nw,"Name",{enumerable:!0,get:function(){return I1.Name}});var U6=N$();Object.defineProperty(Nw,"Scope",{enumerable:!0,get:function(){return U6.Scope}});Object.defineProperty(Nw,"ValueScope",{enumerable:!0,get:function(){return U6.ValueScope}});Object.defineProperty(Nw,"ValueScopeName",{enumerable:!0,get:function(){return U6.ValueScopeName}});Object.defineProperty(Nw,"varKinds",{enumerable:!0,get:function(){return U6.varKinds}});Nw.operators={GT:new i._Code(">"),GTE:new i._Code(">="),LT:new i._Code("<"),LTE:new i._Code("<="),EQ:new i._Code("==="),NEQ:new i._Code("!=="),NOT:new i._Code("!"),OR:new i._Code("||"),AND:new i._Code("&&"),ADD:new i._Code("+")};class N1{optimizeNodes(){return this}optimizeNames(w,b){return this}}class ZG extends N1{constructor(w,b,$){super();this.varKind=w,this.name=b,this.rhs=$}render({es5:w,_n:b}){let $=w?lw.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${W};`+b}optimizeNames(w,b){if(!w[this.name.str])return;if(this.rhs)this.rhs=w0(this.rhs,w,b);return this}get names(){return this.rhs instanceof i._CodeOrName?this.rhs.names:{}}}class R$ extends N1{constructor(w,b,$){super();this.lhs=w,this.rhs=b,this.sideEffects=$}render({_n:w}){return`${this.lhs} = ${this.rhs};`+w}optimizeNames(w,b){if(this.lhs instanceof i.Name&&!w[this.lhs.str]&&!this.sideEffects)return;return this.rhs=w0(this.rhs,w,b),this}get names(){let w=this.lhs instanceof i.Name?{}:{...this.lhs.names};return L6(w,this.rhs)}}class MG extends R${constructor(w,b,$,W){super(w,$,W);this.op=b}render({_n:w}){return`${this.lhs} ${this.op}= ${this.rhs};`+w}}class VG extends N1{constructor(w){super();this.label=w,this.names={}}render({_n:w}){return`${this.label}:`+w}}class jG extends N1{constructor(w){super();this.label=w,this.names={}}render({_n:w}){return`break${this.label?` ${this.label}`:""};`+w}}class qG extends N1{constructor(w){super();this.error=w}render({_n:w}){return`throw ${this.error};`+w}get names(){return this.error.names}}class PG extends N1{constructor(w){super();this.code=w}render({_n:w}){return`${this.code};`+w}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(w,b){return this.code=w0(this.code,w,b),this}get names(){return this.code instanceof i._CodeOrName?this.code.names:{}}}class K6 extends N1{constructor(w=[]){super();this.nodes=w}render(w){return this.nodes.reduce((b,$)=>b+$.render(w),"")}optimizeNodes(){let{nodes:w}=this,b=w.length;while(b--){let $=w[b].optimizeNodes();if(Array.isArray($))w.splice(b,1,...$);else if($)w[b]=$;else w.splice(b,1)}return w.length>0?this:void 0}optimizeNames(w,b){let{nodes:$}=this,W=$.length;while(W--){let Q=$[W];if(Q.optimizeNames(w,b))continue;fA(w,Q.names),$.splice(W,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((w,b)=>h1(w,b.names),{})}}class E1 extends K6{render(w){return"{"+w._n+super.render(w)+"}"+w._n}}class IG extends K6{}class o0 extends E1{}o0.kind="else";class J1 extends E1{constructor(w,b){super(b);this.condition=w}render(w){let b=`if(${this.condition})`+super.render(w);if(this.else)b+="else "+this.else.render(w);return b}optimizeNodes(){super.optimizeNodes();let w=this.condition;if(w===!0)return this.nodes;let b=this.else;if(b){let $=b.optimizeNodes();b=this.else=Array.isArray($)?new o0($):$}if(b){if(w===!1)return b instanceof J1?b:b.nodes;if(this.nodes.length)return this;return new J1(SG(w),b instanceof J1?[b]:b.nodes)}if(w===!1||!this.nodes.length)return;return this}optimizeNames(w,b){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(w,b),!(super.optimizeNames(w,b)||this.else))return;return this.condition=w0(this.condition,w,b),this}get names(){let w=super.names;if(L6(w,this.condition),this.else)h1(w,this.else.names);return w}}J1.kind="if";class a1 extends E1{}a1.kind="for";class NG extends a1{constructor(w){super();this.iteration=w}render(w){return`for(${this.iteration})`+super.render(w)}optimizeNames(w,b){if(!super.optimizeNames(w,b))return;return this.iteration=w0(this.iteration,w,b),this}get names(){return h1(super.names,this.iteration.names)}}class EG extends a1{constructor(w,b,$,W){super();this.varKind=w,this.name=b,this.from=$,this.to=W}render(w){let b=w.es5?lw.varKinds.var:this.varKind,{name:$,from:W,to:Q}=this;return`for(${b} ${$}=${W}; ${$}<${Q}; ${$}++)`+super.render(w)}get names(){let w=L6(super.names,this.from);return L6(w,this.to)}}class E$ extends a1{constructor(w,b,$,W){super();this.loop=w,this.varKind=b,this.name=$,this.iterable=W}render(w){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(w)}optimizeNames(w,b){if(!super.optimizeNames(w,b))return;return this.iterable=w0(this.iterable,w,b),this}get names(){return h1(super.names,this.iterable.names)}}class D6 extends E1{constructor(w,b,$){super();this.name=w,this.args=b,this.async=$}render(w){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(w)}}D6.kind="func";class B6 extends K6{render(w){return"return "+super.render(w)}}B6.kind="return";class TG extends E1{render(w){let b="try"+super.render(w);if(this.catch)b+=this.catch.render(w);if(this.finally)b+=this.finally.render(w);return b}optimizeNodes(){var w,b;return super.optimizeNodes(),(w=this.catch)===null||w===void 0||w.optimizeNodes(),(b=this.finally)===null||b===void 0||b.optimizeNodes(),this}optimizeNames(w,b){var $,W;return super.optimizeNames(w,b),($=this.catch)===null||$===void 0||$.optimizeNames(w,b),(W=this.finally)===null||W===void 0||W.optimizeNames(w,b),this}get names(){let w=super.names;if(this.catch)h1(w,this.catch.names);if(this.finally)h1(w,this.finally.names);return w}}class A6 extends E1{constructor(w){super();this.error=w}render(w){return`catch(${this.error})`+super.render(w)}}A6.kind="catch";class F6 extends E1{render(w){return"finally"+super.render(w)}}F6.kind="finally";class RG{constructor(w,b={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...b,_n:b.lines?`
3
- `:""},this._extScope=w,this._scope=new lw.Scope({parent:w}),this._nodes=[new IG]}toString(){return this._root.render(this.opts)}name(w){return this._scope.name(w)}scopeName(w){return this._extScope.name(w)}scopeValue(w,b){let $=this._extScope.value(w,b);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(w,b){return this._extScope.getValue(w,b)}scopeRefs(w){return this._extScope.scopeRefs(w,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(w,b,$,W){let Q=this._scope.toName(b);if($!==void 0&&W)this._constants[Q.str]=$;return this._leafNode(new ZG(w,Q,$)),Q}const(w,b,$){return this._def(lw.varKinds.const,w,b,$)}let(w,b,$){return this._def(lw.varKinds.let,w,b,$)}var(w,b,$){return this._def(lw.varKinds.var,w,b,$)}assign(w,b,$){return this._leafNode(new R$(w,b,$))}add(w,b){return this._leafNode(new MG(w,Nw.operators.ADD,b))}code(w){if(typeof w=="function")w();else if(w!==i.nil)this._leafNode(new PG(w));return this}object(...w){let b=["{"];for(let[$,W]of w){if(b.length>1)b.push(",");if(b.push($),$!==W||this.opts.es5)b.push(":"),(0,i.addCodeArg)(b,W)}return b.push("}"),new i._Code(b)}if(w,b,$){if(this._blockNode(new J1(w)),b&&$)this.code(b).else().code($).endIf();else if(b)this.code(b).endIf();else if($)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(w){return this._elseNode(new J1(w))}else(){return this._elseNode(new o0)}endIf(){return this._endBlockNode(J1,o0)}_for(w,b){if(this._blockNode(w),b)this.code(b).endFor();return this}for(w,b){return this._for(new NG(w),b)}forRange(w,b,$,W,Q=this.opts.es5?lw.varKinds.var:lw.varKinds.let){let X=this._scope.toName(w);return this._for(new EG(Q,X,b,$),()=>W(X))}forOf(w,b,$,W=lw.varKinds.const){let Q=this._scope.toName(w);if(this.opts.es5){let X=b instanceof i.Name?b:this.var("_arr",b);return this.forRange("_i",0,i._`${X}.length`,(G)=>{this.var(Q,i._`${X}[${G}]`),$(Q)})}return this._for(new E$("of",W,Q,b),()=>$(Q))}forIn(w,b,$,W=this.opts.es5?lw.varKinds.var:lw.varKinds.const){if(this.opts.ownProperties)return this.forOf(w,i._`Object.keys(${b})`,$);let Q=this._scope.toName(w);return this._for(new E$("in",W,Q,b),()=>$(Q))}endFor(){return this._endBlockNode(a1)}label(w){return this._leafNode(new VG(w))}break(w){return this._leafNode(new jG(w))}return(w){let b=new B6;if(this._blockNode(b),this.code(w),b.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(B6)}try(w,b,$){if(!b&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new TG;if(this._blockNode(W),this.code(w),b){let Q=this.name("e");this._currNode=W.catch=new A6(Q),b(Q)}if($)this._currNode=W.finally=new F6,this.code($);return this._endBlockNode(A6,F6)}throw(w){return this._leafNode(new qG(w))}block(w,b){if(this._blockStarts.push(this._nodes.length),w)this.code(w).endBlock(b);return this}endBlock(w){let b=this._blockStarts.pop();if(b===void 0)throw Error("CodeGen: not in self-balancing block");let $=this._nodes.length-b;if($<0||w!==void 0&&$!==w)throw Error(`CodeGen: wrong number of nodes: ${$} vs ${w} expected`);return this._nodes.length=b,this}func(w,b=i.nil,$,W){if(this._blockNode(new D6(w,b,$)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(D6)}optimize(w=1){while(w-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(w){return this._currNode.nodes.push(w),this}_blockNode(w){this._currNode.nodes.push(w),this._nodes.push(w)}_endBlockNode(w,b){let $=this._currNode;if($ instanceof w||b&&$ instanceof b)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${b?`${w.kind}/${b.kind}`:w.kind}"`)}_elseNode(w){let b=this._currNode;if(!(b instanceof J1))throw Error('CodeGen: "else" without "if"');return this._currNode=b.else=w,this}get _root(){return this._nodes[0]}get _currNode(){let w=this._nodes;return w[w.length-1]}set _currNode(w){let b=this._nodes;b[b.length-1]=w}}Nw.CodeGen=RG;function h1(w,b){for(let $ in b)w[$]=(w[$]||0)+(b[$]||0);return w}function L6(w,b){return b instanceof i._CodeOrName?h1(w,b.names):w}function w0(w,b,$){if(w instanceof i.Name)return W(w);if(!Q(w))return w;return new i._Code(w._items.reduce((X,G)=>{if(G instanceof i.Name)G=W(G);if(G instanceof i._Code)X.push(...G._items);else X.push(G);return X},[]));function W(X){let G=$[X.str];if(G===void 0||b[X.str]!==1)return X;return delete b[X.str],G}function Q(X){return X instanceof i._Code&&X._items.some((G)=>G instanceof i.Name&&b[G.str]===1&&$[G.str]!==void 0)}}function fA(w,b){for(let $ in b)w[$]=(w[$]||0)-(b[$]||0)}function SG(w){return typeof w=="boolean"||typeof w=="number"||w===null?!w:i._`!${T$(w)}`}Nw.not=SG;var cA=vG(Nw.operators.AND);function mA(...w){return w.reduce(cA)}Nw.and=mA;var lA=vG(Nw.operators.OR);function gA(...w){return w.reduce(lA)}Nw.or=gA;function vG(w){return(b,$)=>b===i.nil?$:$===i.nil?b:i._`${T$(b)} ${w} ${T$($)}`}function T$(w){return w instanceof i.Name?w:i._`(${w})`}});var o=I((cG)=>{Object.defineProperty(cG,"__esModule",{value:!0});cG.checkStrictMode=cG.getErrorPath=cG.Type=cG.useFunc=cG.setEvaluated=cG.evaluatedPropsToName=cG.mergeEvaluated=cG.eachItem=cG.unescapeJsonPointer=cG.escapeJsonPointer=cG.escapeFragment=cG.unescapeFragment=cG.schemaRefOrVal=cG.schemaHasRulesButRef=cG.schemaHasRules=cG.checkUnknownRules=cG.alwaysValidSchema=cG.toHash=void 0;var e=f(),dA=d0();function oA(w){let b={};for(let $ of w)b[$]=!0;return b}cG.toHash=oA;function tA(w,b){if(typeof b=="boolean")return b;if(Object.keys(b).length===0)return!0;return xG(w,b),!hG(b,w.self.RULES.all)}cG.alwaysValidSchema=tA;function xG(w,b=w.schema){let{opts:$,self:W}=w;if(!$.strictSchema)return;if(typeof b==="boolean")return;let Q=W.RULES.keywords;for(let X in b)if(!Q[X])fG(w,`unknown keyword: "${X}"`)}cG.checkUnknownRules=xG;function hG(w,b){if(typeof w=="boolean")return!w;for(let $ in w)if(b[$])return!0;return!1}cG.schemaHasRules=hG;function rA(w,b){if(typeof w=="boolean")return!w;for(let $ in w)if($!=="$ref"&&b.all[$])return!0;return!1}cG.schemaHasRulesButRef=rA;function sA({topSchemaRef:w,schemaPath:b},$,W,Q){if(!Q){if(typeof $=="number"||typeof $=="boolean")return $;if(typeof $=="string")return e._`${$}`}return e._`${w}${b}${(0,e.getProperty)(W)}`}cG.schemaRefOrVal=sA;function eA(w){return yG(decodeURIComponent(w))}cG.unescapeFragment=eA;function aA(w){return encodeURIComponent(v$(w))}cG.escapeFragment=aA;function v$(w){if(typeof w=="number")return`${w}`;return w.replace(/~/g,"~0").replace(/\//g,"~1")}cG.escapeJsonPointer=v$;function yG(w){return w.replace(/~1/g,"/").replace(/~0/g,"~")}cG.unescapeJsonPointer=yG;function wF(w,b){if(Array.isArray(w))for(let $ of w)b($);else b(w)}cG.eachItem=wF;function kG({mergeNames:w,mergeToName:b,mergeValues:$,resultToName:W}){return(Q,X,G,J)=>{let Y=G===void 0?X:G instanceof e.Name?(X instanceof e.Name?w(Q,X,G):b(Q,X,G),G):X instanceof e.Name?(b(Q,G,X),X):$(X,G);return J===e.Name&&!(Y instanceof e.Name)?W(Q,Y):Y}}cG.mergeEvaluated={props:kG({mergeNames:(w,b,$)=>w.if(e._`${$} !== true && ${b} !== undefined`,()=>{w.if(e._`${b} === true`,()=>w.assign($,!0),()=>w.assign($,e._`${$} || {}`).code(e._`Object.assign(${$}, ${b})`))}),mergeToName:(w,b,$)=>w.if(e._`${$} !== true`,()=>{if(b===!0)w.assign($,!0);else w.assign($,e._`${$} || {}`),C$(w,$,b)}),mergeValues:(w,b)=>w===!0?!0:{...w,...b},resultToName:uG}),items:kG({mergeNames:(w,b,$)=>w.if(e._`${$} !== true && ${b} !== undefined`,()=>w.assign($,e._`${b} === true ? true : ${$} > ${b} ? ${$} : ${b}`)),mergeToName:(w,b,$)=>w.if(e._`${$} !== true`,()=>w.assign($,b===!0?!0:e._`${$} > ${b} ? ${$} : ${b}`)),mergeValues:(w,b)=>w===!0?!0:Math.max(w,b),resultToName:(w,b)=>w.var("items",b)})};function uG(w,b){if(b===!0)return w.var("props",!0);let $=w.var("props",e._`{}`);if(b!==void 0)C$(w,$,b);return $}cG.evaluatedPropsToName=uG;function C$(w,b,$){Object.keys($).forEach((W)=>w.assign(e._`${b}${(0,e.getProperty)(W)}`,!0))}cG.setEvaluated=C$;var _G={};function bF(w,b){return w.scopeValue("func",{ref:b,code:_G[b.code]||(_G[b.code]=new dA._Code(b.code))})}cG.useFunc=bF;var S$;(function(w){w[w.Num=0]="Num",w[w.Str=1]="Str"})(S$||(cG.Type=S$={}));function $F(w,b,$){if(w instanceof e.Name){let W=b===S$.Num;return $?W?e._`"[" + ${w} + "]"`:e._`"['" + ${w} + "']"`:W?e._`"/" + ${w}`:e._`"/" + ${w}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,e.getProperty)(w).toString():"/"+v$(w)}cG.getErrorPath=$F;function fG(w,b,$=w.opts.strictSchema){if(!$)return;if(b=`strict mode: ${b}`,$===!0)throw Error(b);w.self.logger.warn(b)}cG.checkStrictMode=fG});var Y1=I((lG)=>{Object.defineProperty(lG,"__esModule",{value:!0});var Mw=f(),MF={data:new Mw.Name("data"),valCxt:new Mw.Name("valCxt"),instancePath:new Mw.Name("instancePath"),parentData:new Mw.Name("parentData"),parentDataProperty:new Mw.Name("parentDataProperty"),rootData:new Mw.Name("rootData"),dynamicAnchors:new Mw.Name("dynamicAnchors"),vErrors:new Mw.Name("vErrors"),errors:new Mw.Name("errors"),this:new Mw.Name("this"),self:new Mw.Name("self"),scope:new Mw.Name("scope"),json:new Mw.Name("json"),jsonPos:new Mw.Name("jsonPos"),jsonLen:new Mw.Name("jsonLen"),jsonPart:new Mw.Name("jsonPart")};lG.default=MF});var t0=I((pG)=>{Object.defineProperty(pG,"__esModule",{value:!0});pG.extendErrors=pG.resetErrorsCount=pG.reportExtraError=pG.reportError=pG.keyword$DataError=pG.keywordError=void 0;var p=f(),Z6=o(),jw=Y1();pG.keywordError={message:({keyword:w})=>p.str`must pass "${w}" keyword validation`};pG.keyword$DataError={message:({keyword:w,schemaType:b})=>b?p.str`"${w}" keyword must be ${b} ($data)`:p.str`"${w}" keyword is invalid ($data)`};function jF(w,b=pG.keywordError,$,W){let{it:Q}=w,{gen:X,compositeRule:G,allErrors:J}=Q,Y=nG(w,b,$);if(W!==null&&W!==void 0?W:G||J)gG(X,Y);else iG(Q,p._`[${Y}]`)}pG.reportError=jF;function qF(w,b=pG.keywordError,$){let{it:W}=w,{gen:Q,compositeRule:X,allErrors:G}=W,J=nG(w,b,$);if(gG(Q,J),!(X||G))iG(W,jw.default.vErrors)}pG.reportExtraError=qF;function PF(w,b){w.assign(jw.default.errors,b),w.if(p._`${jw.default.vErrors} !== null`,()=>w.if(b,()=>w.assign(p._`${jw.default.vErrors}.length`,b),()=>w.assign(jw.default.vErrors,null)))}pG.resetErrorsCount=PF;function IF({gen:w,keyword:b,schemaValue:$,data:W,errsCount:Q,it:X}){if(Q===void 0)throw Error("ajv implementation error");let G=w.name("err");w.forRange("i",Q,jw.default.errors,(J)=>{if(w.const(G,p._`${jw.default.vErrors}[${J}]`),w.if(p._`${G}.instancePath === undefined`,()=>w.assign(p._`${G}.instancePath`,(0,p.strConcat)(jw.default.instancePath,X.errorPath))),w.assign(p._`${G}.schemaPath`,p.str`${X.errSchemaPath}/${b}`),X.opts.verbose)w.assign(p._`${G}.schema`,$),w.assign(p._`${G}.data`,W)})}pG.extendErrors=IF;function gG(w,b){let $=w.const("err",b);w.if(p._`${jw.default.vErrors} === null`,()=>w.assign(jw.default.vErrors,p._`[${$}]`),p._`${jw.default.vErrors}.push(${$})`),w.code(p._`${jw.default.errors}++`)}function iG(w,b){let{gen:$,validateName:W,schemaEnv:Q}=w;if(Q.$async)$.throw(p._`new ${w.ValidationError}(${b})`);else $.assign(p._`${W}.errors`,b),$.return(!1)}var y1={keyword:new p.Name("keyword"),schemaPath:new p.Name("schemaPath"),params:new p.Name("params"),propertyName:new p.Name("propertyName"),message:new p.Name("message"),schema:new p.Name("schema"),parentSchema:new p.Name("parentSchema")};function nG(w,b,$){let{createErrors:W}=w.it;if(W===!1)return p._`{}`;return NF(w,b,$)}function NF(w,b,$={}){let{gen:W,it:Q}=w,X=[EF(Q,$),TF(w,$)];return RF(w,b,X),W.object(...X)}function EF({errorPath:w},{instancePath:b}){let $=b?p.str`${w}${(0,Z6.getErrorPath)(b,Z6.Type.Str)}`:w;return[jw.default.instancePath,(0,p.strConcat)(jw.default.instancePath,$)]}function TF({keyword:w,it:{errSchemaPath:b}},{schemaPath:$,parentSchema:W}){let Q=W?b:p.str`${b}/${w}`;if($)Q=p.str`${Q}${(0,Z6.getErrorPath)($,Z6.Type.Str)}`;return[y1.schemaPath,Q]}function RF(w,{params:b,message:$},W){let{keyword:Q,data:X,schemaValue:G,it:J}=w,{opts:Y,propertyName:H,topSchemaRef:z,schemaPath:B}=J;if(W.push([y1.keyword,Q],[y1.params,typeof b=="function"?b(w):b||p._`{}`]),Y.messages)W.push([y1.message,typeof $=="function"?$(w):$]);if(Y.verbose)W.push([y1.schema,G],[y1.parentSchema,p._`${z}${B}`],[jw.default.data,X]);if(H)W.push([y1.propertyName,H])}});var sG=I((tG)=>{Object.defineProperty(tG,"__esModule",{value:!0});tG.boolOrEmptySchema=tG.topBoolOrEmptySchema=void 0;var _F=t0(),xF=f(),hF=Y1(),yF={message:"boolean schema is false"};function uF(w){let{gen:b,schema:$,validateName:W}=w;if($===!1)oG(w,!1);else if(typeof $=="object"&&$.$async===!0)b.return(hF.default.data);else b.assign(xF._`${W}.errors`,null),b.return(!0)}tG.topBoolOrEmptySchema=uF;function fF(w,b){let{gen:$,schema:W}=w;if(W===!1)$.var(b,!1),oG(w);else $.var(b,!0)}tG.boolOrEmptySchema=fF;function oG(w,b){let{gen:$,data:W}=w,Q={gen:$,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:w};(0,_F.reportError)(Q,yF,void 0,b)}});var _$=I((eG)=>{Object.defineProperty(eG,"__esModule",{value:!0});eG.getRules=eG.isJSONType=void 0;var mF=["string","number","integer","boolean","null","object","array"],lF=new Set(mF);function gF(w){return typeof w=="string"&&lF.has(w)}eG.isJSONType=gF;function iF(){let w={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...w,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},w.number,w.string,w.array,w.object],post:{rules:[]},all:{},keywords:{}}}eG.getRules=iF});var x$=I(($J)=>{Object.defineProperty($J,"__esModule",{value:!0});$J.shouldUseRule=$J.shouldUseGroup=$J.schemaHasRulesForType=void 0;function pF({schema:w,self:b},$){let W=b.RULES.types[$];return W&&W!==!0&&wJ(w,W)}$J.schemaHasRulesForType=pF;function wJ(w,b){return b.rules.some(($)=>bJ(w,$))}$J.shouldUseGroup=wJ;function bJ(w,b){var $;return w[b.keyword]!==void 0||(($=b.definition.implements)===null||$===void 0?void 0:$.some((W)=>w[W]!==void 0))}$J.shouldUseRule=bJ});var r0=I((JJ)=>{Object.defineProperty(JJ,"__esModule",{value:!0});JJ.reportTypeError=JJ.checkDataTypes=JJ.checkDataType=JJ.coerceAndCheckDataType=JJ.getJSONTypes=JJ.getSchemaTypes=JJ.DataType=void 0;var tF=_$(),rF=x$(),sF=t0(),y=f(),QJ=o(),b0;(function(w){w[w.Correct=0]="Correct",w[w.Wrong=1]="Wrong"})(b0||(JJ.DataType=b0={}));function eF(w){let b=XJ(w.type);if(b.includes("null")){if(w.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!b.length&&w.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(w.nullable===!0)b.push("null")}return b}JJ.getSchemaTypes=eF;function XJ(w){let b=Array.isArray(w)?w:w?[w]:[];if(b.every(tF.isJSONType))return b;throw Error("type must be JSONType or JSONType[]: "+b.join(","))}JJ.getJSONTypes=XJ;function aF(w,b){let{gen:$,data:W,opts:Q}=w,X=wL(b,Q.coerceTypes),G=b.length>0&&!(X.length===0&&b.length===1&&(0,rF.schemaHasRulesForType)(w,b[0]));if(G){let J=y$(b,W,Q.strictNumbers,b0.Wrong);$.if(J,()=>{if(X.length)bL(w,b,X);else u$(w)})}return G}JJ.coerceAndCheckDataType=aF;var GJ=new Set(["string","number","integer","boolean","null"]);function wL(w,b){return b?w.filter(($)=>GJ.has($)||b==="array"&&$==="array"):[]}function bL(w,b,$){let{gen:W,data:Q,opts:X}=w,G=W.let("dataType",y._`typeof ${Q}`),J=W.let("coerced",y._`undefined`);if(X.coerceTypes==="array")W.if(y._`${G} == 'object' && Array.isArray(${Q}) && ${Q}.length == 1`,()=>W.assign(Q,y._`${Q}[0]`).assign(G,y._`typeof ${Q}`).if(y$(b,Q,X.strictNumbers),()=>W.assign(J,Q)));W.if(y._`${J} !== undefined`);for(let H of $)if(GJ.has(H)||H==="array"&&X.coerceTypes==="array")Y(H);W.else(),u$(w),W.endIf(),W.if(y._`${J} !== undefined`,()=>{W.assign(Q,J),$L(w,J)});function Y(H){switch(H){case"string":W.elseIf(y._`${G} == "number" || ${G} == "boolean"`).assign(J,y._`"" + ${Q}`).elseIf(y._`${Q} === null`).assign(J,y._`""`);return;case"number":W.elseIf(y._`${G} == "boolean" || ${Q} === null
4
- || (${G} == "string" && ${Q} && ${Q} == +${Q})`).assign(J,y._`+${Q}`);return;case"integer":W.elseIf(y._`${G} === "boolean" || ${Q} === null
5
- || (${G} === "string" && ${Q} && ${Q} == +${Q} && !(${Q} % 1))`).assign(J,y._`+${Q}`);return;case"boolean":W.elseIf(y._`${Q} === "false" || ${Q} === 0 || ${Q} === null`).assign(J,!1).elseIf(y._`${Q} === "true" || ${Q} === 1`).assign(J,!0);return;case"null":W.elseIf(y._`${Q} === "" || ${Q} === 0 || ${Q} === false`),W.assign(J,null);return;case"array":W.elseIf(y._`${G} === "string" || ${G} === "number"
6
- || ${G} === "boolean" || ${Q} === null`).assign(J,y._`[${Q}]`)}}}function $L({gen:w,parentData:b,parentDataProperty:$},W){w.if(y._`${b} !== undefined`,()=>w.assign(y._`${b}[${$}]`,W))}function h$(w,b,$,W=b0.Correct){let Q=W===b0.Correct?y.operators.EQ:y.operators.NEQ,X;switch(w){case"null":return y._`${b} ${Q} null`;case"array":X=y._`Array.isArray(${b})`;break;case"object":X=y._`${b} && typeof ${b} == "object" && !Array.isArray(${b})`;break;case"integer":X=G(y._`!(${b} % 1) && !isNaN(${b})`);break;case"number":X=G();break;default:return y._`typeof ${b} ${Q} ${w}`}return W===b0.Correct?X:(0,y.not)(X);function G(J=y.nil){return(0,y.and)(y._`typeof ${b} == "number"`,J,$?y._`isFinite(${b})`:y.nil)}}JJ.checkDataType=h$;function y$(w,b,$,W){if(w.length===1)return h$(w[0],b,$,W);let Q,X=(0,QJ.toHash)(w);if(X.array&&X.object){let G=y._`typeof ${b} != "object"`;Q=X.null?G:y._`!${b} || ${G}`,delete X.null,delete X.array,delete X.object}else Q=y.nil;if(X.number)delete X.integer;for(let G in X)Q=(0,y.and)(Q,h$(G,b,$,W));return Q}JJ.checkDataTypes=y$;var WL={message:({schema:w})=>`must be ${w}`,params:({schema:w,schemaValue:b})=>typeof w=="string"?y._`{type: ${w}}`:y._`{type: ${b}}`};function u$(w){let b=QL(w);(0,sF.reportError)(b,WL)}JJ.reportTypeError=u$;function QL(w){let{gen:b,data:$,schema:W}=w,Q=(0,QJ.schemaRefOrVal)(w,W,"type");return{gen:b,keyword:"type",data:$,schema:W.type,schemaCode:Q,schemaValue:Q,parentSchema:W,params:{},it:w}}});var BJ=I((zJ)=>{Object.defineProperty(zJ,"__esModule",{value:!0});zJ.assignDefaults=void 0;var $0=f(),DL=o();function BL(w,b){let{properties:$,items:W}=w.schema;if(b==="object"&&$)for(let Q in $)HJ(w,Q,$[Q].default);else if(b==="array"&&Array.isArray(W))W.forEach((Q,X)=>HJ(w,X,Q.default))}zJ.assignDefaults=BL;function HJ(w,b,$){let{gen:W,compositeRule:Q,data:X,opts:G}=w;if($===void 0)return;let J=$0._`${X}${(0,$0.getProperty)(b)}`;if(Q){(0,DL.checkStrictMode)(w,`default is ignored for: ${J}`);return}let Y=$0._`${J} === undefined`;if(G.useDefaults==="empty")Y=$0._`${Y} || ${J} === null || ${J} === ""`;W.if(Y,$0._`${J} = ${(0,$0.stringify)($)}`)}});var hw=I((LJ)=>{Object.defineProperty(LJ,"__esModule",{value:!0});LJ.validateUnion=LJ.validateArray=LJ.usePattern=LJ.callValidateCode=LJ.schemaProperties=LJ.allSchemaProperties=LJ.noPropertyInData=LJ.propertyInData=LJ.isOwnProperty=LJ.hasPropFunc=LJ.reportMissingProp=LJ.checkMissingProp=LJ.checkReportMissingProp=void 0;var $w=f(),f$=o(),T1=Y1(),AL=o();function FL(w,b){let{gen:$,data:W,it:Q}=w;$.if(m$($,W,b,Q.opts.ownProperties),()=>{w.setParams({missingProperty:$w._`${b}`},!0),w.error()})}LJ.checkReportMissingProp=FL;function LL({gen:w,data:b,it:{opts:$}},W,Q){return(0,$w.or)(...W.map((X)=>(0,$w.and)(m$(w,b,X,$.ownProperties),$w._`${Q} = ${X}`)))}LJ.checkMissingProp=LL;function UL(w,b){w.setParams({missingProperty:b},!0),w.error()}LJ.reportMissingProp=UL;function AJ(w){return w.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:$w._`Object.prototype.hasOwnProperty`})}LJ.hasPropFunc=AJ;function c$(w,b,$){return $w._`${AJ(w)}.call(${b}, ${$})`}LJ.isOwnProperty=c$;function KL(w,b,$,W){let Q=$w._`${b}${(0,$w.getProperty)($)} !== undefined`;return W?$w._`${Q} && ${c$(w,b,$)}`:Q}LJ.propertyInData=KL;function m$(w,b,$,W){let Q=$w._`${b}${(0,$w.getProperty)($)} === undefined`;return W?(0,$w.or)(Q,(0,$w.not)(c$(w,b,$))):Q}LJ.noPropertyInData=m$;function FJ(w){return w?Object.keys(w).filter((b)=>b!=="__proto__"):[]}LJ.allSchemaProperties=FJ;function OL(w,b){return FJ(b).filter(($)=>!(0,f$.alwaysValidSchema)(w,b[$]))}LJ.schemaProperties=OL;function ZL({schemaCode:w,data:b,it:{gen:$,topSchemaRef:W,schemaPath:Q,errorPath:X},it:G},J,Y,H){let z=H?$w._`${w}, ${b}, ${W}${Q}`:b,B=[[T1.default.instancePath,(0,$w.strConcat)(T1.default.instancePath,X)],[T1.default.parentData,G.parentData],[T1.default.parentDataProperty,G.parentDataProperty],[T1.default.rootData,T1.default.rootData]];if(G.opts.dynamicRef)B.push([T1.default.dynamicAnchors,T1.default.dynamicAnchors]);let A=$w._`${z}, ${$.object(...B)}`;return Y!==$w.nil?$w._`${J}.call(${Y}, ${A})`:$w._`${J}(${A})`}LJ.callValidateCode=ZL;var ML=$w._`new RegExp`;function VL({gen:w,it:{opts:b}},$){let W=b.unicodeRegExp?"u":"",{regExp:Q}=b.code,X=Q($,W);return w.scopeValue("pattern",{key:X.toString(),ref:X,code:$w._`${Q.code==="new RegExp"?ML:(0,AL.useFunc)(w,Q)}(${$}, ${W})`})}LJ.usePattern=VL;function jL(w){let{gen:b,data:$,keyword:W,it:Q}=w,X=b.name("valid");if(Q.allErrors){let J=b.let("valid",!0);return G(()=>b.assign(J,!1)),J}return b.var(X,!0),G(()=>b.break()),X;function G(J){let Y=b.const("len",$w._`${$}.length`);b.forRange("i",0,Y,(H)=>{w.subschema({keyword:W,dataProp:H,dataPropType:f$.Type.Num},X),b.if((0,$w.not)(X),J)})}}LJ.validateArray=jL;function qL(w){let{gen:b,schema:$,keyword:W,it:Q}=w;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((Y)=>(0,f$.alwaysValidSchema)(Q,Y))&&!Q.opts.unevaluated)return;let G=b.let("valid",!1),J=b.name("_valid");b.block(()=>$.forEach((Y,H)=>{let z=w.subschema({keyword:W,schemaProp:H,compositeRule:!0},J);if(b.assign(G,$w._`${G} || ${J}`),!w.mergeValidEvaluated(z,J))b.if((0,$w.not)(G))})),w.result(G,()=>w.reset(),()=>w.error(!0))}LJ.validateUnion=qL});var VJ=I((ZJ)=>{Object.defineProperty(ZJ,"__esModule",{value:!0});ZJ.validateKeywordUsage=ZJ.validSchemaType=ZJ.funcKeywordCode=ZJ.macroKeywordCode=void 0;var qw=f(),u1=Y1(),hL=hw(),yL=t0();function uL(w,b){let{gen:$,keyword:W,schema:Q,parentSchema:X,it:G}=w,J=b.macro.call(G.self,Q,X,G),Y=OJ($,W,J);if(G.opts.validateSchema!==!1)G.self.validateSchema(J,!0);let H=$.name("valid");w.subschema({schema:J,schemaPath:qw.nil,errSchemaPath:`${G.errSchemaPath}/${W}`,topSchemaRef:Y,compositeRule:!0},H),w.pass(H,()=>w.error(!0))}ZJ.macroKeywordCode=uL;function fL(w,b){var $;let{gen:W,keyword:Q,schema:X,parentSchema:G,$data:J,it:Y}=w;mL(Y,b);let H=!J&&b.compile?b.compile.call(Y.self,X,G,Y):b.validate,z=OJ(W,Q,H),B=W.let("valid");w.block$data(B,A),w.ok(($=b.valid)!==null&&$!==void 0?$:B);function A(){if(b.errors===!1){if(V(),b.modifying)KJ(w);q(()=>w.error())}else{let P=b.async?F():U();if(b.modifying)KJ(w);q(()=>cL(w,P))}}function F(){let P=W.let("ruleErrs",null);return W.try(()=>V(qw._`await `),(k)=>W.assign(B,!1).if(qw._`${k} instanceof ${Y.ValidationError}`,()=>W.assign(P,qw._`${k}.errors`),()=>W.throw(k))),P}function U(){let P=qw._`${z}.errors`;return W.assign(P,null),V(qw.nil),P}function V(P=b.async?qw._`await `:qw.nil){let k=Y.opts.passContext?u1.default.this:u1.default.self,S=!(("compile"in b)&&!J||b.schema===!1);W.assign(B,qw._`${P}${(0,hL.callValidateCode)(w,z,k,S)}`,b.modifying)}function q(P){var k;W.if((0,qw.not)((k=b.valid)!==null&&k!==void 0?k:B),P)}}ZJ.funcKeywordCode=fL;function KJ(w){let{gen:b,data:$,it:W}=w;b.if(W.parentData,()=>b.assign($,qw._`${W.parentData}[${W.parentDataProperty}]`))}function cL(w,b){let{gen:$}=w;$.if(qw._`Array.isArray(${b})`,()=>{$.assign(u1.default.vErrors,qw._`${u1.default.vErrors} === null ? ${b} : ${u1.default.vErrors}.concat(${b})`).assign(u1.default.errors,qw._`${u1.default.vErrors}.length`),(0,yL.extendErrors)(w)},()=>w.error())}function mL({schemaEnv:w},b){if(b.async&&!w.$async)throw Error("async keyword in sync schema")}function OJ(w,b,$){if($===void 0)throw Error(`keyword "${b}" failed to compile`);return w.scopeValue("keyword",typeof $=="function"?{ref:$}:{ref:$,code:(0,qw.stringify)($)})}function lL(w,b,$=!1){return!b.length||b.some((W)=>W==="array"?Array.isArray(w):W==="object"?w&&typeof w=="object"&&!Array.isArray(w):typeof w==W||$&&typeof w>"u")}ZJ.validSchemaType=lL;function gL({schema:w,opts:b,self:$,errSchemaPath:W},Q,X){if(Array.isArray(Q.keyword)?!Q.keyword.includes(X):Q.keyword!==X)throw Error("ajv implementation error");let G=Q.dependencies;if(G===null||G===void 0?void 0:G.some((J)=>!Object.prototype.hasOwnProperty.call(w,J)))throw Error(`parent schema must have dependencies of ${X}: ${G.join(",")}`);if(Q.validateSchema){if(!Q.validateSchema(w[X])){let Y=`keyword "${X}" value is invalid at path "${W}": `+$.errorsText(Q.validateSchema.errors);if(b.validateSchema==="log")$.logger.error(Y);else throw Error(Y)}}}ZJ.validateKeywordUsage=gL});var IJ=I((qJ)=>{Object.defineProperty(qJ,"__esModule",{value:!0});qJ.extendSubschemaMode=qJ.extendSubschemaData=qJ.getSubschema=void 0;var sw=f(),jJ=o();function dL(w,{keyword:b,schemaProp:$,schema:W,schemaPath:Q,errSchemaPath:X,topSchemaRef:G}){if(b!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(b!==void 0){let J=w.schema[b];return $===void 0?{schema:J,schemaPath:sw._`${w.schemaPath}${(0,sw.getProperty)(b)}`,errSchemaPath:`${w.errSchemaPath}/${b}`}:{schema:J[$],schemaPath:sw._`${w.schemaPath}${(0,sw.getProperty)(b)}${(0,sw.getProperty)($)}`,errSchemaPath:`${w.errSchemaPath}/${b}/${(0,jJ.escapeFragment)($)}`}}if(W!==void 0){if(Q===void 0||X===void 0||G===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:Q,topSchemaRef:G,errSchemaPath:X}}throw Error('either "keyword" or "schema" must be passed')}qJ.getSubschema=dL;function oL(w,b,{dataProp:$,dataPropType:W,data:Q,dataTypes:X,propertyName:G}){if(Q!==void 0&&$!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:J}=b;if($!==void 0){let{errorPath:H,dataPathArr:z,opts:B}=b,A=J.let("data",sw._`${b.data}${(0,sw.getProperty)($)}`,!0);Y(A),w.errorPath=sw.str`${H}${(0,jJ.getErrorPath)($,W,B.jsPropertySyntax)}`,w.parentDataProperty=sw._`${$}`,w.dataPathArr=[...z,w.parentDataProperty]}if(Q!==void 0){let H=Q instanceof sw.Name?Q:J.let("data",Q,!0);if(Y(H),G!==void 0)w.propertyName=G}if(X)w.dataTypes=X;function Y(H){w.data=H,w.dataLevel=b.dataLevel+1,w.dataTypes=[],b.definedProperties=new Set,w.parentData=b.data,w.dataNames=[...b.dataNames,H]}}qJ.extendSubschemaData=oL;function tL(w,{jtdDiscriminator:b,jtdMetadata:$,compositeRule:W,createErrors:Q,allErrors:X}){if(W!==void 0)w.compositeRule=W;if(Q!==void 0)w.createErrors=Q;if(X!==void 0)w.allErrors=X;w.jtdDiscriminator=b,w.jtdMetadata=$}qJ.extendSubschemaMode=tL});var l$=I((rT,NJ)=>{NJ.exports=function w(b,$){if(b===$)return!0;if(b&&$&&typeof b=="object"&&typeof $=="object"){if(b.constructor!==$.constructor)return!1;var W,Q,X;if(Array.isArray(b)){if(W=b.length,W!=$.length)return!1;for(Q=W;Q--!==0;)if(!w(b[Q],$[Q]))return!1;return!0}if(b.constructor===RegExp)return b.source===$.source&&b.flags===$.flags;if(b.valueOf!==Object.prototype.valueOf)return b.valueOf()===$.valueOf();if(b.toString!==Object.prototype.toString)return b.toString()===$.toString();if(X=Object.keys(b),W=X.length,W!==Object.keys($).length)return!1;for(Q=W;Q--!==0;)if(!Object.prototype.hasOwnProperty.call($,X[Q]))return!1;for(Q=W;Q--!==0;){var G=X[Q];if(!w(b[G],$[G]))return!1}return!0}return b!==b&&$!==$}});var TJ=I((sT,EJ)=>{var R1=EJ.exports=function(w,b,$){if(typeof b=="function")$=b,b={};$=b.cb||$;var W=typeof $=="function"?$:$.pre||function(){},Q=$.post||function(){};M6(b,W,Q,w,"",w)};R1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};R1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};R1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};R1.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function M6(w,b,$,W,Q,X,G,J,Y,H){if(W&&typeof W=="object"&&!Array.isArray(W)){b(W,Q,X,G,J,Y,H);for(var z in W){var B=W[z];if(Array.isArray(B)){if(z in R1.arrayKeywords)for(var A=0;A<B.length;A++)M6(w,b,$,B[A],Q+"/"+z+"/"+A,X,Q,z,W,A)}else if(z in R1.propsKeywords){if(B&&typeof B=="object")for(var F in B)M6(w,b,$,B[F],Q+"/"+z+"/"+eL(F),X,Q,z,W,F)}else if(z in R1.keywords||w.allKeys&&!(z in R1.skipKeywords))M6(w,b,$,B,Q+"/"+z,X,Q,z,W)}$(W,Q,X,G,J,Y,H)}}function eL(w){return w.replace(/~/g,"~0").replace(/\//g,"~1")}});var s0=I((CJ)=>{Object.defineProperty(CJ,"__esModule",{value:!0});CJ.getSchemaRefs=CJ.resolveUrl=CJ.normalizeId=CJ._getFullPath=CJ.getFullPath=CJ.inlineRef=void 0;var aL=o(),wU=l$(),bU=TJ(),$U=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function WU(w,b=!0){if(typeof w=="boolean")return!0;if(b===!0)return!g$(w);if(!b)return!1;return RJ(w)<=b}CJ.inlineRef=WU;var QU=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function g$(w){for(let b in w){if(QU.has(b))return!0;let $=w[b];if(Array.isArray($)&&$.some(g$))return!0;if(typeof $=="object"&&g$($))return!0}return!1}function RJ(w){let b=0;for(let $ in w){if($==="$ref")return 1/0;if(b++,$U.has($))continue;if(typeof w[$]=="object")(0,aL.eachItem)(w[$],(W)=>b+=RJ(W));if(b===1/0)return 1/0}return b}function SJ(w,b="",$){if($!==!1)b=W0(b);let W=w.parse(b);return vJ(w,W)}CJ.getFullPath=SJ;function vJ(w,b){return w.serialize(b).split("#")[0]+"#"}CJ._getFullPath=vJ;var XU=/#\/?$/;function W0(w){return w?w.replace(XU,""):""}CJ.normalizeId=W0;function GU(w,b,$){return $=W0($),w.resolve(b,$)}CJ.resolveUrl=GU;var JU=/^[a-z_][-a-z0-9._]*$/i;function YU(w,b){if(typeof w=="boolean")return{};let{schemaId:$,uriResolver:W}=this.opts,Q=W0(w[$]||b),X={"":Q},G=SJ(W,Q,!1),J={},Y=new Set;return bU(w,{allKeys:!0},(B,A,F,U)=>{if(U===void 0)return;let V=G+A,q=X[U];if(typeof B[$]=="string")q=P.call(this,B[$]);k.call(this,B.$anchor),k.call(this,B.$dynamicAnchor),X[A]=q;function P(S){let m=this.opts.uriResolver.resolve;if(S=W0(q?m(q,S):S),Y.has(S))throw z(S);Y.add(S);let _=this.refs[S];if(typeof _=="string")_=this.refs[_];if(typeof _=="object")H(B,_.schema,S);else if(S!==W0(V))if(S[0]==="#")H(B,J[S],S),J[S]=B;else this.refs[S]=V;return S}function k(S){if(typeof S=="string"){if(!JU.test(S))throw Error(`invalid anchor "${S}"`);P.call(this,`#${S}`)}}}),J;function H(B,A,F){if(A!==void 0&&!wU(B,A))throw z(F)}function z(B){return Error(`reference "${B}" resolves to more than one schema`)}}CJ.getSchemaRefs=YU});var wb=I((oJ)=>{Object.defineProperty(oJ,"__esModule",{value:!0});oJ.getData=oJ.KeywordCxt=oJ.validateFunctionCode=void 0;var uJ=sG(),_J=r0(),n$=x$(),V6=r0(),FU=BJ(),a0=VJ(),i$=IJ(),R=f(),x=Y1(),LU=s0(),H1=o(),e0=t0();function UU(w){if(mJ(w)){if(lJ(w),cJ(w)){ZU(w);return}}fJ(w,()=>(0,uJ.topBoolOrEmptySchema)(w))}oJ.validateFunctionCode=UU;function fJ({gen:w,validateName:b,schema:$,schemaEnv:W,opts:Q},X){if(Q.code.es5)w.func(b,R._`${x.default.data}, ${x.default.valCxt}`,W.$async,()=>{w.code(R._`"use strict"; ${xJ($,Q)}`),OU(w,Q),w.code(X)});else w.func(b,R._`${x.default.data}, ${KU(Q)}`,W.$async,()=>w.code(xJ($,Q)).code(X))}function KU(w){return R._`{${x.default.instancePath}="", ${x.default.parentData}, ${x.default.parentDataProperty}, ${x.default.rootData}=${x.default.data}${w.dynamicRef?R._`, ${x.default.dynamicAnchors}={}`:R.nil}}={}`}function OU(w,b){w.if(x.default.valCxt,()=>{if(w.var(x.default.instancePath,R._`${x.default.valCxt}.${x.default.instancePath}`),w.var(x.default.parentData,R._`${x.default.valCxt}.${x.default.parentData}`),w.var(x.default.parentDataProperty,R._`${x.default.valCxt}.${x.default.parentDataProperty}`),w.var(x.default.rootData,R._`${x.default.valCxt}.${x.default.rootData}`),b.dynamicRef)w.var(x.default.dynamicAnchors,R._`${x.default.valCxt}.${x.default.dynamicAnchors}`)},()=>{if(w.var(x.default.instancePath,R._`""`),w.var(x.default.parentData,R._`undefined`),w.var(x.default.parentDataProperty,R._`undefined`),w.var(x.default.rootData,x.default.data),b.dynamicRef)w.var(x.default.dynamicAnchors,R._`{}`)})}function ZU(w){let{schema:b,opts:$,gen:W}=w;fJ(w,()=>{if($.$comment&&b.$comment)iJ(w);if(PU(w),W.let(x.default.vErrors,null),W.let(x.default.errors,0),$.unevaluated)MU(w);gJ(w),EU(w)});return}function MU(w){let{gen:b,validateName:$}=w;w.evaluated=b.const("evaluated",R._`${$}.evaluated`),b.if(R._`${w.evaluated}.dynamicProps`,()=>b.assign(R._`${w.evaluated}.props`,R._`undefined`)),b.if(R._`${w.evaluated}.dynamicItems`,()=>b.assign(R._`${w.evaluated}.items`,R._`undefined`))}function xJ(w,b){let $=typeof w=="object"&&w[b.schemaId];return $&&(b.code.source||b.code.process)?R._`/*# sourceURL=${$} */`:R.nil}function VU(w,b){if(mJ(w)){if(lJ(w),cJ(w)){jU(w,b);return}}(0,uJ.boolOrEmptySchema)(w,b)}function cJ({schema:w,self:b}){if(typeof w=="boolean")return!w;for(let $ in w)if(b.RULES.all[$])return!0;return!1}function mJ(w){return typeof w.schema!="boolean"}function jU(w,b){let{schema:$,gen:W,opts:Q}=w;if(Q.$comment&&$.$comment)iJ(w);IU(w),NU(w);let X=W.const("_errs",x.default.errors);gJ(w,X),W.var(b,R._`${X} === ${x.default.errors}`)}function lJ(w){(0,H1.checkUnknownRules)(w),qU(w)}function gJ(w,b){if(w.opts.jtd)return hJ(w,[],!1,b);let $=(0,_J.getSchemaTypes)(w.schema),W=(0,_J.coerceAndCheckDataType)(w,$);hJ(w,$,!W,b)}function qU(w){let{schema:b,errSchemaPath:$,opts:W,self:Q}=w;if(b.$ref&&W.ignoreKeywordsWithRef&&(0,H1.schemaHasRulesButRef)(b,Q.RULES))Q.logger.warn(`$ref: keywords ignored in schema at path "${$}"`)}function PU(w){let{schema:b,opts:$}=w;if(b.default!==void 0&&$.useDefaults&&$.strictSchema)(0,H1.checkStrictMode)(w,"default is ignored in the schema root")}function IU(w){let b=w.schema[w.opts.schemaId];if(b)w.baseId=(0,LU.resolveUrl)(w.opts.uriResolver,w.baseId,b)}function NU(w){if(w.schema.$async&&!w.schemaEnv.$async)throw Error("async schema in sync schema")}function iJ({gen:w,schemaEnv:b,schema:$,errSchemaPath:W,opts:Q}){let X=$.$comment;if(Q.$comment===!0)w.code(R._`${x.default.self}.logger.log(${X})`);else if(typeof Q.$comment=="function"){let G=R.str`${W}/$comment`,J=w.scopeValue("root",{ref:b.root});w.code(R._`${x.default.self}.opts.$comment(${X}, ${G}, ${J}.schema)`)}}function EU(w){let{gen:b,schemaEnv:$,validateName:W,ValidationError:Q,opts:X}=w;if($.$async)b.if(R._`${x.default.errors} === 0`,()=>b.return(x.default.data),()=>b.throw(R._`new ${Q}(${x.default.vErrors})`));else{if(b.assign(R._`${W}.errors`,x.default.vErrors),X.unevaluated)TU(w);b.return(R._`${x.default.errors} === 0`)}}function TU({gen:w,evaluated:b,props:$,items:W}){if($ instanceof R.Name)w.assign(R._`${b}.props`,$);if(W instanceof R.Name)w.assign(R._`${b}.items`,W)}function hJ(w,b,$,W){let{gen:Q,schema:X,data:G,allErrors:J,opts:Y,self:H}=w,{RULES:z}=H;if(X.$ref&&(Y.ignoreKeywordsWithRef||!(0,H1.schemaHasRulesButRef)(X,z))){Q.block(()=>pJ(w,"$ref",z.all.$ref.definition));return}if(!Y.jtd)RU(w,b);Q.block(()=>{for(let A of z.rules)B(A);B(z.post)});function B(A){if(!(0,n$.shouldUseGroup)(X,A))return;if(A.type){if(Q.if((0,V6.checkDataType)(A.type,G,Y.strictNumbers)),yJ(w,A),b.length===1&&b[0]===A.type&&$)Q.else(),(0,V6.reportTypeError)(w);Q.endIf()}else yJ(w,A);if(!J)Q.if(R._`${x.default.errors} === ${W||0}`)}}function yJ(w,b){let{gen:$,schema:W,opts:{useDefaults:Q}}=w;if(Q)(0,FU.assignDefaults)(w,b.type);$.block(()=>{for(let X of b.rules)if((0,n$.shouldUseRule)(W,X))pJ(w,X.keyword,X.definition,b.type)})}function RU(w,b){if(w.schemaEnv.meta||!w.opts.strictTypes)return;if(SU(w,b),!w.opts.allowUnionTypes)vU(w,b);CU(w,w.dataTypes)}function SU(w,b){if(!b.length)return;if(!w.dataTypes.length){w.dataTypes=b;return}b.forEach(($)=>{if(!nJ(w.dataTypes,$))p$(w,`type "${$}" not allowed by context "${w.dataTypes.join(",")}"`)}),_U(w,b)}function vU(w,b){if(b.length>1&&!(b.length===2&&b.includes("null")))p$(w,"use allowUnionTypes to allow union type keyword")}function CU(w,b){let $=w.self.RULES.all;for(let W in $){let Q=$[W];if(typeof Q=="object"&&(0,n$.shouldUseRule)(w.schema,Q)){let{type:X}=Q.definition;if(X.length&&!X.some((G)=>kU(b,G)))p$(w,`missing type "${X.join(",")}" for keyword "${W}"`)}}}function kU(w,b){return w.includes(b)||b==="number"&&w.includes("integer")}function nJ(w,b){return w.includes(b)||b==="integer"&&w.includes("number")}function _U(w,b){let $=[];for(let W of w.dataTypes)if(nJ(b,W))$.push(W);else if(b.includes("integer")&&W==="number")$.push("integer");w.dataTypes=$}function p$(w,b){let $=w.schemaEnv.baseId+w.errSchemaPath;b+=` at "${$}" (strictTypes)`,(0,H1.checkStrictMode)(w,b,w.opts.strictTypes)}class d${constructor(w,b,$){if((0,a0.validateKeywordUsage)(w,b,$),this.gen=w.gen,this.allErrors=w.allErrors,this.keyword=$,this.data=w.data,this.schema=w.schema[$],this.$data=b.$data&&w.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,H1.schemaRefOrVal)(w,this.schema,$,this.$data),this.schemaType=b.schemaType,this.parentSchema=w.schema,this.params={},this.it=w,this.def=b,this.$data)this.schemaCode=w.gen.const("vSchema",dJ(this.$data,w));else if(this.schemaCode=this.schemaValue,!(0,a0.validSchemaType)(this.schema,b.schemaType,b.allowUndefined))throw Error(`${$} value must be ${JSON.stringify(b.schemaType)}`);if("code"in b?b.trackErrors:b.errors!==!1)this.errsCount=w.gen.const("_errs",x.default.errors)}result(w,b,$){this.failResult((0,R.not)(w),b,$)}failResult(w,b,$){if(this.gen.if(w),$)$();else this.error();if(b){if(this.gen.else(),b(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(w,b){this.failResult((0,R.not)(w),void 0,b)}fail(w){if(w===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(w),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(w){if(!this.$data)return this.fail(w);let{schemaCode:b}=this;this.fail(R._`${b} !== undefined && (${(0,R.or)(this.invalid$data(),w)})`)}error(w,b,$){if(b){this.setParams(b),this._error(w,$),this.setParams({});return}this._error(w,$)}_error(w,b){(w?e0.reportExtraError:e0.reportError)(this,this.def.error,b)}$dataError(){(0,e0.reportError)(this,this.def.$dataError||e0.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,e0.resetErrorsCount)(this.gen,this.errsCount)}ok(w){if(!this.allErrors)this.gen.if(w)}setParams(w,b){if(b)Object.assign(this.params,w);else this.params=w}block$data(w,b,$=R.nil){this.gen.block(()=>{this.check$data(w,$),b()})}check$data(w=R.nil,b=R.nil){if(!this.$data)return;let{gen:$,schemaCode:W,schemaType:Q,def:X}=this;if($.if((0,R.or)(R._`${W} === undefined`,b)),w!==R.nil)$.assign(w,!0);if(Q.length||X.validateSchema){if($.elseIf(this.invalid$data()),this.$dataError(),w!==R.nil)$.assign(w,!1)}$.else()}invalid$data(){let{gen:w,schemaCode:b,schemaType:$,def:W,it:Q}=this;return(0,R.or)(X(),G());function X(){if($.length){if(!(b instanceof R.Name))throw Error("ajv implementation error");let J=Array.isArray($)?$:[$];return R._`${(0,V6.checkDataTypes)(J,b,Q.opts.strictNumbers,V6.DataType.Wrong)}`}return R.nil}function G(){if(W.validateSchema){let J=w.scopeValue("validate$data",{ref:W.validateSchema});return R._`!${J}(${b})`}return R.nil}}subschema(w,b){let $=(0,i$.getSubschema)(this.it,w);(0,i$.extendSubschemaData)($,this.it,w),(0,i$.extendSubschemaMode)($,w);let W={...this.it,...$,items:void 0,props:void 0};return VU(W,b),W}mergeEvaluated(w,b){let{it:$,gen:W}=this;if(!$.opts.unevaluated)return;if($.props!==!0&&w.props!==void 0)$.props=H1.mergeEvaluated.props(W,w.props,$.props,b);if($.items!==!0&&w.items!==void 0)$.items=H1.mergeEvaluated.items(W,w.items,$.items,b)}mergeValidEvaluated(w,b){let{it:$,gen:W}=this;if($.opts.unevaluated&&($.props!==!0||$.items!==!0))return W.if(b,()=>this.mergeEvaluated(w,R.Name)),!0}}oJ.KeywordCxt=d$;function pJ(w,b,$,W){let Q=new d$(w,$,b);if("code"in $)$.code(Q,W);else if(Q.$data&&$.validate)(0,a0.funcKeywordCode)(Q,$);else if("macro"in $)(0,a0.macroKeywordCode)(Q,$);else if($.compile||$.validate)(0,a0.funcKeywordCode)(Q,$)}var xU=/^\/(?:[^~]|~0|~1)*$/,hU=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function dJ(w,{dataLevel:b,dataNames:$,dataPathArr:W}){let Q,X;if(w==="")return x.default.rootData;if(w[0]==="/"){if(!xU.test(w))throw Error(`Invalid JSON-pointer: ${w}`);Q=w,X=x.default.rootData}else{let H=hU.exec(w);if(!H)throw Error(`Invalid JSON-pointer: ${w}`);let z=+H[1];if(Q=H[2],Q==="#"){if(z>=b)throw Error(Y("property/index",z));return W[b-z]}if(z>b)throw Error(Y("data",z));if(X=$[b-z],!Q)return X}let G=X,J=Q.split("/");for(let H of J)if(H)X=R._`${X}${(0,R.getProperty)((0,H1.unescapeJsonPointer)(H))}`,G=R._`${G} && ${X}`;return G;function Y(H,z){return`Cannot access ${H} ${z} levels up, current level is ${b}`}}oJ.getData=dJ});var j6=I((sJ)=>{Object.defineProperty(sJ,"__esModule",{value:!0});class rJ extends Error{constructor(w){super("validation failed");this.errors=w,this.ajv=this.validation=!0}}sJ.default=rJ});var bb=I((aJ)=>{Object.defineProperty(aJ,"__esModule",{value:!0});var o$=s0();class eJ extends Error{constructor(w,b,$,W){super(W||`can't resolve reference ${$} from id ${b}`);this.missingRef=(0,o$.resolveUrl)(w,b,$),this.missingSchema=(0,o$.normalizeId)((0,o$.getFullPath)(w,this.missingRef))}}aJ.default=eJ});var P6=I(($Y)=>{Object.defineProperty($Y,"__esModule",{value:!0});$Y.resolveSchema=$Y.getCompilingSchema=$Y.resolveRef=$Y.compileSchema=$Y.SchemaEnv=void 0;var gw=f(),mU=j6(),f1=Y1(),iw=s0(),wY=o(),lU=wb();class $b{constructor(w){var b;this.refs={},this.dynamicAnchors={};let $;if(typeof w.schema=="object")$=w.schema;this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(b=w.baseId)!==null&&b!==void 0?b:(0,iw.normalizeId)($===null||$===void 0?void 0:$[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=$===null||$===void 0?void 0:$.$async,this.refs={}}}$Y.SchemaEnv=$b;function r$(w){let b=bY.call(this,w);if(b)return b;let $=(0,iw.getFullPath)(this.opts.uriResolver,w.root.baseId),{es5:W,lines:Q}=this.opts.code,{ownProperties:X}=this.opts,G=new gw.CodeGen(this.scope,{es5:W,lines:Q,ownProperties:X}),J;if(w.$async)J=G.scopeValue("Error",{ref:mU.default,code:gw._`require("ajv/dist/runtime/validation_error").default`});let Y=G.scopeName("validate");w.validateName=Y;let H={gen:G,allErrors:this.opts.allErrors,data:f1.default.data,parentData:f1.default.parentData,parentDataProperty:f1.default.parentDataProperty,dataNames:[f1.default.data],dataPathArr:[gw.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:G.scopeValue("schema",this.opts.code.source===!0?{ref:w.schema,code:(0,gw.stringify)(w.schema)}:{ref:w.schema}),validateName:Y,ValidationError:J,schema:w.schema,schemaEnv:w,rootId:$,baseId:w.baseId||$,schemaPath:gw.nil,errSchemaPath:w.schemaPath||(this.opts.jtd?"":"#"),errorPath:gw._`""`,opts:this.opts,self:this},z;try{this._compilations.add(w),(0,lU.validateFunctionCode)(H),G.optimize(this.opts.code.optimize);let B=G.toString();if(z=`${G.scopeRefs(f1.default.scope)}return ${B}`,this.opts.code.process)z=this.opts.code.process(z,w);let F=Function(`${f1.default.self}`,`${f1.default.scope}`,z)(this,this.scope.get());if(this.scope.value(Y,{ref:F}),F.errors=null,F.schema=w.schema,F.schemaEnv=w,w.$async)F.$async=!0;if(this.opts.code.source===!0)F.source={validateName:Y,validateCode:B,scopeValues:G._values};if(this.opts.unevaluated){let{props:U,items:V}=H;if(F.evaluated={props:U instanceof gw.Name?void 0:U,items:V instanceof gw.Name?void 0:V,dynamicProps:U instanceof gw.Name,dynamicItems:V instanceof gw.Name},F.source)F.source.evaluated=(0,gw.stringify)(F.evaluated)}return w.validate=F,w}catch(B){if(delete w.validate,delete w.validateName,z)this.logger.error("Error compiling schema, function code:",z);throw B}finally{this._compilations.delete(w)}}$Y.compileSchema=r$;function gU(w,b,$){var W;$=(0,iw.resolveUrl)(this.opts.uriResolver,b,$);let Q=w.refs[$];if(Q)return Q;let X=pU.call(this,w,$);if(X===void 0){let G=(W=w.localRefs)===null||W===void 0?void 0:W[$],{schemaId:J}=this.opts;if(G)X=new $b({schema:G,schemaId:J,root:w,baseId:b})}if(X===void 0)return;return w.refs[$]=iU.call(this,X)}$Y.resolveRef=gU;function iU(w){if((0,iw.inlineRef)(w.schema,this.opts.inlineRefs))return w.schema;return w.validate?w:r$.call(this,w)}function bY(w){for(let b of this._compilations)if(nU(b,w))return b}$Y.getCompilingSchema=bY;function nU(w,b){return w.schema===b.schema&&w.root===b.root&&w.baseId===b.baseId}function pU(w,b){let $;while(typeof($=this.refs[b])=="string")b=$;return $||this.schemas[b]||q6.call(this,w,b)}function q6(w,b){let $=this.opts.uriResolver.parse(b),W=(0,iw._getFullPath)(this.opts.uriResolver,$),Q=(0,iw.getFullPath)(this.opts.uriResolver,w.baseId,void 0);if(Object.keys(w.schema).length>0&&W===Q)return t$.call(this,$,w);let X=(0,iw.normalizeId)(W),G=this.refs[X]||this.schemas[X];if(typeof G=="string"){let J=q6.call(this,w,G);if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;return t$.call(this,$,J)}if(typeof(G===null||G===void 0?void 0:G.schema)!=="object")return;if(!G.validate)r$.call(this,G);if(X===(0,iw.normalizeId)(b)){let{schema:J}=G,{schemaId:Y}=this.opts,H=J[Y];if(H)Q=(0,iw.resolveUrl)(this.opts.uriResolver,Q,H);return new $b({schema:J,schemaId:Y,root:w,baseId:Q})}return t$.call(this,$,G)}$Y.resolveSchema=q6;var dU=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function t$(w,{baseId:b,schema:$,root:W}){var Q;if(((Q=w.fragment)===null||Q===void 0?void 0:Q[0])!=="/")return;for(let J of w.fragment.slice(1).split("/")){if(typeof $==="boolean")return;let Y=$[(0,wY.unescapeFragment)(J)];if(Y===void 0)return;$=Y;let H=typeof $==="object"&&$[this.opts.schemaId];if(!dU.has(J)&&H)b=(0,iw.resolveUrl)(this.opts.uriResolver,b,H)}let X;if(typeof $!="boolean"&&$.$ref&&!(0,wY.schemaHasRulesButRef)($,this.RULES)){let J=(0,iw.resolveUrl)(this.opts.uriResolver,b,$.$ref);X=q6.call(this,W,J)}let{schemaId:G}=this.opts;if(X=X||new $b({schema:$,schemaId:G,root:W,baseId:b}),X.schema!==X.root.schema)return X;return}});var QY=I((WR,eU)=>{eU.exports={$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:!1}});var e$=I((QR,YY)=>{var aU=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),GY=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function s$(w){let b="",$=0,W=0;for(W=0;W<w.length;W++){if($=w[W].charCodeAt(0),$===48)continue;if(!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";b+=w[W];break}for(W+=1;W<w.length;W++){if($=w[W].charCodeAt(0),!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";b+=w[W]}return b}var wK=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function XY(w){return w.length=0,!0}function bK(w,b,$){if(w.length){let W=s$(w);if(W!=="")b.push(W);else return $.error=!0,!1;w.length=0}return!0}function $K(w){let b=0,$={error:!1,address:"",zone:""},W=[],Q=[],X=!1,G=!1,J=bK;for(let Y=0;Y<w.length;Y++){let H=w[Y];if(H==="["||H==="]")continue;if(H===":"){if(X===!0)G=!0;if(!J(Q,W,$))break;if(++b>7){$.error=!0;break}if(Y>0&&w[Y-1]===":")X=!0;W.push(":");continue}else if(H==="%"){if(!J(Q,W,$))break;J=XY}else{Q.push(H);continue}}if(Q.length)if(J===XY)$.zone=Q.join("");else if(G)W.push(Q.join(""));else W.push(s$(Q));return $.address=W.join(""),$}function JY(w){if(WK(w,":")<2)return{host:w,isIPV6:!1};let b=$K(w);if(!b.error){let{address:$,address:W}=b;if(b.zone)$+="%"+b.zone,W+="%25"+b.zone;return{host:$,isIPV6:!0,escapedHost:W}}else return{host:w,isIPV6:!1}}function WK(w,b){let $=0;for(let W=0;W<w.length;W++)if(w[W]===b)$++;return $}function QK(w){let b=w,$=[],W=-1,Q=0;while(Q=b.length){if(Q===1)if(b===".")break;else if(b==="/"){$.push("/");break}else{$.push(b);break}else if(Q===2){if(b[0]==="."){if(b[1]===".")break;else if(b[1]==="/"){b=b.slice(2);continue}}else if(b[0]==="/"){if(b[1]==="."||b[1]==="/"){$.push("/");break}}}else if(Q===3){if(b==="/.."){if($.length!==0)$.pop();$.push("/");break}}if(b[0]==="."){if(b[1]==="."){if(b[2]==="/"){b=b.slice(3);continue}}else if(b[1]==="/"){b=b.slice(2);continue}}else if(b[0]==="/"){if(b[1]==="."){if(b[2]==="/"){b=b.slice(2);continue}else if(b[2]==="."){if(b[3]==="/"){if(b=b.slice(3),$.length!==0)$.pop();continue}}}}if((W=b.indexOf("/",1))===-1){$.push(b);break}else $.push(b.slice(0,W)),b=b.slice(W)}return $.join("")}function XK(w,b){let $=b!==!0?escape:unescape;if(w.scheme!==void 0)w.scheme=$(w.scheme);if(w.userinfo!==void 0)w.userinfo=$(w.userinfo);if(w.host!==void 0)w.host=$(w.host);if(w.path!==void 0)w.path=$(w.path);if(w.query!==void 0)w.query=$(w.query);if(w.fragment!==void 0)w.fragment=$(w.fragment);return w}function GK(w){let b=[];if(w.userinfo!==void 0)b.push(w.userinfo),b.push("@");if(w.host!==void 0){let $=unescape(w.host);if(!GY($)){let W=JY($);if(W.isIPV6===!0)$=`[${W.escapedHost}]`;else $=w.host}b.push($)}if(typeof w.port==="number"||typeof w.port==="string")b.push(":"),b.push(String(w.port));return b.length?b.join(""):void 0}YY.exports={nonSimpleDomain:wK,recomposeAuthority:GK,normalizeComponentEncoding:XK,removeDotSegments:QK,isIPv4:GY,isUUID:aU,normalizeIPv6:JY,stringArrayToHexStripped:s$}});var AY=I((XR,BY)=>{var{isUUID:JK}=e$(),YK=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,HK=["http","https","ws","wss","urn","urn:uuid"];function zK(w){return HK.indexOf(w)!==-1}function a$(w){if(w.secure===!0)return!0;else if(w.secure===!1)return!1;else if(w.scheme)return w.scheme.length===3&&(w.scheme[0]==="w"||w.scheme[0]==="W")&&(w.scheme[1]==="s"||w.scheme[1]==="S")&&(w.scheme[2]==="s"||w.scheme[2]==="S");else return!1}function HY(w){if(!w.host)w.error=w.error||"HTTP URIs must have a host.";return w}function zY(w){let b=String(w.scheme).toLowerCase()==="https";if(w.port===(b?443:80)||w.port==="")w.port=void 0;if(!w.path)w.path="/";return w}function DK(w){return w.secure=a$(w),w.resourceName=(w.path||"/")+(w.query?"?"+w.query:""),w.path=void 0,w.query=void 0,w}function BK(w){if(w.port===(a$(w)?443:80)||w.port==="")w.port=void 0;if(typeof w.secure==="boolean")w.scheme=w.secure?"wss":"ws",w.secure=void 0;if(w.resourceName){let[b,$]=w.resourceName.split("?");w.path=b&&b!=="/"?b:void 0,w.query=$,w.resourceName=void 0}return w.fragment=void 0,w}function AK(w,b){if(!w.path)return w.error="URN can not be parsed",w;let $=w.path.match(YK);if($){let W=b.scheme||w.scheme||"urn";w.nid=$[1].toLowerCase(),w.nss=$[2];let Q=`${W}:${b.nid||w.nid}`,X=w9(Q);if(w.path=void 0,X)w=X.parse(w,b)}else w.error=w.error||"URN can not be parsed.";return w}function FK(w,b){if(w.nid===void 0)throw Error("URN without nid cannot be serialized");let $=b.scheme||w.scheme||"urn",W=w.nid.toLowerCase(),Q=`${$}:${b.nid||W}`,X=w9(Q);if(X)w=X.serialize(w,b);let G=w,J=w.nss;return G.path=`${W||b.nid}:${J}`,b.skipEscape=!0,G}function LK(w,b){let $=w;if($.uuid=$.nss,$.nss=void 0,!b.tolerant&&(!$.uuid||!JK($.uuid)))$.error=$.error||"UUID is not valid.";return $}function UK(w){let b=w;return b.nss=(w.uuid||"").toLowerCase(),b}var DY={scheme:"http",domainHost:!0,parse:HY,serialize:zY},KK={scheme:"https",domainHost:DY.domainHost,parse:HY,serialize:zY},I6={scheme:"ws",domainHost:!0,parse:DK,serialize:BK},OK={scheme:"wss",domainHost:I6.domainHost,parse:I6.parse,serialize:I6.serialize},ZK={scheme:"urn",parse:AK,serialize:FK,skipNormalize:!0},MK={scheme:"urn:uuid",parse:LK,serialize:UK,skipNormalize:!0},N6={http:DY,https:KK,ws:I6,wss:OK,urn:ZK,"urn:uuid":MK};Object.setPrototypeOf(N6,null);function w9(w){return w&&(N6[w]||N6[w.toLowerCase()])||void 0}BY.exports={wsIsSecure:a$,SCHEMES:N6,isValidSchemeName:zK,getSchemeHandler:w9}});var UY=I((GR,T6)=>{var{normalizeIPv6:VK,removeDotSegments:Wb,recomposeAuthority:jK,normalizeComponentEncoding:E6,isIPv4:qK,nonSimpleDomain:PK}=e$(),{SCHEMES:IK,getSchemeHandler:FY}=AY();function NK(w,b){if(typeof w==="string")w=ew(z1(w,b),b);else if(typeof w==="object")w=z1(ew(w,b),b);return w}function EK(w,b,$){let W=$?Object.assign({scheme:"null"},$):{scheme:"null"},Q=LY(z1(w,W),z1(b,W),W,!0);return W.skipEscape=!0,ew(Q,W)}function LY(w,b,$,W){let Q={};if(!W)w=z1(ew(w,$),$),b=z1(ew(b,$),$);if($=$||{},!$.tolerant&&b.scheme)Q.scheme=b.scheme,Q.userinfo=b.userinfo,Q.host=b.host,Q.port=b.port,Q.path=Wb(b.path||""),Q.query=b.query;else{if(b.userinfo!==void 0||b.host!==void 0||b.port!==void 0)Q.userinfo=b.userinfo,Q.host=b.host,Q.port=b.port,Q.path=Wb(b.path||""),Q.query=b.query;else{if(!b.path)if(Q.path=w.path,b.query!==void 0)Q.query=b.query;else Q.query=w.query;else{if(b.path[0]==="/")Q.path=Wb(b.path);else{if((w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)&&!w.path)Q.path="/"+b.path;else if(!w.path)Q.path=b.path;else Q.path=w.path.slice(0,w.path.lastIndexOf("/")+1)+b.path;Q.path=Wb(Q.path)}Q.query=b.query}Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port}Q.scheme=w.scheme}return Q.fragment=b.fragment,Q}function TK(w,b,$){if(typeof w==="string")w=unescape(w),w=ew(E6(z1(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=ew(E6(w,!0),{...$,skipEscape:!0});if(typeof b==="string")b=unescape(b),b=ew(E6(z1(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=ew(E6(b,!0),{...$,skipEscape:!0});return w.toLowerCase()===b.toLowerCase()}function ew(w,b){let $={host:w.host,scheme:w.scheme,userinfo:w.userinfo,port:w.port,path:w.path,query:w.query,nid:w.nid,nss:w.nss,uuid:w.uuid,fragment:w.fragment,reference:w.reference,resourceName:w.resourceName,secure:w.secure,error:""},W=Object.assign({},b),Q=[],X=FY(W.scheme||$.scheme);if(X&&X.serialize)X.serialize($,W);if($.path!==void 0)if(!W.skipEscape){if($.path=escape($.path),$.scheme!==void 0)$.path=$.path.split("%3A").join(":")}else $.path=unescape($.path);if(W.reference!=="suffix"&&$.scheme)Q.push($.scheme,":");let G=jK($);if(G!==void 0){if(W.reference!=="suffix")Q.push("//");if(Q.push(G),$.path&&$.path[0]!=="/")Q.push("/")}if($.path!==void 0){let J=$.path;if(!W.absolutePath&&(!X||!X.absolutePath))J=Wb(J);if(G===void 0&&J[0]==="/"&&J[1]==="/")J="/%2F"+J.slice(2);Q.push(J)}if($.query!==void 0)Q.push("?",$.query);if($.fragment!==void 0)Q.push("#",$.fragment);return Q.join("")}var RK=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function z1(w,b){let $=Object.assign({},b),W={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},Q=!1;if($.reference==="suffix")if($.scheme)w=$.scheme+":"+w;else w="//"+w;let X=w.match(RK);if(X){if(W.scheme=X[1],W.userinfo=X[3],W.host=X[4],W.port=parseInt(X[5],10),W.path=X[6]||"",W.query=X[7],W.fragment=X[8],isNaN(W.port))W.port=X[5];if(W.host)if(qK(W.host)===!1){let Y=VK(W.host);W.host=Y.host.toLowerCase(),Q=Y.isIPV6}else Q=!0;if(W.scheme===void 0&&W.userinfo===void 0&&W.host===void 0&&W.port===void 0&&W.query===void 0&&!W.path)W.reference="same-document";else if(W.scheme===void 0)W.reference="relative";else if(W.fragment===void 0)W.reference="absolute";else W.reference="uri";if($.reference&&$.reference!=="suffix"&&$.reference!==W.reference)W.error=W.error||"URI is not a "+$.reference+" reference.";let G=FY($.scheme||W.scheme);if(!$.unicodeSupport&&(!G||!G.unicodeSupport)){if(W.host&&($.domainHost||G&&G.domainHost)&&Q===!1&&PK(W.host))try{W.host=URL.domainToASCII(W.host.toLowerCase())}catch(J){W.error=W.error||"Host's domain name can not be converted to ASCII: "+J}}if(!G||G&&!G.skipNormalize){if(w.indexOf("%")!==-1){if(W.scheme!==void 0)W.scheme=unescape(W.scheme);if(W.host!==void 0)W.host=unescape(W.host)}if(W.path)W.path=escape(unescape(W.path));if(W.fragment)W.fragment=encodeURI(decodeURIComponent(W.fragment))}if(G&&G.parse)G.parse(W,$)}else W.error=W.error||"URI can not be parsed.";return W}var b9={SCHEMES:IK,normalize:NK,resolve:EK,resolveComponent:LY,equal:TK,serialize:ew,parse:z1};T6.exports=b9;T6.exports.default=b9;T6.exports.fastUri=b9});var ZY=I((OY)=>{Object.defineProperty(OY,"__esModule",{value:!0});var KY=UY();KY.code='require("ajv/dist/runtime/uri").default';OY.default=KY});var EY=I((D1)=>{Object.defineProperty(D1,"__esModule",{value:!0});D1.CodeGen=D1.Name=D1.nil=D1.stringify=D1.str=D1._=D1.KeywordCxt=void 0;var vK=wb();Object.defineProperty(D1,"KeywordCxt",{enumerable:!0,get:function(){return vK.KeywordCxt}});var Q0=f();Object.defineProperty(D1,"_",{enumerable:!0,get:function(){return Q0._}});Object.defineProperty(D1,"str",{enumerable:!0,get:function(){return Q0.str}});Object.defineProperty(D1,"stringify",{enumerable:!0,get:function(){return Q0.stringify}});Object.defineProperty(D1,"nil",{enumerable:!0,get:function(){return Q0.nil}});Object.defineProperty(D1,"Name",{enumerable:!0,get:function(){return Q0.Name}});Object.defineProperty(D1,"CodeGen",{enumerable:!0,get:function(){return Q0.CodeGen}});var CK=j6(),PY=bb(),kK=_$(),Qb=P6(),_K=f(),Xb=s0(),R6=r0(),W9=o(),MY=QY(),xK=ZY(),IY=(w,b)=>new RegExp(w,b);IY.code="new RegExp";var hK=["removeAdditional","useDefaults","coerceTypes"],yK=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),uK={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},fK={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},VY=200;function cK(w){var b,$,W,Q,X,G,J,Y,H,z,B,A,F,U,V,q,P,k,S,m,_,tw,$1,z4,D4;let Z0=w.strict,B4=(b=w.code)===null||b===void 0?void 0:b.optimize,HW=B4===!0||B4===void 0?1:B4||0,zW=(W=($=w.code)===null||$===void 0?void 0:$.regExp)!==null&&W!==void 0?W:IY,y3=(Q=w.uriResolver)!==null&&Q!==void 0?Q:xK.default;return{strictSchema:(G=(X=w.strictSchema)!==null&&X!==void 0?X:Z0)!==null&&G!==void 0?G:!0,strictNumbers:(Y=(J=w.strictNumbers)!==null&&J!==void 0?J:Z0)!==null&&Y!==void 0?Y:!0,strictTypes:(z=(H=w.strictTypes)!==null&&H!==void 0?H:Z0)!==null&&z!==void 0?z:"log",strictTuples:(A=(B=w.strictTuples)!==null&&B!==void 0?B:Z0)!==null&&A!==void 0?A:"log",strictRequired:(U=(F=w.strictRequired)!==null&&F!==void 0?F:Z0)!==null&&U!==void 0?U:!1,code:w.code?{...w.code,optimize:HW,regExp:zW}:{optimize:HW,regExp:zW},loopRequired:(V=w.loopRequired)!==null&&V!==void 0?V:VY,loopEnum:(q=w.loopEnum)!==null&&q!==void 0?q:VY,meta:(P=w.meta)!==null&&P!==void 0?P:!0,messages:(k=w.messages)!==null&&k!==void 0?k:!0,inlineRefs:(S=w.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(m=w.schemaId)!==null&&m!==void 0?m:"$id",addUsedSchema:(_=w.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(tw=w.validateSchema)!==null&&tw!==void 0?tw:!0,validateFormats:($1=w.validateFormats)!==null&&$1!==void 0?$1:!0,unicodeRegExp:(z4=w.unicodeRegExp)!==null&&z4!==void 0?z4:!0,int32range:(D4=w.int32range)!==null&&D4!==void 0?D4:!0,uriResolver:y3}}class S6{constructor(w={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,w=this.opts={...w,...cK(w)};let{es5:b,lines:$}=this.opts.code;this.scope=new _K.ValueScope({scope:{},prefixes:yK,es5:b,lines:$}),this.logger=pK(w.logger);let W=w.validateFormats;if(w.validateFormats=!1,this.RULES=(0,kK.getRules)(),jY.call(this,uK,w,"NOT SUPPORTED"),jY.call(this,fK,w,"DEPRECATED","warn"),this._metaOpts=iK.call(this),w.formats)lK.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),w.keywords)gK.call(this,w.keywords);if(typeof w.meta=="object")this.addMetaSchema(w.meta);mK.call(this),w.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:w,meta:b,schemaId:$}=this.opts,W=MY;if($==="id")W={...MY},W.id=W.$id,delete W.$id;if(b&&w)this.addMetaSchema(W,W[$],!1)}defaultMeta(){let{meta:w,schemaId:b}=this.opts;return this.opts.defaultMeta=typeof w=="object"?w[b]||w:void 0}validate(w,b){let $;if(typeof w=="string"){if($=this.getSchema(w),!$)throw Error(`no schema with key or ref "${w}"`)}else $=this.compile(w);let W=$(b);if(!("$async"in $))this.errors=$.errors;return W}compile(w,b){let $=this._addSchema(w,b);return $.validate||this._compileSchemaEnv($)}compileAsync(w,b){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:$}=this.opts;return W.call(this,w,b);async function W(H,z){await Q.call(this,H.$schema);let B=this._addSchema(H,z);return B.validate||X.call(this,B)}async function Q(H){if(H&&!this.getSchema(H))await W.call(this,{$ref:H},!0)}async function X(H){try{return this._compileSchemaEnv(H)}catch(z){if(!(z instanceof PY.default))throw z;return G.call(this,z),await J.call(this,z.missingSchema),X.call(this,H)}}function G({missingSchema:H,missingRef:z}){if(this.refs[H])throw Error(`AnySchema ${H} is loaded but ${z} cannot be resolved`)}async function J(H){let z=await Y.call(this,H);if(!this.refs[H])await Q.call(this,z.$schema);if(!this.refs[H])this.addSchema(z,H,b)}async function Y(H){let z=this._loading[H];if(z)return z;try{return await(this._loading[H]=$(H))}finally{delete this._loading[H]}}}addSchema(w,b,$,W=this.opts.validateSchema){if(Array.isArray(w)){for(let X of w)this.addSchema(X,void 0,$,W);return this}let Q;if(typeof w==="object"){let{schemaId:X}=this.opts;if(Q=w[X],Q!==void 0&&typeof Q!="string")throw Error(`schema ${X} must be string`)}return b=(0,Xb.normalizeId)(b||Q),this._checkUnique(b),this.schemas[b]=this._addSchema(w,$,b,W,!0),this}addMetaSchema(w,b,$=this.opts.validateSchema){return this.addSchema(w,b,!0,$),this}validateSchema(w,b){if(typeof w=="boolean")return!0;let $;if($=w.$schema,$!==void 0&&typeof $!="string")throw Error("$schema must be a string");if($=$||this.opts.defaultMeta||this.defaultMeta(),!$)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let W=this.validate($,w);if(!W&&b){let Q="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(Q);else throw Error(Q)}return W}getSchema(w){let b;while(typeof(b=qY.call(this,w))=="string")w=b;if(b===void 0){let{schemaId:$}=this.opts,W=new Qb.SchemaEnv({schema:{},schemaId:$});if(b=Qb.resolveSchema.call(this,W,w),!b)return;this.refs[w]=b}return b.validate||this._compileSchemaEnv(b)}removeSchema(w){if(w instanceof RegExp)return this._removeAllSchemas(this.schemas,w),this._removeAllSchemas(this.refs,w),this;switch(typeof w){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let b=qY.call(this,w);if(typeof b=="object")this._cache.delete(b.schema);return delete this.schemas[w],delete this.refs[w],this}case"object":{let b=w;this._cache.delete(b);let $=w[this.opts.schemaId];if($)$=(0,Xb.normalizeId)($),delete this.schemas[$],delete this.refs[$];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(w){for(let b of w)this.addKeyword(b);return this}addKeyword(w,b){let $;if(typeof w=="string"){if($=w,typeof b=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),b.keyword=$}else if(typeof w=="object"&&b===void 0){if(b=w,$=b.keyword,Array.isArray($)&&!$.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(oK.call(this,$,b),!b)return(0,W9.eachItem)($,(Q)=>$9.call(this,Q)),this;rK.call(this,b);let W={...b,type:(0,R6.getJSONTypes)(b.type),schemaType:(0,R6.getJSONTypes)(b.schemaType)};return(0,W9.eachItem)($,W.type.length===0?(Q)=>$9.call(this,Q,W):(Q)=>W.type.forEach((X)=>$9.call(this,Q,W,X))),this}getKeyword(w){let b=this.RULES.all[w];return typeof b=="object"?b.definition:!!b}removeKeyword(w){let{RULES:b}=this;delete b.keywords[w],delete b.all[w];for(let $ of b.rules){let W=$.rules.findIndex((Q)=>Q.keyword===w);if(W>=0)$.rules.splice(W,1)}return this}addFormat(w,b){if(typeof b=="string")b=new RegExp(b);return this.formats[w]=b,this}errorsText(w=this.errors,{separator:b=", ",dataVar:$="data"}={}){if(!w||w.length===0)return"No errors";return w.map((W)=>`${$}${W.instancePath} ${W.message}`).reduce((W,Q)=>W+b+Q)}$dataMetaSchema(w,b){let $=this.RULES.all;w=JSON.parse(JSON.stringify(w));for(let W of b){let Q=W.split("/").slice(1),X=w;for(let G of Q)X=X[G];for(let G in $){let J=$[G];if(typeof J!="object")continue;let{$data:Y}=J.definition,H=X[G];if(Y&&H)X[G]=NY(H)}}return w}_removeAllSchemas(w,b){for(let $ in w){let W=w[$];if(!b||b.test($)){if(typeof W=="string")delete w[$];else if(W&&!W.meta)this._cache.delete(W.schema),delete w[$]}}}_addSchema(w,b,$,W=this.opts.validateSchema,Q=this.opts.addUsedSchema){let X,{schemaId:G}=this.opts;if(typeof w=="object")X=w[G];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof w!="boolean")throw Error("schema must be object or boolean");let J=this._cache.get(w);if(J!==void 0)return J;$=(0,Xb.normalizeId)(X||$);let Y=Xb.getSchemaRefs.call(this,w,$);if(J=new Qb.SchemaEnv({schema:w,schemaId:G,meta:b,baseId:$,localRefs:Y}),this._cache.set(J.schema,J),Q&&!$.startsWith("#")){if($)this._checkUnique($);this.refs[$]=J}if(W)this.validateSchema(w,!0);return J}_checkUnique(w){if(this.schemas[w]||this.refs[w])throw Error(`schema with key or id "${w}" already exists`)}_compileSchemaEnv(w){if(w.meta)this._compileMetaSchema(w);else Qb.compileSchema.call(this,w);if(!w.validate)throw Error("ajv implementation error");return w.validate}_compileMetaSchema(w){let b=this.opts;this.opts=this._metaOpts;try{Qb.compileSchema.call(this,w)}finally{this.opts=b}}}S6.ValidationError=CK.default;S6.MissingRefError=PY.default;D1.default=S6;function jY(w,b,$,W="error"){for(let Q in w){let X=Q;if(X in b)this.logger[W](`${$}: option ${Q}. ${w[X]}`)}}function qY(w){return w=(0,Xb.normalizeId)(w),this.schemas[w]||this.refs[w]}function mK(){let w=this.opts.schemas;if(!w)return;if(Array.isArray(w))this.addSchema(w);else for(let b in w)this.addSchema(w[b],b)}function lK(){for(let w in this.opts.formats){let b=this.opts.formats[w];if(b)this.addFormat(w,b)}}function gK(w){if(Array.isArray(w)){this.addVocabulary(w);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let b in w){let $=w[b];if(!$.keyword)$.keyword=b;this.addKeyword($)}}function iK(){let w={...this.opts};for(let b of hK)delete w[b];return w}var nK={log(){},warn(){},error(){}};function pK(w){if(w===!1)return nK;if(w===void 0)return console;if(w.log&&w.warn&&w.error)return w;throw Error("logger must implement log, warn and error methods")}var dK=/^[a-z_$][a-z0-9_$:-]*$/i;function oK(w,b){let{RULES:$}=this;if((0,W9.eachItem)(w,(W)=>{if($.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!dK.test(W))throw Error(`Keyword ${W} has invalid name`)}),!b)return;if(b.$data&&!(("code"in b)||("validate"in b)))throw Error('$data keyword must have "code" or "validate" function')}function $9(w,b,$){var W;let Q=b===null||b===void 0?void 0:b.post;if($&&Q)throw Error('keyword with "post" flag cannot have "type"');let{RULES:X}=this,G=Q?X.post:X.rules.find(({type:Y})=>Y===$);if(!G)G={type:$,rules:[]},X.rules.push(G);if(X.keywords[w]=!0,!b)return;let J={keyword:w,definition:{...b,type:(0,R6.getJSONTypes)(b.type),schemaType:(0,R6.getJSONTypes)(b.schemaType)}};if(b.before)tK.call(this,G,J,b.before);else G.rules.push(J);X.all[w]=J,(W=b.implements)===null||W===void 0||W.forEach((Y)=>this.addKeyword(Y))}function tK(w,b,$){let W=w.rules.findIndex((Q)=>Q.keyword===$);if(W>=0)w.rules.splice(W,0,b);else w.rules.push(b),this.logger.warn(`rule ${$} is not defined`)}function rK(w){let{metaSchema:b}=w;if(b===void 0)return;if(w.$data&&this.opts.$data)b=NY(b);w.validateSchema=this.compile(b,!0)}var sK={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function NY(w){return{anyOf:[w,sK]}}});var RY=I((TY)=>{Object.defineProperty(TY,"__esModule",{value:!0});var wO={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};TY.default=wO});var xY=I((kY)=>{Object.defineProperty(kY,"__esModule",{value:!0});kY.callRef=kY.getValidate=void 0;var $O=bb(),SY=hw(),Ew=f(),X0=Y1(),vY=P6(),v6=o(),WO={keyword:"$ref",schemaType:"string",code(w){let{gen:b,schema:$,it:W}=w,{baseId:Q,schemaEnv:X,validateName:G,opts:J,self:Y}=W,{root:H}=X;if(($==="#"||$==="#/")&&Q===H.baseId)return B();let z=vY.resolveRef.call(Y,H,Q,$);if(z===void 0)throw new $O.default(W.opts.uriResolver,Q,$);if(z instanceof vY.SchemaEnv)return A(z);return F(z);function B(){if(X===H)return C6(w,G,X,X.$async);let U=b.scopeValue("root",{ref:H});return C6(w,Ew._`${U}.validate`,H,H.$async)}function A(U){let V=CY(w,U);C6(w,V,U,U.$async)}function F(U){let V=b.scopeValue("schema",J.code.source===!0?{ref:U,code:(0,Ew.stringify)(U)}:{ref:U}),q=b.name("valid"),P=w.subschema({schema:U,dataTypes:[],schemaPath:Ew.nil,topSchemaRef:V,errSchemaPath:$},q);w.mergeEvaluated(P),w.ok(q)}}};function CY(w,b){let{gen:$}=w;return b.validate?$.scopeValue("validate",{ref:b.validate}):Ew._`${$.scopeValue("wrapper",{ref:b})}.validate`}kY.getValidate=CY;function C6(w,b,$,W){let{gen:Q,it:X}=w,{allErrors:G,schemaEnv:J,opts:Y}=X,H=Y.passContext?X0.default.this:Ew.nil;if(W)z();else B();function z(){if(!J.$async)throw Error("async schema referenced by sync schema");let U=Q.let("valid");Q.try(()=>{if(Q.code(Ew._`await ${(0,SY.callValidateCode)(w,b,H)}`),F(b),!G)Q.assign(U,!0)},(V)=>{if(Q.if(Ew._`!(${V} instanceof ${X.ValidationError})`,()=>Q.throw(V)),A(V),!G)Q.assign(U,!1)}),w.ok(U)}function B(){w.result((0,SY.callValidateCode)(w,b,H),()=>F(b),()=>A(b))}function A(U){let V=Ew._`${U}.errors`;Q.assign(X0.default.vErrors,Ew._`${X0.default.vErrors} === null ? ${V} : ${X0.default.vErrors}.concat(${V})`),Q.assign(X0.default.errors,Ew._`${X0.default.vErrors}.length`)}function F(U){var V;if(!X.opts.unevaluated)return;let q=(V=$===null||$===void 0?void 0:$.validate)===null||V===void 0?void 0:V.evaluated;if(X.props!==!0)if(q&&!q.dynamicProps){if(q.props!==void 0)X.props=v6.mergeEvaluated.props(Q,q.props,X.props)}else{let P=Q.var("props",Ew._`${U}.evaluated.props`);X.props=v6.mergeEvaluated.props(Q,P,X.props,Ew.Name)}if(X.items!==!0)if(q&&!q.dynamicItems){if(q.items!==void 0)X.items=v6.mergeEvaluated.items(Q,q.items,X.items)}else{let P=Q.var("items",Ew._`${U}.evaluated.items`);X.items=v6.mergeEvaluated.items(Q,P,X.items,Ew.Name)}}}kY.callRef=C6;kY.default=WO});var yY=I((hY)=>{Object.defineProperty(hY,"__esModule",{value:!0});var GO=RY(),JO=xY(),YO=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",GO.default,JO.default];hY.default=YO});var fY=I((uY)=>{Object.defineProperty(uY,"__esModule",{value:!0});var k6=f(),S1=k6.operators,_6={maximum:{okStr:"<=",ok:S1.LTE,fail:S1.GT},minimum:{okStr:">=",ok:S1.GTE,fail:S1.LT},exclusiveMaximum:{okStr:"<",ok:S1.LT,fail:S1.GTE},exclusiveMinimum:{okStr:">",ok:S1.GT,fail:S1.LTE}},zO={message:({keyword:w,schemaCode:b})=>k6.str`must be ${_6[w].okStr} ${b}`,params:({keyword:w,schemaCode:b})=>k6._`{comparison: ${_6[w].okStr}, limit: ${b}}`},DO={keyword:Object.keys(_6),type:"number",schemaType:"number",$data:!0,error:zO,code(w){let{keyword:b,data:$,schemaCode:W}=w;w.fail$data(k6._`${$} ${_6[b].fail} ${W} || isNaN(${$})`)}};uY.default=DO});var mY=I((cY)=>{Object.defineProperty(cY,"__esModule",{value:!0});var Gb=f(),AO={message:({schemaCode:w})=>Gb.str`must be multiple of ${w}`,params:({schemaCode:w})=>Gb._`{multipleOf: ${w}}`},FO={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:AO,code(w){let{gen:b,data:$,schemaCode:W,it:Q}=w,X=Q.opts.multipleOfPrecision,G=b.let("res"),J=X?Gb._`Math.abs(Math.round(${G}) - ${G}) > 1e-${X}`:Gb._`${G} !== parseInt(${G})`;w.fail$data(Gb._`(${W} === 0 || (${G} = ${$}/${W}, ${J}))`)}};cY.default=FO});var iY=I((gY)=>{Object.defineProperty(gY,"__esModule",{value:!0});function lY(w){let b=w.length,$=0,W=0,Q;while(W<b)if($++,Q=w.charCodeAt(W++),Q>=55296&&Q<=56319&&W<b){if(Q=w.charCodeAt(W),(Q&64512)===56320)W++}return $}gY.default=lY;lY.code='require("ajv/dist/runtime/ucs2length").default'});var pY=I((nY)=>{Object.defineProperty(nY,"__esModule",{value:!0});var c1=f(),KO=o(),OO=iY(),ZO={message({keyword:w,schemaCode:b}){let $=w==="maxLength"?"more":"fewer";return c1.str`must NOT have ${$} than ${b} characters`},params:({schemaCode:w})=>c1._`{limit: ${w}}`},MO={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ZO,code(w){let{keyword:b,data:$,schemaCode:W,it:Q}=w,X=b==="maxLength"?c1.operators.GT:c1.operators.LT,G=Q.opts.unicode===!1?c1._`${$}.length`:c1._`${(0,KO.useFunc)(w.gen,OO.default)}(${$})`;w.fail$data(c1._`${G} ${X} ${W}`)}};nY.default=MO});var oY=I((dY)=>{Object.defineProperty(dY,"__esModule",{value:!0});var jO=hw(),x6=f(),qO={message:({schemaCode:w})=>x6.str`must match pattern "${w}"`,params:({schemaCode:w})=>x6._`{pattern: ${w}}`},PO={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:qO,code(w){let{data:b,$data:$,schema:W,schemaCode:Q,it:X}=w,G=X.opts.unicodeRegExp?"u":"",J=$?x6._`(new RegExp(${Q}, ${G}))`:(0,jO.usePattern)(w,W);w.fail$data(x6._`!${J}.test(${b})`)}};dY.default=PO});var rY=I((tY)=>{Object.defineProperty(tY,"__esModule",{value:!0});var Jb=f(),NO={message({keyword:w,schemaCode:b}){let $=w==="maxProperties"?"more":"fewer";return Jb.str`must NOT have ${$} than ${b} properties`},params:({schemaCode:w})=>Jb._`{limit: ${w}}`},EO={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:NO,code(w){let{keyword:b,data:$,schemaCode:W}=w,Q=b==="maxProperties"?Jb.operators.GT:Jb.operators.LT;w.fail$data(Jb._`Object.keys(${$}).length ${Q} ${W}`)}};tY.default=EO});var eY=I((sY)=>{Object.defineProperty(sY,"__esModule",{value:!0});var Yb=hw(),Hb=f(),RO=o(),SO={message:({params:{missingProperty:w}})=>Hb.str`must have required property '${w}'`,params:({params:{missingProperty:w}})=>Hb._`{missingProperty: ${w}}`},vO={keyword:"required",type:"object",schemaType:"array",$data:!0,error:SO,code(w){let{gen:b,schema:$,schemaCode:W,data:Q,$data:X,it:G}=w,{opts:J}=G;if(!X&&$.length===0)return;let Y=$.length>=J.loopRequired;if(G.allErrors)H();else z();if(J.strictRequired){let F=w.parentSchema.properties,{definedProperties:U}=w.it;for(let V of $)if((F===null||F===void 0?void 0:F[V])===void 0&&!U.has(V)){let q=G.schemaEnv.baseId+G.errSchemaPath,P=`required property "${V}" is not defined at "${q}" (strictRequired)`;(0,RO.checkStrictMode)(G,P,G.opts.strictRequired)}}function H(){if(Y||X)w.block$data(Hb.nil,B);else for(let F of $)(0,Yb.checkReportMissingProp)(w,F)}function z(){let F=b.let("missing");if(Y||X){let U=b.let("valid",!0);w.block$data(U,()=>A(F,U)),w.ok(U)}else b.if((0,Yb.checkMissingProp)(w,$,F)),(0,Yb.reportMissingProp)(w,F),b.else()}function B(){b.forOf("prop",W,(F)=>{w.setParams({missingProperty:F}),b.if((0,Yb.noPropertyInData)(b,Q,F,J.ownProperties),()=>w.error())})}function A(F,U){w.setParams({missingProperty:F}),b.forOf(F,W,()=>{b.assign(U,(0,Yb.propertyInData)(b,Q,F,J.ownProperties)),b.if((0,Hb.not)(U),()=>{w.error(),b.break()})},Hb.nil)}}};sY.default=vO});var w7=I((aY)=>{Object.defineProperty(aY,"__esModule",{value:!0});var zb=f(),kO={message({keyword:w,schemaCode:b}){let $=w==="maxItems"?"more":"fewer";return zb.str`must NOT have ${$} than ${b} items`},params:({schemaCode:w})=>zb._`{limit: ${w}}`},_O={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:kO,code(w){let{keyword:b,data:$,schemaCode:W}=w,Q=b==="maxItems"?zb.operators.GT:zb.operators.LT;w.fail$data(zb._`${$}.length ${Q} ${W}`)}};aY.default=_O});var h6=I(($7)=>{Object.defineProperty($7,"__esModule",{value:!0});var b7=l$();b7.code='require("ajv/dist/runtime/equal").default';$7.default=b7});var Q7=I((W7)=>{Object.defineProperty(W7,"__esModule",{value:!0});var Q9=r0(),Zw=f(),yO=o(),uO=h6(),fO={message:({params:{i:w,j:b}})=>Zw.str`must NOT have duplicate items (items ## ${b} and ${w} are identical)`,params:({params:{i:w,j:b}})=>Zw._`{i: ${w}, j: ${b}}`},cO={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:fO,code(w){let{gen:b,data:$,$data:W,schema:Q,parentSchema:X,schemaCode:G,it:J}=w;if(!W&&!Q)return;let Y=b.let("valid"),H=X.items?(0,Q9.getSchemaTypes)(X.items):[];w.block$data(Y,z,Zw._`${G} === false`),w.ok(Y);function z(){let U=b.let("i",Zw._`${$}.length`),V=b.let("j");w.setParams({i:U,j:V}),b.assign(Y,!0),b.if(Zw._`${U} > 1`,()=>(B()?A:F)(U,V))}function B(){return H.length>0&&!H.some((U)=>U==="object"||U==="array")}function A(U,V){let q=b.name("item"),P=(0,Q9.checkDataTypes)(H,q,J.opts.strictNumbers,Q9.DataType.Wrong),k=b.const("indices",Zw._`{}`);b.for(Zw._`;${U}--;`,()=>{if(b.let(q,Zw._`${$}[${U}]`),b.if(P,Zw._`continue`),H.length>1)b.if(Zw._`typeof ${q} == "string"`,Zw._`${q} += "_"`);b.if(Zw._`typeof ${k}[${q}] == "number"`,()=>{b.assign(V,Zw._`${k}[${q}]`),w.error(),b.assign(Y,!1).break()}).code(Zw._`${k}[${q}] = ${U}`)})}function F(U,V){let q=(0,yO.useFunc)(b,uO.default),P=b.name("outer");b.label(P).for(Zw._`;${U}--;`,()=>b.for(Zw._`${V} = ${U}; ${V}--;`,()=>b.if(Zw._`${q}(${$}[${U}], ${$}[${V}])`,()=>{w.error(),b.assign(Y,!1).break(P)})))}}};W7.default=cO});var G7=I((X7)=>{Object.defineProperty(X7,"__esModule",{value:!0});var X9=f(),lO=o(),gO=h6(),iO={message:"must be equal to constant",params:({schemaCode:w})=>X9._`{allowedValue: ${w}}`},nO={keyword:"const",$data:!0,error:iO,code(w){let{gen:b,data:$,$data:W,schemaCode:Q,schema:X}=w;if(W||X&&typeof X=="object")w.fail$data(X9._`!${(0,lO.useFunc)(b,gO.default)}(${$}, ${Q})`);else w.fail(X9._`${X} !== ${$}`)}};X7.default=nO});var Y7=I((J7)=>{Object.defineProperty(J7,"__esModule",{value:!0});var Db=f(),dO=o(),oO=h6(),tO={message:"must be equal to one of the allowed values",params:({schemaCode:w})=>Db._`{allowedValues: ${w}}`},rO={keyword:"enum",schemaType:"array",$data:!0,error:tO,code(w){let{gen:b,data:$,$data:W,schema:Q,schemaCode:X,it:G}=w;if(!W&&Q.length===0)throw Error("enum must have non-empty array");let J=Q.length>=G.opts.loopEnum,Y,H=()=>Y!==null&&Y!==void 0?Y:Y=(0,dO.useFunc)(b,oO.default),z;if(J||W)z=b.let("valid"),w.block$data(z,B);else{if(!Array.isArray(Q))throw Error("ajv implementation error");let F=b.const("vSchema",X);z=(0,Db.or)(...Q.map((U,V)=>A(F,V)))}w.pass(z);function B(){b.assign(z,!1),b.forOf("v",X,(F)=>b.if(Db._`${H()}(${$}, ${F})`,()=>b.assign(z,!0).break()))}function A(F,U){let V=Q[U];return typeof V==="object"&&V!==null?Db._`${H()}(${$}, ${F}[${U}])`:Db._`${$} === ${V}`}}};J7.default=rO});var z7=I((H7)=>{Object.defineProperty(H7,"__esModule",{value:!0});var eO=fY(),aO=mY(),wZ=pY(),bZ=oY(),$Z=rY(),WZ=eY(),QZ=w7(),XZ=Q7(),GZ=G7(),JZ=Y7(),YZ=[eO.default,aO.default,wZ.default,bZ.default,$Z.default,WZ.default,QZ.default,XZ.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},GZ.default,JZ.default];H7.default=YZ});var J9=I((B7)=>{Object.defineProperty(B7,"__esModule",{value:!0});B7.validateAdditionalItems=void 0;var m1=f(),G9=o(),zZ={message:({params:{len:w}})=>m1.str`must NOT have more than ${w} items`,params:({params:{len:w}})=>m1._`{limit: ${w}}`},DZ={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:zZ,code(w){let{parentSchema:b,it:$}=w,{items:W}=b;if(!Array.isArray(W)){(0,G9.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}D7(w,W)}};function D7(w,b){let{gen:$,schema:W,data:Q,keyword:X,it:G}=w;G.items=!0;let J=$.const("len",m1._`${Q}.length`);if(W===!1)w.setParams({len:b.length}),w.pass(m1._`${J} <= ${b.length}`);else if(typeof W=="object"&&!(0,G9.alwaysValidSchema)(G,W)){let H=$.var("valid",m1._`${J} <= ${b.length}`);$.if((0,m1.not)(H),()=>Y(H)),w.ok(H)}function Y(H){$.forRange("i",b.length,J,(z)=>{if(w.subschema({keyword:X,dataProp:z,dataPropType:G9.Type.Num},H),!G.allErrors)$.if((0,m1.not)(H),()=>$.break())})}}B7.validateAdditionalItems=D7;B7.default=DZ});var Y9=I((U7)=>{Object.defineProperty(U7,"__esModule",{value:!0});U7.validateTuple=void 0;var F7=f(),y6=o(),AZ=hw(),FZ={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(w){let{schema:b,it:$}=w;if(Array.isArray(b))return L7(w,"additionalItems",b);if($.items=!0,(0,y6.alwaysValidSchema)($,b))return;w.ok((0,AZ.validateArray)(w))}};function L7(w,b,$=w.schema){let{gen:W,parentSchema:Q,data:X,keyword:G,it:J}=w;if(z(Q),J.opts.unevaluated&&$.length&&J.items!==!0)J.items=y6.mergeEvaluated.items(W,$.length,J.items);let Y=W.name("valid"),H=W.const("len",F7._`${X}.length`);$.forEach((B,A)=>{if((0,y6.alwaysValidSchema)(J,B))return;W.if(F7._`${H} > ${A}`,()=>w.subschema({keyword:G,schemaProp:A,dataProp:A},Y)),w.ok(Y)});function z(B){let{opts:A,errSchemaPath:F}=J,U=$.length,V=U===B.minItems&&(U===B.maxItems||B[b]===!1);if(A.strictTuples&&!V){let q=`"${G}" is ${U}-tuple, but minItems or maxItems/${b} are not specified or different at path "${F}"`;(0,y6.checkStrictMode)(J,q,A.strictTuples)}}}U7.validateTuple=L7;U7.default=FZ});var Z7=I((O7)=>{Object.defineProperty(O7,"__esModule",{value:!0});var UZ=Y9(),KZ={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(w)=>(0,UZ.validateTuple)(w,"items")};O7.default=KZ});var j7=I((V7)=>{Object.defineProperty(V7,"__esModule",{value:!0});var M7=f(),ZZ=o(),MZ=hw(),VZ=J9(),jZ={message:({params:{len:w}})=>M7.str`must NOT have more than ${w} items`,params:({params:{len:w}})=>M7._`{limit: ${w}}`},qZ={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:jZ,code(w){let{schema:b,parentSchema:$,it:W}=w,{prefixItems:Q}=$;if(W.items=!0,(0,ZZ.alwaysValidSchema)(W,b))return;if(Q)(0,VZ.validateAdditionalItems)(w,Q);else w.ok((0,MZ.validateArray)(w))}};V7.default=qZ});var P7=I((q7)=>{Object.defineProperty(q7,"__esModule",{value:!0});var yw=f(),u6=o(),IZ={message:({params:{min:w,max:b}})=>b===void 0?yw.str`must contain at least ${w} valid item(s)`:yw.str`must contain at least ${w} and no more than ${b} valid item(s)`,params:({params:{min:w,max:b}})=>b===void 0?yw._`{minContains: ${w}}`:yw._`{minContains: ${w}, maxContains: ${b}}`},NZ={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:IZ,code(w){let{gen:b,schema:$,parentSchema:W,data:Q,it:X}=w,G,J,{minContains:Y,maxContains:H}=W;if(X.opts.next)G=Y===void 0?1:Y,J=H;else G=1;let z=b.const("len",yw._`${Q}.length`);if(w.setParams({min:G,max:J}),J===void 0&&G===0){(0,u6.checkStrictMode)(X,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(J!==void 0&&G>J){(0,u6.checkStrictMode)(X,'"minContains" > "maxContains" is always invalid'),w.fail();return}if((0,u6.alwaysValidSchema)(X,$)){let V=yw._`${z} >= ${G}`;if(J!==void 0)V=yw._`${V} && ${z} <= ${J}`;w.pass(V);return}X.items=!0;let B=b.name("valid");if(J===void 0&&G===1)F(B,()=>b.if(B,()=>b.break()));else if(G===0){if(b.let(B,!0),J!==void 0)b.if(yw._`${Q}.length > 0`,A)}else b.let(B,!1),A();w.result(B,()=>w.reset());function A(){let V=b.name("_valid"),q=b.let("count",0);F(V,()=>b.if(V,()=>U(q)))}function F(V,q){b.forRange("i",0,z,(P)=>{w.subschema({keyword:"contains",dataProp:P,dataPropType:u6.Type.Num,compositeRule:!0},V),q()})}function U(V){if(b.code(yw._`${V}++`),J===void 0)b.if(yw._`${V} >= ${G}`,()=>b.assign(B,!0).break());else if(b.if(yw._`${V} > ${J}`,()=>b.assign(B,!1).break()),G===1)b.assign(B,!0);else b.if(yw._`${V} >= ${G}`,()=>b.assign(B,!0))}}};q7.default=NZ});var S7=I((E7)=>{Object.defineProperty(E7,"__esModule",{value:!0});E7.validateSchemaDeps=E7.validatePropertyDeps=E7.error=void 0;var H9=f(),TZ=o(),Bb=hw();E7.error={message:({params:{property:w,depsCount:b,deps:$}})=>{let W=b===1?"property":"properties";return H9.str`must have ${W} ${$} when property ${w} is present`},params:({params:{property:w,depsCount:b,deps:$,missingProperty:W}})=>H9._`{property: ${w},
2
+ var u3=Object.create;var{getPrototypeOf:c3,defineProperty:A4,getOwnPropertyNames:m3}=Object;var l3=Object.prototype.hasOwnProperty;function g3(w){return this[w]}var i3,n3,BW=(w,b,$)=>{var W=w!=null&&typeof w==="object";if(W){var Q=b?i3??=new WeakMap:n3??=new WeakMap,X=Q.get(w);if(X)return X}$=w!=null?u3(c3(w)):{};let G=b||!w||!w.__esModule?A4($,"default",{value:w,enumerable:!0}):$;for(let J of m3(w))if(!l3.call(G,J))A4(G,J,{get:g3.bind(w,J),enumerable:!0});if(W)Q.set(w,G);return G};var I=(w,b)=>()=>(b||w((b={exports:{}}).exports,b),b.exports);var p3=(w)=>w;function d3(w,b){this[w]=p3.bind(null,b)}var AW=(w,b)=>{for(var $ in b)A4(w,$,{get:b[$],enumerable:!0,configurable:!0,set:d3.bind(b,$)})};var o0=I((FG)=>{Object.defineProperty(FG,"__esModule",{value:!0});FG.regexpCode=FG.getEsmExportName=FG.getProperty=FG.safeStringify=FG.stringify=FG.strConcat=FG.addCodeArg=FG.str=FG._=FG.nil=FG._Code=FG.Name=FG.IDENTIFIER=FG._CodeOrName=void 0;class H6{}FG._CodeOrName=H6;FG.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class a1 extends H6{constructor(w){super();if(!FG.IDENTIFIER.test(w))throw Error("CodeGen: name must be a valid identifier");this.str=w}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}FG.Name=a1;class lw extends H6{constructor(w){super();this._items=typeof w==="string"?[w]:w}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let w=this._items[0];return w===""||w==='""'}get str(){var w;return(w=this._str)!==null&&w!==void 0?w:this._str=this._items.reduce((b,$)=>`${b}${$}`,"")}get names(){var w;return(w=this._names)!==null&&w!==void 0?w:this._names=this._items.reduce((b,$)=>{if($ instanceof a1)b[$.str]=(b[$.str]||0)+1;return b},{})}}FG._Code=lw;FG.nil=new lw("");function BG(w,...b){let $=[w[0]],W=0;while(W<b.length)j$($,b[W]),$.push(w[++W]);return new lw($)}FG._=BG;var M$=new lw("+");function AG(w,...b){let $=[d0(w[0])],W=0;while(W<b.length)$.push(M$),j$($,b[W]),$.push(M$,d0(w[++W]));return UA($),new lw($)}FG.str=AG;function j$(w,b){if(b instanceof lw)w.push(...b._items);else if(b instanceof a1)w.push(b);else w.push(ZA(b))}FG.addCodeArg=j$;function UA(w){let b=1;while(b<w.length-1){if(w[b]===M$){let $=KA(w[b-1],w[b+1]);if($!==void 0){w.splice(b-1,3,$);continue}w[b++]="+"}b++}}function KA(w,b){if(b==='""')return w;if(w==='""')return b;if(typeof w=="string"){if(b instanceof a1||w[w.length-1]!=='"')return;if(typeof b!="string")return`${w.slice(0,-1)}${b}"`;if(b[0]==='"')return w.slice(0,-1)+b.slice(1);return}if(typeof b=="string"&&b[0]==='"'&&!(w instanceof a1))return`"${w}${b.slice(1)}`;return}function OA(w,b){return b.emptyStr()?w:w.emptyStr()?b:AG`${w}${b}`}FG.strConcat=OA;function ZA(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:d0(Array.isArray(w)?w.join(","):w)}function VA(w){return new lw(d0(w))}FG.stringify=VA;function d0(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}FG.safeStringify=d0;function MA(w){return typeof w=="string"&&FG.IDENTIFIER.test(w)?new lw(`.${w}`):BG`[${w}]`}FG.getProperty=MA;function jA(w){if(typeof w=="string"&&FG.IDENTIFIER.test(w))return new lw(`${w}`);throw Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}FG.getEsmExportName=jA;function qA(w){return new lw(w.toString())}FG.regexpCode=qA});var N$=I((OG)=>{Object.defineProperty(OG,"__esModule",{value:!0});OG.ValueScope=OG.ValueScopeName=OG.Scope=OG.varKinds=OG.UsedValueState=void 0;var Nw=o0();class UG extends Error{constructor(w){super(`CodeGen: "code" for ${w} not defined`);this.value=w.value}}var D6;(function(w){w[w.Started=0]="Started",w[w.Completed=1]="Completed"})(D6||(OG.UsedValueState=D6={}));OG.varKinds={const:new Nw.Name("const"),let:new Nw.Name("let"),var:new Nw.Name("var")};class P${constructor({prefixes:w,parent:b}={}){this._names={},this._prefixes=w,this._parent=b}toName(w){return w instanceof Nw.Name?w:this.name(w)}name(w){return new Nw.Name(this._newName(w))}_newName(w){let b=this._names[w]||this._nameGroup(w);return`${w}${b.index++}`}_nameGroup(w){var b,$;if((($=(b=this._parent)===null||b===void 0?void 0:b._prefixes)===null||$===void 0?void 0:$.has(w))||this._prefixes&&!this._prefixes.has(w))throw Error(`CodeGen: prefix "${w}" is not allowed in this scope`);return this._names[w]={prefix:w,index:0}}}OG.Scope=P$;class I$ extends Nw.Name{constructor(w,b){super(b);this.prefix=w}setValue(w,{property:b,itemIndex:$}){this.value=w,this.scopePath=Nw._`.${new Nw.Name(b)}[${$}]`}}OG.ValueScopeName=I$;var hA=Nw._`\n`;class KG extends P${constructor(w){super(w);this._values={},this._scope=w.scope,this.opts={...w,_n:w.lines?hA:Nw.nil}}get(){return this._scope}name(w){return new I$(w,this._newName(w))}value(w,b){var $;if(b.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName(w),{prefix:Q}=W,X=($=b.key)!==null&&$!==void 0?$:b.ref,G=this._values[Q];if(G){let H=G.get(X);if(H)return H}else G=this._values[Q]=new Map;G.set(X,W);let J=this._scope[Q]||(this._scope[Q]=[]),Y=J.length;return J[Y]=b.ref,W.setValue(b,{property:Q,itemIndex:Y}),W}getValue(w,b){let $=this._values[w];if(!$)return;return $.get(b)}scopeRefs(w,b=this._values){return this._reduceValues(b,($)=>{if($.scopePath===void 0)throw Error(`CodeGen: name "${$}" has no value`);return Nw._`${w}${$.scopePath}`})}scopeCode(w=this._values,b,$){return this._reduceValues(w,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},b,$)}_reduceValues(w,b,$={},W){let Q=Nw.nil;for(let X in w){let G=w[X];if(!G)continue;let J=$[X]=$[X]||new Map;G.forEach((Y)=>{if(J.has(Y))return;J.set(Y,D6.Started);let H=b(Y);if(H){let z=this.opts.es5?OG.varKinds.var:OG.varKinds.const;Q=Nw._`${Q}${z} ${Y} = ${H};${this.opts._n}`}else if(H=W===null||W===void 0?void 0:W(Y))Q=Nw._`${Q}${H}${this.opts._n}`;else throw new UG(Y);J.set(Y,D6.Completed)})}return Q}}OG.ValueScope=KG});var c=I((Ew)=>{Object.defineProperty(Ew,"__esModule",{value:!0});Ew.or=Ew.and=Ew.not=Ew.CodeGen=Ew.operators=Ew.varKinds=Ew.ValueScopeName=Ew.ValueScope=Ew.Scope=Ew.Name=Ew.regexpCode=Ew.stringify=Ew.getProperty=Ew.nil=Ew.strConcat=Ew.str=Ew._=void 0;var n=o0(),gw=N$(),N1=o0();Object.defineProperty(Ew,"_",{enumerable:!0,get:function(){return N1._}});Object.defineProperty(Ew,"str",{enumerable:!0,get:function(){return N1.str}});Object.defineProperty(Ew,"strConcat",{enumerable:!0,get:function(){return N1.strConcat}});Object.defineProperty(Ew,"nil",{enumerable:!0,get:function(){return N1.nil}});Object.defineProperty(Ew,"getProperty",{enumerable:!0,get:function(){return N1.getProperty}});Object.defineProperty(Ew,"stringify",{enumerable:!0,get:function(){return N1.stringify}});Object.defineProperty(Ew,"regexpCode",{enumerable:!0,get:function(){return N1.regexpCode}});Object.defineProperty(Ew,"Name",{enumerable:!0,get:function(){return N1.Name}});var K6=N$();Object.defineProperty(Ew,"Scope",{enumerable:!0,get:function(){return K6.Scope}});Object.defineProperty(Ew,"ValueScope",{enumerable:!0,get:function(){return K6.ValueScope}});Object.defineProperty(Ew,"ValueScopeName",{enumerable:!0,get:function(){return K6.ValueScopeName}});Object.defineProperty(Ew,"varKinds",{enumerable:!0,get:function(){return K6.varKinds}});Ew.operators={GT:new n._Code(">"),GTE:new n._Code(">="),LT:new n._Code("<"),LTE:new n._Code("<="),EQ:new n._Code("==="),NEQ:new n._Code("!=="),NOT:new n._Code("!"),OR:new n._Code("||"),AND:new n._Code("&&"),ADD:new n._Code("+")};class E1{optimizeNodes(){return this}optimizeNames(w,b){return this}}class VG extends E1{constructor(w,b,$){super();this.varKind=w,this.name=b,this.rhs=$}render({es5:w,_n:b}){let $=w?gw.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${W};`+b}optimizeNames(w,b){if(!w[this.name.str])return;if(this.rhs)this.rhs=b0(this.rhs,w,b);return this}get names(){return this.rhs instanceof n._CodeOrName?this.rhs.names:{}}}class R$ extends E1{constructor(w,b,$){super();this.lhs=w,this.rhs=b,this.sideEffects=$}render({_n:w}){return`${this.lhs} = ${this.rhs};`+w}optimizeNames(w,b){if(this.lhs instanceof n.Name&&!w[this.lhs.str]&&!this.sideEffects)return;return this.rhs=b0(this.rhs,w,b),this}get names(){let w=this.lhs instanceof n.Name?{}:{...this.lhs.names};return U6(w,this.rhs)}}class MG extends R${constructor(w,b,$,W){super(w,$,W);this.op=b}render({_n:w}){return`${this.lhs} ${this.op}= ${this.rhs};`+w}}class jG extends E1{constructor(w){super();this.label=w,this.names={}}render({_n:w}){return`${this.label}:`+w}}class qG extends E1{constructor(w){super();this.label=w,this.names={}}render({_n:w}){return`break${this.label?` ${this.label}`:""};`+w}}class PG extends E1{constructor(w){super();this.error=w}render({_n:w}){return`throw ${this.error};`+w}get names(){return this.error.names}}class IG extends E1{constructor(w){super();this.code=w}render({_n:w}){return`${this.code};`+w}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(w,b){return this.code=b0(this.code,w,b),this}get names(){return this.code instanceof n._CodeOrName?this.code.names:{}}}class O6 extends E1{constructor(w=[]){super();this.nodes=w}render(w){return this.nodes.reduce((b,$)=>b+$.render(w),"")}optimizeNodes(){let{nodes:w}=this,b=w.length;while(b--){let $=w[b].optimizeNodes();if(Array.isArray($))w.splice(b,1,...$);else if($)w[b]=$;else w.splice(b,1)}return w.length>0?this:void 0}optimizeNames(w,b){let{nodes:$}=this,W=$.length;while(W--){let Q=$[W];if(Q.optimizeNames(w,b))continue;cA(w,Q.names),$.splice(W,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((w,b)=>y1(w,b.names),{})}}class T1 extends O6{render(w){return"{"+w._n+super.render(w)+"}"+w._n}}class NG extends O6{}class t0 extends T1{}t0.kind="else";class J1 extends T1{constructor(w,b){super(b);this.condition=w}render(w){let b=`if(${this.condition})`+super.render(w);if(this.else)b+="else "+this.else.render(w);return b}optimizeNodes(){super.optimizeNodes();let w=this.condition;if(w===!0)return this.nodes;let b=this.else;if(b){let $=b.optimizeNodes();b=this.else=Array.isArray($)?new t0($):$}if(b){if(w===!1)return b instanceof J1?b:b.nodes;if(this.nodes.length)return this;return new J1(vG(w),b instanceof J1?[b]:b.nodes)}if(w===!1||!this.nodes.length)return;return this}optimizeNames(w,b){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(w,b),!(super.optimizeNames(w,b)||this.else))return;return this.condition=b0(this.condition,w,b),this}get names(){let w=super.names;if(U6(w,this.condition),this.else)y1(w,this.else.names);return w}}J1.kind="if";class w0 extends T1{}w0.kind="for";class EG extends w0{constructor(w){super();this.iteration=w}render(w){return`for(${this.iteration})`+super.render(w)}optimizeNames(w,b){if(!super.optimizeNames(w,b))return;return this.iteration=b0(this.iteration,w,b),this}get names(){return y1(super.names,this.iteration.names)}}class TG extends w0{constructor(w,b,$,W){super();this.varKind=w,this.name=b,this.from=$,this.to=W}render(w){let b=w.es5?gw.varKinds.var:this.varKind,{name:$,from:W,to:Q}=this;return`for(${b} ${$}=${W}; ${$}<${Q}; ${$}++)`+super.render(w)}get names(){let w=U6(super.names,this.from);return U6(w,this.to)}}class E$ extends w0{constructor(w,b,$,W){super();this.loop=w,this.varKind=b,this.name=$,this.iterable=W}render(w){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(w)}optimizeNames(w,b){if(!super.optimizeNames(w,b))return;return this.iterable=b0(this.iterable,w,b),this}get names(){return y1(super.names,this.iterable.names)}}class B6 extends T1{constructor(w,b,$){super();this.name=w,this.args=b,this.async=$}render(w){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(w)}}B6.kind="func";class A6 extends O6{render(w){return"return "+super.render(w)}}A6.kind="return";class RG extends T1{render(w){let b="try"+super.render(w);if(this.catch)b+=this.catch.render(w);if(this.finally)b+=this.finally.render(w);return b}optimizeNodes(){var w,b;return super.optimizeNodes(),(w=this.catch)===null||w===void 0||w.optimizeNodes(),(b=this.finally)===null||b===void 0||b.optimizeNodes(),this}optimizeNames(w,b){var $,W;return super.optimizeNames(w,b),($=this.catch)===null||$===void 0||$.optimizeNames(w,b),(W=this.finally)===null||W===void 0||W.optimizeNames(w,b),this}get names(){let w=super.names;if(this.catch)y1(w,this.catch.names);if(this.finally)y1(w,this.finally.names);return w}}class F6 extends T1{constructor(w){super();this.error=w}render(w){return`catch(${this.error})`+super.render(w)}}F6.kind="catch";class L6 extends T1{render(w){return"finally"+super.render(w)}}L6.kind="finally";class SG{constructor(w,b={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...b,_n:b.lines?`
3
+ `:""},this._extScope=w,this._scope=new gw.Scope({parent:w}),this._nodes=[new NG]}toString(){return this._root.render(this.opts)}name(w){return this._scope.name(w)}scopeName(w){return this._extScope.name(w)}scopeValue(w,b){let $=this._extScope.value(w,b);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(w,b){return this._extScope.getValue(w,b)}scopeRefs(w){return this._extScope.scopeRefs(w,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(w,b,$,W){let Q=this._scope.toName(b);if($!==void 0&&W)this._constants[Q.str]=$;return this._leafNode(new VG(w,Q,$)),Q}const(w,b,$){return this._def(gw.varKinds.const,w,b,$)}let(w,b,$){return this._def(gw.varKinds.let,w,b,$)}var(w,b,$){return this._def(gw.varKinds.var,w,b,$)}assign(w,b,$){return this._leafNode(new R$(w,b,$))}add(w,b){return this._leafNode(new MG(w,Ew.operators.ADD,b))}code(w){if(typeof w=="function")w();else if(w!==n.nil)this._leafNode(new IG(w));return this}object(...w){let b=["{"];for(let[$,W]of w){if(b.length>1)b.push(",");if(b.push($),$!==W||this.opts.es5)b.push(":"),(0,n.addCodeArg)(b,W)}return b.push("}"),new n._Code(b)}if(w,b,$){if(this._blockNode(new J1(w)),b&&$)this.code(b).else().code($).endIf();else if(b)this.code(b).endIf();else if($)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(w){return this._elseNode(new J1(w))}else(){return this._elseNode(new t0)}endIf(){return this._endBlockNode(J1,t0)}_for(w,b){if(this._blockNode(w),b)this.code(b).endFor();return this}for(w,b){return this._for(new EG(w),b)}forRange(w,b,$,W,Q=this.opts.es5?gw.varKinds.var:gw.varKinds.let){let X=this._scope.toName(w);return this._for(new TG(Q,X,b,$),()=>W(X))}forOf(w,b,$,W=gw.varKinds.const){let Q=this._scope.toName(w);if(this.opts.es5){let X=b instanceof n.Name?b:this.var("_arr",b);return this.forRange("_i",0,n._`${X}.length`,(G)=>{this.var(Q,n._`${X}[${G}]`),$(Q)})}return this._for(new E$("of",W,Q,b),()=>$(Q))}forIn(w,b,$,W=this.opts.es5?gw.varKinds.var:gw.varKinds.const){if(this.opts.ownProperties)return this.forOf(w,n._`Object.keys(${b})`,$);let Q=this._scope.toName(w);return this._for(new E$("in",W,Q,b),()=>$(Q))}endFor(){return this._endBlockNode(w0)}label(w){return this._leafNode(new jG(w))}break(w){return this._leafNode(new qG(w))}return(w){let b=new A6;if(this._blockNode(b),this.code(w),b.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(A6)}try(w,b,$){if(!b&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new RG;if(this._blockNode(W),this.code(w),b){let Q=this.name("e");this._currNode=W.catch=new F6(Q),b(Q)}if($)this._currNode=W.finally=new L6,this.code($);return this._endBlockNode(F6,L6)}throw(w){return this._leafNode(new PG(w))}block(w,b){if(this._blockStarts.push(this._nodes.length),w)this.code(w).endBlock(b);return this}endBlock(w){let b=this._blockStarts.pop();if(b===void 0)throw Error("CodeGen: not in self-balancing block");let $=this._nodes.length-b;if($<0||w!==void 0&&$!==w)throw Error(`CodeGen: wrong number of nodes: ${$} vs ${w} expected`);return this._nodes.length=b,this}func(w,b=n.nil,$,W){if(this._blockNode(new B6(w,b,$)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(B6)}optimize(w=1){while(w-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(w){return this._currNode.nodes.push(w),this}_blockNode(w){this._currNode.nodes.push(w),this._nodes.push(w)}_endBlockNode(w,b){let $=this._currNode;if($ instanceof w||b&&$ instanceof b)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${b?`${w.kind}/${b.kind}`:w.kind}"`)}_elseNode(w){let b=this._currNode;if(!(b instanceof J1))throw Error('CodeGen: "else" without "if"');return this._currNode=b.else=w,this}get _root(){return this._nodes[0]}get _currNode(){let w=this._nodes;return w[w.length-1]}set _currNode(w){let b=this._nodes;b[b.length-1]=w}}Ew.CodeGen=SG;function y1(w,b){for(let $ in b)w[$]=(w[$]||0)+(b[$]||0);return w}function U6(w,b){return b instanceof n._CodeOrName?y1(w,b.names):w}function b0(w,b,$){if(w instanceof n.Name)return W(w);if(!Q(w))return w;return new n._Code(w._items.reduce((X,G)=>{if(G instanceof n.Name)G=W(G);if(G instanceof n._Code)X.push(...G._items);else X.push(G);return X},[]));function W(X){let G=$[X.str];if(G===void 0||b[X.str]!==1)return X;return delete b[X.str],G}function Q(X){return X instanceof n._Code&&X._items.some((G)=>G instanceof n.Name&&b[G.str]===1&&$[G.str]!==void 0)}}function cA(w,b){for(let $ in b)w[$]=(w[$]||0)-(b[$]||0)}function vG(w){return typeof w=="boolean"||typeof w=="number"||w===null?!w:n._`!${T$(w)}`}Ew.not=vG;var mA=CG(Ew.operators.AND);function lA(...w){return w.reduce(mA)}Ew.and=lA;var gA=CG(Ew.operators.OR);function iA(...w){return w.reduce(gA)}Ew.or=iA;function CG(w){return(b,$)=>b===n.nil?$:$===n.nil?b:n._`${T$(b)} ${w} ${T$($)}`}function T$(w){return w instanceof n.Name?w:n._`(${w})`}});var o=I((mG)=>{Object.defineProperty(mG,"__esModule",{value:!0});mG.checkStrictMode=mG.getErrorPath=mG.Type=mG.useFunc=mG.setEvaluated=mG.evaluatedPropsToName=mG.mergeEvaluated=mG.eachItem=mG.unescapeJsonPointer=mG.escapeJsonPointer=mG.escapeFragment=mG.unescapeFragment=mG.schemaRefOrVal=mG.schemaHasRulesButRef=mG.schemaHasRules=mG.checkUnknownRules=mG.alwaysValidSchema=mG.toHash=void 0;var e=c(),oA=o0();function tA(w){let b={};for(let $ of w)b[$]=!0;return b}mG.toHash=tA;function rA(w,b){if(typeof b=="boolean")return b;if(Object.keys(b).length===0)return!0;return hG(w,b),!yG(b,w.self.RULES.all)}mG.alwaysValidSchema=rA;function hG(w,b=w.schema){let{opts:$,self:W}=w;if(!$.strictSchema)return;if(typeof b==="boolean")return;let Q=W.RULES.keywords;for(let X in b)if(!Q[X])cG(w,`unknown keyword: "${X}"`)}mG.checkUnknownRules=hG;function yG(w,b){if(typeof w=="boolean")return!w;for(let $ in w)if(b[$])return!0;return!1}mG.schemaHasRules=yG;function sA(w,b){if(typeof w=="boolean")return!w;for(let $ in w)if($!=="$ref"&&b.all[$])return!0;return!1}mG.schemaHasRulesButRef=sA;function eA({topSchemaRef:w,schemaPath:b},$,W,Q){if(!Q){if(typeof $=="number"||typeof $=="boolean")return $;if(typeof $=="string")return e._`${$}`}return e._`${w}${b}${(0,e.getProperty)(W)}`}mG.schemaRefOrVal=eA;function aA(w){return fG(decodeURIComponent(w))}mG.unescapeFragment=aA;function wF(w){return encodeURIComponent(v$(w))}mG.escapeFragment=wF;function v$(w){if(typeof w=="number")return`${w}`;return w.replace(/~/g,"~0").replace(/\//g,"~1")}mG.escapeJsonPointer=v$;function fG(w){return w.replace(/~1/g,"/").replace(/~0/g,"~")}mG.unescapeJsonPointer=fG;function bF(w,b){if(Array.isArray(w))for(let $ of w)b($);else b(w)}mG.eachItem=bF;function _G({mergeNames:w,mergeToName:b,mergeValues:$,resultToName:W}){return(Q,X,G,J)=>{let Y=G===void 0?X:G instanceof e.Name?(X instanceof e.Name?w(Q,X,G):b(Q,X,G),G):X instanceof e.Name?(b(Q,G,X),X):$(X,G);return J===e.Name&&!(Y instanceof e.Name)?W(Q,Y):Y}}mG.mergeEvaluated={props:_G({mergeNames:(w,b,$)=>w.if(e._`${$} !== true && ${b} !== undefined`,()=>{w.if(e._`${b} === true`,()=>w.assign($,!0),()=>w.assign($,e._`${$} || {}`).code(e._`Object.assign(${$}, ${b})`))}),mergeToName:(w,b,$)=>w.if(e._`${$} !== true`,()=>{if(b===!0)w.assign($,!0);else w.assign($,e._`${$} || {}`),C$(w,$,b)}),mergeValues:(w,b)=>w===!0?!0:{...w,...b},resultToName:uG}),items:_G({mergeNames:(w,b,$)=>w.if(e._`${$} !== true && ${b} !== undefined`,()=>w.assign($,e._`${b} === true ? true : ${$} > ${b} ? ${$} : ${b}`)),mergeToName:(w,b,$)=>w.if(e._`${$} !== true`,()=>w.assign($,b===!0?!0:e._`${$} > ${b} ? ${$} : ${b}`)),mergeValues:(w,b)=>w===!0?!0:Math.max(w,b),resultToName:(w,b)=>w.var("items",b)})};function uG(w,b){if(b===!0)return w.var("props",!0);let $=w.var("props",e._`{}`);if(b!==void 0)C$(w,$,b);return $}mG.evaluatedPropsToName=uG;function C$(w,b,$){Object.keys($).forEach((W)=>w.assign(e._`${b}${(0,e.getProperty)(W)}`,!0))}mG.setEvaluated=C$;var xG={};function $F(w,b){return w.scopeValue("func",{ref:b,code:xG[b.code]||(xG[b.code]=new oA._Code(b.code))})}mG.useFunc=$F;var S$;(function(w){w[w.Num=0]="Num",w[w.Str=1]="Str"})(S$||(mG.Type=S$={}));function WF(w,b,$){if(w instanceof e.Name){let W=b===S$.Num;return $?W?e._`"[" + ${w} + "]"`:e._`"['" + ${w} + "']"`:W?e._`"/" + ${w}`:e._`"/" + ${w}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,e.getProperty)(w).toString():"/"+v$(w)}mG.getErrorPath=WF;function cG(w,b,$=w.opts.strictSchema){if(!$)return;if(b=`strict mode: ${b}`,$===!0)throw Error(b);w.self.logger.warn(b)}mG.checkStrictMode=cG});var Y1=I((gG)=>{Object.defineProperty(gG,"__esModule",{value:!0});var Vw=c(),MF={data:new Vw.Name("data"),valCxt:new Vw.Name("valCxt"),instancePath:new Vw.Name("instancePath"),parentData:new Vw.Name("parentData"),parentDataProperty:new Vw.Name("parentDataProperty"),rootData:new Vw.Name("rootData"),dynamicAnchors:new Vw.Name("dynamicAnchors"),vErrors:new Vw.Name("vErrors"),errors:new Vw.Name("errors"),this:new Vw.Name("this"),self:new Vw.Name("self"),scope:new Vw.Name("scope"),json:new Vw.Name("json"),jsonPos:new Vw.Name("jsonPos"),jsonLen:new Vw.Name("jsonLen"),jsonPart:new Vw.Name("jsonPart")};gG.default=MF});var r0=I((dG)=>{Object.defineProperty(dG,"__esModule",{value:!0});dG.extendErrors=dG.resetErrorsCount=dG.reportExtraError=dG.reportError=dG.keyword$DataError=dG.keywordError=void 0;var p=c(),V6=o(),jw=Y1();dG.keywordError={message:({keyword:w})=>p.str`must pass "${w}" keyword validation`};dG.keyword$DataError={message:({keyword:w,schemaType:b})=>b?p.str`"${w}" keyword must be ${b} ($data)`:p.str`"${w}" keyword is invalid ($data)`};function qF(w,b=dG.keywordError,$,W){let{it:Q}=w,{gen:X,compositeRule:G,allErrors:J}=Q,Y=pG(w,b,$);if(W!==null&&W!==void 0?W:G||J)iG(X,Y);else nG(Q,p._`[${Y}]`)}dG.reportError=qF;function PF(w,b=dG.keywordError,$){let{it:W}=w,{gen:Q,compositeRule:X,allErrors:G}=W,J=pG(w,b,$);if(iG(Q,J),!(X||G))nG(W,jw.default.vErrors)}dG.reportExtraError=PF;function IF(w,b){w.assign(jw.default.errors,b),w.if(p._`${jw.default.vErrors} !== null`,()=>w.if(b,()=>w.assign(p._`${jw.default.vErrors}.length`,b),()=>w.assign(jw.default.vErrors,null)))}dG.resetErrorsCount=IF;function NF({gen:w,keyword:b,schemaValue:$,data:W,errsCount:Q,it:X}){if(Q===void 0)throw Error("ajv implementation error");let G=w.name("err");w.forRange("i",Q,jw.default.errors,(J)=>{if(w.const(G,p._`${jw.default.vErrors}[${J}]`),w.if(p._`${G}.instancePath === undefined`,()=>w.assign(p._`${G}.instancePath`,(0,p.strConcat)(jw.default.instancePath,X.errorPath))),w.assign(p._`${G}.schemaPath`,p.str`${X.errSchemaPath}/${b}`),X.opts.verbose)w.assign(p._`${G}.schema`,$),w.assign(p._`${G}.data`,W)})}dG.extendErrors=NF;function iG(w,b){let $=w.const("err",b);w.if(p._`${jw.default.vErrors} === null`,()=>w.assign(jw.default.vErrors,p._`[${$}]`),p._`${jw.default.vErrors}.push(${$})`),w.code(p._`${jw.default.errors}++`)}function nG(w,b){let{gen:$,validateName:W,schemaEnv:Q}=w;if(Q.$async)$.throw(p._`new ${w.ValidationError}(${b})`);else $.assign(p._`${W}.errors`,b),$.return(!1)}var f1={keyword:new p.Name("keyword"),schemaPath:new p.Name("schemaPath"),params:new p.Name("params"),propertyName:new p.Name("propertyName"),message:new p.Name("message"),schema:new p.Name("schema"),parentSchema:new p.Name("parentSchema")};function pG(w,b,$){let{createErrors:W}=w.it;if(W===!1)return p._`{}`;return EF(w,b,$)}function EF(w,b,$={}){let{gen:W,it:Q}=w,X=[TF(Q,$),RF(w,$)];return SF(w,b,X),W.object(...X)}function TF({errorPath:w},{instancePath:b}){let $=b?p.str`${w}${(0,V6.getErrorPath)(b,V6.Type.Str)}`:w;return[jw.default.instancePath,(0,p.strConcat)(jw.default.instancePath,$)]}function RF({keyword:w,it:{errSchemaPath:b}},{schemaPath:$,parentSchema:W}){let Q=W?b:p.str`${b}/${w}`;if($)Q=p.str`${Q}${(0,V6.getErrorPath)($,V6.Type.Str)}`;return[f1.schemaPath,Q]}function SF(w,{params:b,message:$},W){let{keyword:Q,data:X,schemaValue:G,it:J}=w,{opts:Y,propertyName:H,topSchemaRef:z,schemaPath:B}=J;if(W.push([f1.keyword,Q],[f1.params,typeof b=="function"?b(w):b||p._`{}`]),Y.messages)W.push([f1.message,typeof $=="function"?$(w):$]);if(Y.verbose)W.push([f1.schema,G],[f1.parentSchema,p._`${z}${B}`],[jw.default.data,X]);if(H)W.push([f1.propertyName,H])}});var eG=I((rG)=>{Object.defineProperty(rG,"__esModule",{value:!0});rG.boolOrEmptySchema=rG.topBoolOrEmptySchema=void 0;var xF=r0(),hF=c(),yF=Y1(),fF={message:"boolean schema is false"};function uF(w){let{gen:b,schema:$,validateName:W}=w;if($===!1)tG(w,!1);else if(typeof $=="object"&&$.$async===!0)b.return(yF.default.data);else b.assign(hF._`${W}.errors`,null),b.return(!0)}rG.topBoolOrEmptySchema=uF;function cF(w,b){let{gen:$,schema:W}=w;if(W===!1)$.var(b,!1),tG(w);else $.var(b,!0)}rG.boolOrEmptySchema=cF;function tG(w,b){let{gen:$,data:W}=w,Q={gen:$,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:w};(0,xF.reportError)(Q,fF,void 0,b)}});var _$=I((aG)=>{Object.defineProperty(aG,"__esModule",{value:!0});aG.getRules=aG.isJSONType=void 0;var lF=["string","number","integer","boolean","null","object","array"],gF=new Set(lF);function iF(w){return typeof w=="string"&&gF.has(w)}aG.isJSONType=iF;function nF(){let w={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...w,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},w.number,w.string,w.array,w.object],post:{rules:[]},all:{},keywords:{}}}aG.getRules=nF});var x$=I((WJ)=>{Object.defineProperty(WJ,"__esModule",{value:!0});WJ.shouldUseRule=WJ.shouldUseGroup=WJ.schemaHasRulesForType=void 0;function dF({schema:w,self:b},$){let W=b.RULES.types[$];return W&&W!==!0&&bJ(w,W)}WJ.schemaHasRulesForType=dF;function bJ(w,b){return b.rules.some(($)=>$J(w,$))}WJ.shouldUseGroup=bJ;function $J(w,b){var $;return w[b.keyword]!==void 0||(($=b.definition.implements)===null||$===void 0?void 0:$.some((W)=>w[W]!==void 0))}WJ.shouldUseRule=$J});var s0=I((YJ)=>{Object.defineProperty(YJ,"__esModule",{value:!0});YJ.reportTypeError=YJ.checkDataTypes=YJ.checkDataType=YJ.coerceAndCheckDataType=YJ.getJSONTypes=YJ.getSchemaTypes=YJ.DataType=void 0;var rF=_$(),sF=x$(),eF=r0(),f=c(),XJ=o(),$0;(function(w){w[w.Correct=0]="Correct",w[w.Wrong=1]="Wrong"})($0||(YJ.DataType=$0={}));function aF(w){let b=GJ(w.type);if(b.includes("null")){if(w.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!b.length&&w.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(w.nullable===!0)b.push("null")}return b}YJ.getSchemaTypes=aF;function GJ(w){let b=Array.isArray(w)?w:w?[w]:[];if(b.every(rF.isJSONType))return b;throw Error("type must be JSONType or JSONType[]: "+b.join(","))}YJ.getJSONTypes=GJ;function wL(w,b){let{gen:$,data:W,opts:Q}=w,X=bL(b,Q.coerceTypes),G=b.length>0&&!(X.length===0&&b.length===1&&(0,sF.schemaHasRulesForType)(w,b[0]));if(G){let J=y$(b,W,Q.strictNumbers,$0.Wrong);$.if(J,()=>{if(X.length)$L(w,b,X);else f$(w)})}return G}YJ.coerceAndCheckDataType=wL;var JJ=new Set(["string","number","integer","boolean","null"]);function bL(w,b){return b?w.filter(($)=>JJ.has($)||b==="array"&&$==="array"):[]}function $L(w,b,$){let{gen:W,data:Q,opts:X}=w,G=W.let("dataType",f._`typeof ${Q}`),J=W.let("coerced",f._`undefined`);if(X.coerceTypes==="array")W.if(f._`${G} == 'object' && Array.isArray(${Q}) && ${Q}.length == 1`,()=>W.assign(Q,f._`${Q}[0]`).assign(G,f._`typeof ${Q}`).if(y$(b,Q,X.strictNumbers),()=>W.assign(J,Q)));W.if(f._`${J} !== undefined`);for(let H of $)if(JJ.has(H)||H==="array"&&X.coerceTypes==="array")Y(H);W.else(),f$(w),W.endIf(),W.if(f._`${J} !== undefined`,()=>{W.assign(Q,J),WL(w,J)});function Y(H){switch(H){case"string":W.elseIf(f._`${G} == "number" || ${G} == "boolean"`).assign(J,f._`"" + ${Q}`).elseIf(f._`${Q} === null`).assign(J,f._`""`);return;case"number":W.elseIf(f._`${G} == "boolean" || ${Q} === null
4
+ || (${G} == "string" && ${Q} && ${Q} == +${Q})`).assign(J,f._`+${Q}`);return;case"integer":W.elseIf(f._`${G} === "boolean" || ${Q} === null
5
+ || (${G} === "string" && ${Q} && ${Q} == +${Q} && !(${Q} % 1))`).assign(J,f._`+${Q}`);return;case"boolean":W.elseIf(f._`${Q} === "false" || ${Q} === 0 || ${Q} === null`).assign(J,!1).elseIf(f._`${Q} === "true" || ${Q} === 1`).assign(J,!0);return;case"null":W.elseIf(f._`${Q} === "" || ${Q} === 0 || ${Q} === false`),W.assign(J,null);return;case"array":W.elseIf(f._`${G} === "string" || ${G} === "number"
6
+ || ${G} === "boolean" || ${Q} === null`).assign(J,f._`[${Q}]`)}}}function WL({gen:w,parentData:b,parentDataProperty:$},W){w.if(f._`${b} !== undefined`,()=>w.assign(f._`${b}[${$}]`,W))}function h$(w,b,$,W=$0.Correct){let Q=W===$0.Correct?f.operators.EQ:f.operators.NEQ,X;switch(w){case"null":return f._`${b} ${Q} null`;case"array":X=f._`Array.isArray(${b})`;break;case"object":X=f._`${b} && typeof ${b} == "object" && !Array.isArray(${b})`;break;case"integer":X=G(f._`!(${b} % 1) && !isNaN(${b})`);break;case"number":X=G();break;default:return f._`typeof ${b} ${Q} ${w}`}return W===$0.Correct?X:(0,f.not)(X);function G(J=f.nil){return(0,f.and)(f._`typeof ${b} == "number"`,J,$?f._`isFinite(${b})`:f.nil)}}YJ.checkDataType=h$;function y$(w,b,$,W){if(w.length===1)return h$(w[0],b,$,W);let Q,X=(0,XJ.toHash)(w);if(X.array&&X.object){let G=f._`typeof ${b} != "object"`;Q=X.null?G:f._`!${b} || ${G}`,delete X.null,delete X.array,delete X.object}else Q=f.nil;if(X.number)delete X.integer;for(let G in X)Q=(0,f.and)(Q,h$(G,b,$,W));return Q}YJ.checkDataTypes=y$;var QL={message:({schema:w})=>`must be ${w}`,params:({schema:w,schemaValue:b})=>typeof w=="string"?f._`{type: ${w}}`:f._`{type: ${b}}`};function f$(w){let b=XL(w);(0,eF.reportError)(b,QL)}YJ.reportTypeError=f$;function XL(w){let{gen:b,data:$,schema:W}=w,Q=(0,XJ.schemaRefOrVal)(w,W,"type");return{gen:b,keyword:"type",data:$,schema:W.type,schemaCode:Q,schemaValue:Q,parentSchema:W,params:{},it:w}}});var AJ=I((DJ)=>{Object.defineProperty(DJ,"__esModule",{value:!0});DJ.assignDefaults=void 0;var W0=c(),BL=o();function AL(w,b){let{properties:$,items:W}=w.schema;if(b==="object"&&$)for(let Q in $)zJ(w,Q,$[Q].default);else if(b==="array"&&Array.isArray(W))W.forEach((Q,X)=>zJ(w,X,Q.default))}DJ.assignDefaults=AL;function zJ(w,b,$){let{gen:W,compositeRule:Q,data:X,opts:G}=w;if($===void 0)return;let J=W0._`${X}${(0,W0.getProperty)(b)}`;if(Q){(0,BL.checkStrictMode)(w,`default is ignored for: ${J}`);return}let Y=W0._`${J} === undefined`;if(G.useDefaults==="empty")Y=W0._`${Y} || ${J} === null || ${J} === ""`;W.if(Y,W0._`${J} = ${(0,W0.stringify)($)}`)}});var fw=I((UJ)=>{Object.defineProperty(UJ,"__esModule",{value:!0});UJ.validateUnion=UJ.validateArray=UJ.usePattern=UJ.callValidateCode=UJ.schemaProperties=UJ.allSchemaProperties=UJ.noPropertyInData=UJ.propertyInData=UJ.isOwnProperty=UJ.hasPropFunc=UJ.reportMissingProp=UJ.checkMissingProp=UJ.checkReportMissingProp=void 0;var $w=c(),u$=o(),R1=Y1(),FL=o();function LL(w,b){let{gen:$,data:W,it:Q}=w;$.if(m$($,W,b,Q.opts.ownProperties),()=>{w.setParams({missingProperty:$w._`${b}`},!0),w.error()})}UJ.checkReportMissingProp=LL;function UL({gen:w,data:b,it:{opts:$}},W,Q){return(0,$w.or)(...W.map((X)=>(0,$w.and)(m$(w,b,X,$.ownProperties),$w._`${Q} = ${X}`)))}UJ.checkMissingProp=UL;function KL(w,b){w.setParams({missingProperty:b},!0),w.error()}UJ.reportMissingProp=KL;function FJ(w){return w.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:$w._`Object.prototype.hasOwnProperty`})}UJ.hasPropFunc=FJ;function c$(w,b,$){return $w._`${FJ(w)}.call(${b}, ${$})`}UJ.isOwnProperty=c$;function OL(w,b,$,W){let Q=$w._`${b}${(0,$w.getProperty)($)} !== undefined`;return W?$w._`${Q} && ${c$(w,b,$)}`:Q}UJ.propertyInData=OL;function m$(w,b,$,W){let Q=$w._`${b}${(0,$w.getProperty)($)} === undefined`;return W?(0,$w.or)(Q,(0,$w.not)(c$(w,b,$))):Q}UJ.noPropertyInData=m$;function LJ(w){return w?Object.keys(w).filter((b)=>b!=="__proto__"):[]}UJ.allSchemaProperties=LJ;function ZL(w,b){return LJ(b).filter(($)=>!(0,u$.alwaysValidSchema)(w,b[$]))}UJ.schemaProperties=ZL;function VL({schemaCode:w,data:b,it:{gen:$,topSchemaRef:W,schemaPath:Q,errorPath:X},it:G},J,Y,H){let z=H?$w._`${w}, ${b}, ${W}${Q}`:b,B=[[R1.default.instancePath,(0,$w.strConcat)(R1.default.instancePath,X)],[R1.default.parentData,G.parentData],[R1.default.parentDataProperty,G.parentDataProperty],[R1.default.rootData,R1.default.rootData]];if(G.opts.dynamicRef)B.push([R1.default.dynamicAnchors,R1.default.dynamicAnchors]);let A=$w._`${z}, ${$.object(...B)}`;return Y!==$w.nil?$w._`${J}.call(${Y}, ${A})`:$w._`${J}(${A})`}UJ.callValidateCode=VL;var ML=$w._`new RegExp`;function jL({gen:w,it:{opts:b}},$){let W=b.unicodeRegExp?"u":"",{regExp:Q}=b.code,X=Q($,W);return w.scopeValue("pattern",{key:X.toString(),ref:X,code:$w._`${Q.code==="new RegExp"?ML:(0,FL.useFunc)(w,Q)}(${$}, ${W})`})}UJ.usePattern=jL;function qL(w){let{gen:b,data:$,keyword:W,it:Q}=w,X=b.name("valid");if(Q.allErrors){let J=b.let("valid",!0);return G(()=>b.assign(J,!1)),J}return b.var(X,!0),G(()=>b.break()),X;function G(J){let Y=b.const("len",$w._`${$}.length`);b.forRange("i",0,Y,(H)=>{w.subschema({keyword:W,dataProp:H,dataPropType:u$.Type.Num},X),b.if((0,$w.not)(X),J)})}}UJ.validateArray=qL;function PL(w){let{gen:b,schema:$,keyword:W,it:Q}=w;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((Y)=>(0,u$.alwaysValidSchema)(Q,Y))&&!Q.opts.unevaluated)return;let G=b.let("valid",!1),J=b.name("_valid");b.block(()=>$.forEach((Y,H)=>{let z=w.subschema({keyword:W,schemaProp:H,compositeRule:!0},J);if(b.assign(G,$w._`${G} || ${J}`),!w.mergeValidEvaluated(z,J))b.if((0,$w.not)(G))})),w.result(G,()=>w.reset(),()=>w.error(!0))}UJ.validateUnion=PL});var jJ=I((VJ)=>{Object.defineProperty(VJ,"__esModule",{value:!0});VJ.validateKeywordUsage=VJ.validSchemaType=VJ.funcKeywordCode=VJ.macroKeywordCode=void 0;var qw=c(),u1=Y1(),yL=fw(),fL=r0();function uL(w,b){let{gen:$,keyword:W,schema:Q,parentSchema:X,it:G}=w,J=b.macro.call(G.self,Q,X,G),Y=ZJ($,W,J);if(G.opts.validateSchema!==!1)G.self.validateSchema(J,!0);let H=$.name("valid");w.subschema({schema:J,schemaPath:qw.nil,errSchemaPath:`${G.errSchemaPath}/${W}`,topSchemaRef:Y,compositeRule:!0},H),w.pass(H,()=>w.error(!0))}VJ.macroKeywordCode=uL;function cL(w,b){var $;let{gen:W,keyword:Q,schema:X,parentSchema:G,$data:J,it:Y}=w;lL(Y,b);let H=!J&&b.compile?b.compile.call(Y.self,X,G,Y):b.validate,z=ZJ(W,Q,H),B=W.let("valid");w.block$data(B,A),w.ok(($=b.valid)!==null&&$!==void 0?$:B);function A(){if(b.errors===!1){if(M(),b.modifying)OJ(w);q(()=>w.error())}else{let P=b.async?F():U();if(b.modifying)OJ(w);q(()=>mL(w,P))}}function F(){let P=W.let("ruleErrs",null);return W.try(()=>M(qw._`await `),(k)=>W.assign(B,!1).if(qw._`${k} instanceof ${Y.ValidationError}`,()=>W.assign(P,qw._`${k}.errors`),()=>W.throw(k))),P}function U(){let P=qw._`${z}.errors`;return W.assign(P,null),M(qw.nil),P}function M(P=b.async?qw._`await `:qw.nil){let k=Y.opts.passContext?u1.default.this:u1.default.self,S=!(("compile"in b)&&!J||b.schema===!1);W.assign(B,qw._`${P}${(0,yL.callValidateCode)(w,z,k,S)}`,b.modifying)}function q(P){var k;W.if((0,qw.not)((k=b.valid)!==null&&k!==void 0?k:B),P)}}VJ.funcKeywordCode=cL;function OJ(w){let{gen:b,data:$,it:W}=w;b.if(W.parentData,()=>b.assign($,qw._`${W.parentData}[${W.parentDataProperty}]`))}function mL(w,b){let{gen:$}=w;$.if(qw._`Array.isArray(${b})`,()=>{$.assign(u1.default.vErrors,qw._`${u1.default.vErrors} === null ? ${b} : ${u1.default.vErrors}.concat(${b})`).assign(u1.default.errors,qw._`${u1.default.vErrors}.length`),(0,fL.extendErrors)(w)},()=>w.error())}function lL({schemaEnv:w},b){if(b.async&&!w.$async)throw Error("async keyword in sync schema")}function ZJ(w,b,$){if($===void 0)throw Error(`keyword "${b}" failed to compile`);return w.scopeValue("keyword",typeof $=="function"?{ref:$}:{ref:$,code:(0,qw.stringify)($)})}function gL(w,b,$=!1){return!b.length||b.some((W)=>W==="array"?Array.isArray(w):W==="object"?w&&typeof w=="object"&&!Array.isArray(w):typeof w==W||$&&typeof w>"u")}VJ.validSchemaType=gL;function iL({schema:w,opts:b,self:$,errSchemaPath:W},Q,X){if(Array.isArray(Q.keyword)?!Q.keyword.includes(X):Q.keyword!==X)throw Error("ajv implementation error");let G=Q.dependencies;if(G===null||G===void 0?void 0:G.some((J)=>!Object.prototype.hasOwnProperty.call(w,J)))throw Error(`parent schema must have dependencies of ${X}: ${G.join(",")}`);if(Q.validateSchema){if(!Q.validateSchema(w[X])){let Y=`keyword "${X}" value is invalid at path "${W}": `+$.errorsText(Q.validateSchema.errors);if(b.validateSchema==="log")$.logger.error(Y);else throw Error(Y)}}}VJ.validateKeywordUsage=iL});var NJ=I((PJ)=>{Object.defineProperty(PJ,"__esModule",{value:!0});PJ.extendSubschemaMode=PJ.extendSubschemaData=PJ.getSubschema=void 0;var ew=c(),qJ=o();function oL(w,{keyword:b,schemaProp:$,schema:W,schemaPath:Q,errSchemaPath:X,topSchemaRef:G}){if(b!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(b!==void 0){let J=w.schema[b];return $===void 0?{schema:J,schemaPath:ew._`${w.schemaPath}${(0,ew.getProperty)(b)}`,errSchemaPath:`${w.errSchemaPath}/${b}`}:{schema:J[$],schemaPath:ew._`${w.schemaPath}${(0,ew.getProperty)(b)}${(0,ew.getProperty)($)}`,errSchemaPath:`${w.errSchemaPath}/${b}/${(0,qJ.escapeFragment)($)}`}}if(W!==void 0){if(Q===void 0||X===void 0||G===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:Q,topSchemaRef:G,errSchemaPath:X}}throw Error('either "keyword" or "schema" must be passed')}PJ.getSubschema=oL;function tL(w,b,{dataProp:$,dataPropType:W,data:Q,dataTypes:X,propertyName:G}){if(Q!==void 0&&$!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:J}=b;if($!==void 0){let{errorPath:H,dataPathArr:z,opts:B}=b,A=J.let("data",ew._`${b.data}${(0,ew.getProperty)($)}`,!0);Y(A),w.errorPath=ew.str`${H}${(0,qJ.getErrorPath)($,W,B.jsPropertySyntax)}`,w.parentDataProperty=ew._`${$}`,w.dataPathArr=[...z,w.parentDataProperty]}if(Q!==void 0){let H=Q instanceof ew.Name?Q:J.let("data",Q,!0);if(Y(H),G!==void 0)w.propertyName=G}if(X)w.dataTypes=X;function Y(H){w.data=H,w.dataLevel=b.dataLevel+1,w.dataTypes=[],b.definedProperties=new Set,w.parentData=b.data,w.dataNames=[...b.dataNames,H]}}PJ.extendSubschemaData=tL;function rL(w,{jtdDiscriminator:b,jtdMetadata:$,compositeRule:W,createErrors:Q,allErrors:X}){if(W!==void 0)w.compositeRule=W;if(Q!==void 0)w.createErrors=Q;if(X!==void 0)w.allErrors=X;w.jtdDiscriminator=b,w.jtdMetadata=$}PJ.extendSubschemaMode=rL});var l$=I((sT,EJ)=>{EJ.exports=function w(b,$){if(b===$)return!0;if(b&&$&&typeof b=="object"&&typeof $=="object"){if(b.constructor!==$.constructor)return!1;var W,Q,X;if(Array.isArray(b)){if(W=b.length,W!=$.length)return!1;for(Q=W;Q--!==0;)if(!w(b[Q],$[Q]))return!1;return!0}if(b.constructor===RegExp)return b.source===$.source&&b.flags===$.flags;if(b.valueOf!==Object.prototype.valueOf)return b.valueOf()===$.valueOf();if(b.toString!==Object.prototype.toString)return b.toString()===$.toString();if(X=Object.keys(b),W=X.length,W!==Object.keys($).length)return!1;for(Q=W;Q--!==0;)if(!Object.prototype.hasOwnProperty.call($,X[Q]))return!1;for(Q=W;Q--!==0;){var G=X[Q];if(!w(b[G],$[G]))return!1}return!0}return b!==b&&$!==$}});var RJ=I((eT,TJ)=>{var S1=TJ.exports=function(w,b,$){if(typeof b=="function")$=b,b={};$=b.cb||$;var W=typeof $=="function"?$:$.pre||function(){},Q=$.post||function(){};M6(b,W,Q,w,"",w)};S1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};S1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};S1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};S1.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function M6(w,b,$,W,Q,X,G,J,Y,H){if(W&&typeof W=="object"&&!Array.isArray(W)){b(W,Q,X,G,J,Y,H);for(var z in W){var B=W[z];if(Array.isArray(B)){if(z in S1.arrayKeywords)for(var A=0;A<B.length;A++)M6(w,b,$,B[A],Q+"/"+z+"/"+A,X,Q,z,W,A)}else if(z in S1.propsKeywords){if(B&&typeof B=="object")for(var F in B)M6(w,b,$,B[F],Q+"/"+z+"/"+aL(F),X,Q,z,W,F)}else if(z in S1.keywords||w.allKeys&&!(z in S1.skipKeywords))M6(w,b,$,B,Q+"/"+z,X,Q,z,W)}$(W,Q,X,G,J,Y,H)}}function aL(w){return w.replace(/~/g,"~0").replace(/\//g,"~1")}});var e0=I((kJ)=>{Object.defineProperty(kJ,"__esModule",{value:!0});kJ.getSchemaRefs=kJ.resolveUrl=kJ.normalizeId=kJ._getFullPath=kJ.getFullPath=kJ.inlineRef=void 0;var wU=o(),bU=l$(),$U=RJ(),WU=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function QU(w,b=!0){if(typeof w=="boolean")return!0;if(b===!0)return!g$(w);if(!b)return!1;return SJ(w)<=b}kJ.inlineRef=QU;var XU=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function g$(w){for(let b in w){if(XU.has(b))return!0;let $=w[b];if(Array.isArray($)&&$.some(g$))return!0;if(typeof $=="object"&&g$($))return!0}return!1}function SJ(w){let b=0;for(let $ in w){if($==="$ref")return 1/0;if(b++,WU.has($))continue;if(typeof w[$]=="object")(0,wU.eachItem)(w[$],(W)=>b+=SJ(W));if(b===1/0)return 1/0}return b}function vJ(w,b="",$){if($!==!1)b=Q0(b);let W=w.parse(b);return CJ(w,W)}kJ.getFullPath=vJ;function CJ(w,b){return w.serialize(b).split("#")[0]+"#"}kJ._getFullPath=CJ;var GU=/#\/?$/;function Q0(w){return w?w.replace(GU,""):""}kJ.normalizeId=Q0;function JU(w,b,$){return $=Q0($),w.resolve(b,$)}kJ.resolveUrl=JU;var YU=/^[a-z_][-a-z0-9._]*$/i;function HU(w,b){if(typeof w=="boolean")return{};let{schemaId:$,uriResolver:W}=this.opts,Q=Q0(w[$]||b),X={"":Q},G=vJ(W,Q,!1),J={},Y=new Set;return $U(w,{allKeys:!0},(B,A,F,U)=>{if(U===void 0)return;let M=G+A,q=X[U];if(typeof B[$]=="string")q=P.call(this,B[$]);k.call(this,B.$anchor),k.call(this,B.$dynamicAnchor),X[A]=q;function P(S){let l=this.opts.uriResolver.resolve;if(S=Q0(q?l(q,S):S),Y.has(S))throw z(S);Y.add(S);let _=this.refs[S];if(typeof _=="string")_=this.refs[_];if(typeof _=="object")H(B,_.schema,S);else if(S!==Q0(M))if(S[0]==="#")H(B,J[S],S),J[S]=B;else this.refs[S]=M;return S}function k(S){if(typeof S=="string"){if(!YU.test(S))throw Error(`invalid anchor "${S}"`);P.call(this,`#${S}`)}}}),J;function H(B,A,F){if(A!==void 0&&!bU(B,A))throw z(F)}function z(B){return Error(`reference "${B}" resolves to more than one schema`)}}kJ.getSchemaRefs=HU});var bb=I((tJ)=>{Object.defineProperty(tJ,"__esModule",{value:!0});tJ.getData=tJ.KeywordCxt=tJ.validateFunctionCode=void 0;var uJ=eG(),xJ=s0(),n$=x$(),j6=s0(),LU=AJ(),wb=jJ(),i$=NJ(),R=c(),x=Y1(),UU=e0(),H1=o(),a0=r0();function KU(w){if(lJ(w)){if(gJ(w),mJ(w)){VU(w);return}}cJ(w,()=>(0,uJ.topBoolOrEmptySchema)(w))}tJ.validateFunctionCode=KU;function cJ({gen:w,validateName:b,schema:$,schemaEnv:W,opts:Q},X){if(Q.code.es5)w.func(b,R._`${x.default.data}, ${x.default.valCxt}`,W.$async,()=>{w.code(R._`"use strict"; ${hJ($,Q)}`),ZU(w,Q),w.code(X)});else w.func(b,R._`${x.default.data}, ${OU(Q)}`,W.$async,()=>w.code(hJ($,Q)).code(X))}function OU(w){return R._`{${x.default.instancePath}="", ${x.default.parentData}, ${x.default.parentDataProperty}, ${x.default.rootData}=${x.default.data}${w.dynamicRef?R._`, ${x.default.dynamicAnchors}={}`:R.nil}}={}`}function ZU(w,b){w.if(x.default.valCxt,()=>{if(w.var(x.default.instancePath,R._`${x.default.valCxt}.${x.default.instancePath}`),w.var(x.default.parentData,R._`${x.default.valCxt}.${x.default.parentData}`),w.var(x.default.parentDataProperty,R._`${x.default.valCxt}.${x.default.parentDataProperty}`),w.var(x.default.rootData,R._`${x.default.valCxt}.${x.default.rootData}`),b.dynamicRef)w.var(x.default.dynamicAnchors,R._`${x.default.valCxt}.${x.default.dynamicAnchors}`)},()=>{if(w.var(x.default.instancePath,R._`""`),w.var(x.default.parentData,R._`undefined`),w.var(x.default.parentDataProperty,R._`undefined`),w.var(x.default.rootData,x.default.data),b.dynamicRef)w.var(x.default.dynamicAnchors,R._`{}`)})}function VU(w){let{schema:b,opts:$,gen:W}=w;cJ(w,()=>{if($.$comment&&b.$comment)nJ(w);if(IU(w),W.let(x.default.vErrors,null),W.let(x.default.errors,0),$.unevaluated)MU(w);iJ(w),TU(w)});return}function MU(w){let{gen:b,validateName:$}=w;w.evaluated=b.const("evaluated",R._`${$}.evaluated`),b.if(R._`${w.evaluated}.dynamicProps`,()=>b.assign(R._`${w.evaluated}.props`,R._`undefined`)),b.if(R._`${w.evaluated}.dynamicItems`,()=>b.assign(R._`${w.evaluated}.items`,R._`undefined`))}function hJ(w,b){let $=typeof w=="object"&&w[b.schemaId];return $&&(b.code.source||b.code.process)?R._`/*# sourceURL=${$} */`:R.nil}function jU(w,b){if(lJ(w)){if(gJ(w),mJ(w)){qU(w,b);return}}(0,uJ.boolOrEmptySchema)(w,b)}function mJ({schema:w,self:b}){if(typeof w=="boolean")return!w;for(let $ in w)if(b.RULES.all[$])return!0;return!1}function lJ(w){return typeof w.schema!="boolean"}function qU(w,b){let{schema:$,gen:W,opts:Q}=w;if(Q.$comment&&$.$comment)nJ(w);NU(w),EU(w);let X=W.const("_errs",x.default.errors);iJ(w,X),W.var(b,R._`${X} === ${x.default.errors}`)}function gJ(w){(0,H1.checkUnknownRules)(w),PU(w)}function iJ(w,b){if(w.opts.jtd)return yJ(w,[],!1,b);let $=(0,xJ.getSchemaTypes)(w.schema),W=(0,xJ.coerceAndCheckDataType)(w,$);yJ(w,$,!W,b)}function PU(w){let{schema:b,errSchemaPath:$,opts:W,self:Q}=w;if(b.$ref&&W.ignoreKeywordsWithRef&&(0,H1.schemaHasRulesButRef)(b,Q.RULES))Q.logger.warn(`$ref: keywords ignored in schema at path "${$}"`)}function IU(w){let{schema:b,opts:$}=w;if(b.default!==void 0&&$.useDefaults&&$.strictSchema)(0,H1.checkStrictMode)(w,"default is ignored in the schema root")}function NU(w){let b=w.schema[w.opts.schemaId];if(b)w.baseId=(0,UU.resolveUrl)(w.opts.uriResolver,w.baseId,b)}function EU(w){if(w.schema.$async&&!w.schemaEnv.$async)throw Error("async schema in sync schema")}function nJ({gen:w,schemaEnv:b,schema:$,errSchemaPath:W,opts:Q}){let X=$.$comment;if(Q.$comment===!0)w.code(R._`${x.default.self}.logger.log(${X})`);else if(typeof Q.$comment=="function"){let G=R.str`${W}/$comment`,J=w.scopeValue("root",{ref:b.root});w.code(R._`${x.default.self}.opts.$comment(${X}, ${G}, ${J}.schema)`)}}function TU(w){let{gen:b,schemaEnv:$,validateName:W,ValidationError:Q,opts:X}=w;if($.$async)b.if(R._`${x.default.errors} === 0`,()=>b.return(x.default.data),()=>b.throw(R._`new ${Q}(${x.default.vErrors})`));else{if(b.assign(R._`${W}.errors`,x.default.vErrors),X.unevaluated)RU(w);b.return(R._`${x.default.errors} === 0`)}}function RU({gen:w,evaluated:b,props:$,items:W}){if($ instanceof R.Name)w.assign(R._`${b}.props`,$);if(W instanceof R.Name)w.assign(R._`${b}.items`,W)}function yJ(w,b,$,W){let{gen:Q,schema:X,data:G,allErrors:J,opts:Y,self:H}=w,{RULES:z}=H;if(X.$ref&&(Y.ignoreKeywordsWithRef||!(0,H1.schemaHasRulesButRef)(X,z))){Q.block(()=>dJ(w,"$ref",z.all.$ref.definition));return}if(!Y.jtd)SU(w,b);Q.block(()=>{for(let A of z.rules)B(A);B(z.post)});function B(A){if(!(0,n$.shouldUseGroup)(X,A))return;if(A.type){if(Q.if((0,j6.checkDataType)(A.type,G,Y.strictNumbers)),fJ(w,A),b.length===1&&b[0]===A.type&&$)Q.else(),(0,j6.reportTypeError)(w);Q.endIf()}else fJ(w,A);if(!J)Q.if(R._`${x.default.errors} === ${W||0}`)}}function fJ(w,b){let{gen:$,schema:W,opts:{useDefaults:Q}}=w;if(Q)(0,LU.assignDefaults)(w,b.type);$.block(()=>{for(let X of b.rules)if((0,n$.shouldUseRule)(W,X))dJ(w,X.keyword,X.definition,b.type)})}function SU(w,b){if(w.schemaEnv.meta||!w.opts.strictTypes)return;if(vU(w,b),!w.opts.allowUnionTypes)CU(w,b);kU(w,w.dataTypes)}function vU(w,b){if(!b.length)return;if(!w.dataTypes.length){w.dataTypes=b;return}b.forEach(($)=>{if(!pJ(w.dataTypes,$))p$(w,`type "${$}" not allowed by context "${w.dataTypes.join(",")}"`)}),xU(w,b)}function CU(w,b){if(b.length>1&&!(b.length===2&&b.includes("null")))p$(w,"use allowUnionTypes to allow union type keyword")}function kU(w,b){let $=w.self.RULES.all;for(let W in $){let Q=$[W];if(typeof Q=="object"&&(0,n$.shouldUseRule)(w.schema,Q)){let{type:X}=Q.definition;if(X.length&&!X.some((G)=>_U(b,G)))p$(w,`missing type "${X.join(",")}" for keyword "${W}"`)}}}function _U(w,b){return w.includes(b)||b==="number"&&w.includes("integer")}function pJ(w,b){return w.includes(b)||b==="integer"&&w.includes("number")}function xU(w,b){let $=[];for(let W of w.dataTypes)if(pJ(b,W))$.push(W);else if(b.includes("integer")&&W==="number")$.push("integer");w.dataTypes=$}function p$(w,b){let $=w.schemaEnv.baseId+w.errSchemaPath;b+=` at "${$}" (strictTypes)`,(0,H1.checkStrictMode)(w,b,w.opts.strictTypes)}class d${constructor(w,b,$){if((0,wb.validateKeywordUsage)(w,b,$),this.gen=w.gen,this.allErrors=w.allErrors,this.keyword=$,this.data=w.data,this.schema=w.schema[$],this.$data=b.$data&&w.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,H1.schemaRefOrVal)(w,this.schema,$,this.$data),this.schemaType=b.schemaType,this.parentSchema=w.schema,this.params={},this.it=w,this.def=b,this.$data)this.schemaCode=w.gen.const("vSchema",oJ(this.$data,w));else if(this.schemaCode=this.schemaValue,!(0,wb.validSchemaType)(this.schema,b.schemaType,b.allowUndefined))throw Error(`${$} value must be ${JSON.stringify(b.schemaType)}`);if("code"in b?b.trackErrors:b.errors!==!1)this.errsCount=w.gen.const("_errs",x.default.errors)}result(w,b,$){this.failResult((0,R.not)(w),b,$)}failResult(w,b,$){if(this.gen.if(w),$)$();else this.error();if(b){if(this.gen.else(),b(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(w,b){this.failResult((0,R.not)(w),void 0,b)}fail(w){if(w===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(w),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(w){if(!this.$data)return this.fail(w);let{schemaCode:b}=this;this.fail(R._`${b} !== undefined && (${(0,R.or)(this.invalid$data(),w)})`)}error(w,b,$){if(b){this.setParams(b),this._error(w,$),this.setParams({});return}this._error(w,$)}_error(w,b){(w?a0.reportExtraError:a0.reportError)(this,this.def.error,b)}$dataError(){(0,a0.reportError)(this,this.def.$dataError||a0.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,a0.resetErrorsCount)(this.gen,this.errsCount)}ok(w){if(!this.allErrors)this.gen.if(w)}setParams(w,b){if(b)Object.assign(this.params,w);else this.params=w}block$data(w,b,$=R.nil){this.gen.block(()=>{this.check$data(w,$),b()})}check$data(w=R.nil,b=R.nil){if(!this.$data)return;let{gen:$,schemaCode:W,schemaType:Q,def:X}=this;if($.if((0,R.or)(R._`${W} === undefined`,b)),w!==R.nil)$.assign(w,!0);if(Q.length||X.validateSchema){if($.elseIf(this.invalid$data()),this.$dataError(),w!==R.nil)$.assign(w,!1)}$.else()}invalid$data(){let{gen:w,schemaCode:b,schemaType:$,def:W,it:Q}=this;return(0,R.or)(X(),G());function X(){if($.length){if(!(b instanceof R.Name))throw Error("ajv implementation error");let J=Array.isArray($)?$:[$];return R._`${(0,j6.checkDataTypes)(J,b,Q.opts.strictNumbers,j6.DataType.Wrong)}`}return R.nil}function G(){if(W.validateSchema){let J=w.scopeValue("validate$data",{ref:W.validateSchema});return R._`!${J}(${b})`}return R.nil}}subschema(w,b){let $=(0,i$.getSubschema)(this.it,w);(0,i$.extendSubschemaData)($,this.it,w),(0,i$.extendSubschemaMode)($,w);let W={...this.it,...$,items:void 0,props:void 0};return jU(W,b),W}mergeEvaluated(w,b){let{it:$,gen:W}=this;if(!$.opts.unevaluated)return;if($.props!==!0&&w.props!==void 0)$.props=H1.mergeEvaluated.props(W,w.props,$.props,b);if($.items!==!0&&w.items!==void 0)$.items=H1.mergeEvaluated.items(W,w.items,$.items,b)}mergeValidEvaluated(w,b){let{it:$,gen:W}=this;if($.opts.unevaluated&&($.props!==!0||$.items!==!0))return W.if(b,()=>this.mergeEvaluated(w,R.Name)),!0}}tJ.KeywordCxt=d$;function dJ(w,b,$,W){let Q=new d$(w,$,b);if("code"in $)$.code(Q,W);else if(Q.$data&&$.validate)(0,wb.funcKeywordCode)(Q,$);else if("macro"in $)(0,wb.macroKeywordCode)(Q,$);else if($.compile||$.validate)(0,wb.funcKeywordCode)(Q,$)}var hU=/^\/(?:[^~]|~0|~1)*$/,yU=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function oJ(w,{dataLevel:b,dataNames:$,dataPathArr:W}){let Q,X;if(w==="")return x.default.rootData;if(w[0]==="/"){if(!hU.test(w))throw Error(`Invalid JSON-pointer: ${w}`);Q=w,X=x.default.rootData}else{let H=yU.exec(w);if(!H)throw Error(`Invalid JSON-pointer: ${w}`);let z=+H[1];if(Q=H[2],Q==="#"){if(z>=b)throw Error(Y("property/index",z));return W[b-z]}if(z>b)throw Error(Y("data",z));if(X=$[b-z],!Q)return X}let G=X,J=Q.split("/");for(let H of J)if(H)X=R._`${X}${(0,R.getProperty)((0,H1.unescapeJsonPointer)(H))}`,G=R._`${G} && ${X}`;return G;function Y(H,z){return`Cannot access ${H} ${z} levels up, current level is ${b}`}}tJ.getData=oJ});var q6=I((eJ)=>{Object.defineProperty(eJ,"__esModule",{value:!0});class sJ extends Error{constructor(w){super("validation failed");this.errors=w,this.ajv=this.validation=!0}}eJ.default=sJ});var $b=I((wY)=>{Object.defineProperty(wY,"__esModule",{value:!0});var o$=e0();class aJ extends Error{constructor(w,b,$,W){super(W||`can't resolve reference ${$} from id ${b}`);this.missingRef=(0,o$.resolveUrl)(w,b,$),this.missingSchema=(0,o$.normalizeId)((0,o$.getFullPath)(w,this.missingRef))}}wY.default=aJ});var I6=I((WY)=>{Object.defineProperty(WY,"__esModule",{value:!0});WY.resolveSchema=WY.getCompilingSchema=WY.resolveRef=WY.compileSchema=WY.SchemaEnv=void 0;var iw=c(),lU=q6(),c1=Y1(),nw=e0(),bY=o(),gU=bb();class Wb{constructor(w){var b;this.refs={},this.dynamicAnchors={};let $;if(typeof w.schema=="object")$=w.schema;this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(b=w.baseId)!==null&&b!==void 0?b:(0,nw.normalizeId)($===null||$===void 0?void 0:$[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=$===null||$===void 0?void 0:$.$async,this.refs={}}}WY.SchemaEnv=Wb;function r$(w){let b=$Y.call(this,w);if(b)return b;let $=(0,nw.getFullPath)(this.opts.uriResolver,w.root.baseId),{es5:W,lines:Q}=this.opts.code,{ownProperties:X}=this.opts,G=new iw.CodeGen(this.scope,{es5:W,lines:Q,ownProperties:X}),J;if(w.$async)J=G.scopeValue("Error",{ref:lU.default,code:iw._`require("ajv/dist/runtime/validation_error").default`});let Y=G.scopeName("validate");w.validateName=Y;let H={gen:G,allErrors:this.opts.allErrors,data:c1.default.data,parentData:c1.default.parentData,parentDataProperty:c1.default.parentDataProperty,dataNames:[c1.default.data],dataPathArr:[iw.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:G.scopeValue("schema",this.opts.code.source===!0?{ref:w.schema,code:(0,iw.stringify)(w.schema)}:{ref:w.schema}),validateName:Y,ValidationError:J,schema:w.schema,schemaEnv:w,rootId:$,baseId:w.baseId||$,schemaPath:iw.nil,errSchemaPath:w.schemaPath||(this.opts.jtd?"":"#"),errorPath:iw._`""`,opts:this.opts,self:this},z;try{this._compilations.add(w),(0,gU.validateFunctionCode)(H),G.optimize(this.opts.code.optimize);let B=G.toString();if(z=`${G.scopeRefs(c1.default.scope)}return ${B}`,this.opts.code.process)z=this.opts.code.process(z,w);let F=Function(`${c1.default.self}`,`${c1.default.scope}`,z)(this,this.scope.get());if(this.scope.value(Y,{ref:F}),F.errors=null,F.schema=w.schema,F.schemaEnv=w,w.$async)F.$async=!0;if(this.opts.code.source===!0)F.source={validateName:Y,validateCode:B,scopeValues:G._values};if(this.opts.unevaluated){let{props:U,items:M}=H;if(F.evaluated={props:U instanceof iw.Name?void 0:U,items:M instanceof iw.Name?void 0:M,dynamicProps:U instanceof iw.Name,dynamicItems:M instanceof iw.Name},F.source)F.source.evaluated=(0,iw.stringify)(F.evaluated)}return w.validate=F,w}catch(B){if(delete w.validate,delete w.validateName,z)this.logger.error("Error compiling schema, function code:",z);throw B}finally{this._compilations.delete(w)}}WY.compileSchema=r$;function iU(w,b,$){var W;$=(0,nw.resolveUrl)(this.opts.uriResolver,b,$);let Q=w.refs[$];if(Q)return Q;let X=dU.call(this,w,$);if(X===void 0){let G=(W=w.localRefs)===null||W===void 0?void 0:W[$],{schemaId:J}=this.opts;if(G)X=new Wb({schema:G,schemaId:J,root:w,baseId:b})}if(X===void 0)return;return w.refs[$]=nU.call(this,X)}WY.resolveRef=iU;function nU(w){if((0,nw.inlineRef)(w.schema,this.opts.inlineRefs))return w.schema;return w.validate?w:r$.call(this,w)}function $Y(w){for(let b of this._compilations)if(pU(b,w))return b}WY.getCompilingSchema=$Y;function pU(w,b){return w.schema===b.schema&&w.root===b.root&&w.baseId===b.baseId}function dU(w,b){let $;while(typeof($=this.refs[b])=="string")b=$;return $||this.schemas[b]||P6.call(this,w,b)}function P6(w,b){let $=this.opts.uriResolver.parse(b),W=(0,nw._getFullPath)(this.opts.uriResolver,$),Q=(0,nw.getFullPath)(this.opts.uriResolver,w.baseId,void 0);if(Object.keys(w.schema).length>0&&W===Q)return t$.call(this,$,w);let X=(0,nw.normalizeId)(W),G=this.refs[X]||this.schemas[X];if(typeof G=="string"){let J=P6.call(this,w,G);if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;return t$.call(this,$,J)}if(typeof(G===null||G===void 0?void 0:G.schema)!=="object")return;if(!G.validate)r$.call(this,G);if(X===(0,nw.normalizeId)(b)){let{schema:J}=G,{schemaId:Y}=this.opts,H=J[Y];if(H)Q=(0,nw.resolveUrl)(this.opts.uriResolver,Q,H);return new Wb({schema:J,schemaId:Y,root:w,baseId:Q})}return t$.call(this,$,G)}WY.resolveSchema=P6;var oU=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function t$(w,{baseId:b,schema:$,root:W}){var Q;if(((Q=w.fragment)===null||Q===void 0?void 0:Q[0])!=="/")return;for(let J of w.fragment.slice(1).split("/")){if(typeof $==="boolean")return;let Y=$[(0,bY.unescapeFragment)(J)];if(Y===void 0)return;$=Y;let H=typeof $==="object"&&$[this.opts.schemaId];if(!oU.has(J)&&H)b=(0,nw.resolveUrl)(this.opts.uriResolver,b,H)}let X;if(typeof $!="boolean"&&$.$ref&&!(0,bY.schemaHasRulesButRef)($,this.RULES)){let J=(0,nw.resolveUrl)(this.opts.uriResolver,b,$.$ref);X=P6.call(this,W,J)}let{schemaId:G}=this.opts;if(X=X||new Wb({schema:$,schemaId:G,root:W,baseId:b}),X.schema!==X.root.schema)return X;return}});var XY=I((QR,aU)=>{aU.exports={$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:!1}});var e$=I((XR,HY)=>{var wK=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),JY=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function s$(w){let b="",$=0,W=0;for(W=0;W<w.length;W++){if($=w[W].charCodeAt(0),$===48)continue;if(!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";b+=w[W];break}for(W+=1;W<w.length;W++){if($=w[W].charCodeAt(0),!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";b+=w[W]}return b}var bK=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function GY(w){return w.length=0,!0}function $K(w,b,$){if(w.length){let W=s$(w);if(W!=="")b.push(W);else return $.error=!0,!1;w.length=0}return!0}function WK(w){let b=0,$={error:!1,address:"",zone:""},W=[],Q=[],X=!1,G=!1,J=$K;for(let Y=0;Y<w.length;Y++){let H=w[Y];if(H==="["||H==="]")continue;if(H===":"){if(X===!0)G=!0;if(!J(Q,W,$))break;if(++b>7){$.error=!0;break}if(Y>0&&w[Y-1]===":")X=!0;W.push(":");continue}else if(H==="%"){if(!J(Q,W,$))break;J=GY}else{Q.push(H);continue}}if(Q.length)if(J===GY)$.zone=Q.join("");else if(G)W.push(Q.join(""));else W.push(s$(Q));return $.address=W.join(""),$}function YY(w){if(QK(w,":")<2)return{host:w,isIPV6:!1};let b=WK(w);if(!b.error){let{address:$,address:W}=b;if(b.zone)$+="%"+b.zone,W+="%25"+b.zone;return{host:$,isIPV6:!0,escapedHost:W}}else return{host:w,isIPV6:!1}}function QK(w,b){let $=0;for(let W=0;W<w.length;W++)if(w[W]===b)$++;return $}function XK(w){let b=w,$=[],W=-1,Q=0;while(Q=b.length){if(Q===1)if(b===".")break;else if(b==="/"){$.push("/");break}else{$.push(b);break}else if(Q===2){if(b[0]==="."){if(b[1]===".")break;else if(b[1]==="/"){b=b.slice(2);continue}}else if(b[0]==="/"){if(b[1]==="."||b[1]==="/"){$.push("/");break}}}else if(Q===3){if(b==="/.."){if($.length!==0)$.pop();$.push("/");break}}if(b[0]==="."){if(b[1]==="."){if(b[2]==="/"){b=b.slice(3);continue}}else if(b[1]==="/"){b=b.slice(2);continue}}else if(b[0]==="/"){if(b[1]==="."){if(b[2]==="/"){b=b.slice(2);continue}else if(b[2]==="."){if(b[3]==="/"){if(b=b.slice(3),$.length!==0)$.pop();continue}}}}if((W=b.indexOf("/",1))===-1){$.push(b);break}else $.push(b.slice(0,W)),b=b.slice(W)}return $.join("")}function GK(w,b){let $=b!==!0?escape:unescape;if(w.scheme!==void 0)w.scheme=$(w.scheme);if(w.userinfo!==void 0)w.userinfo=$(w.userinfo);if(w.host!==void 0)w.host=$(w.host);if(w.path!==void 0)w.path=$(w.path);if(w.query!==void 0)w.query=$(w.query);if(w.fragment!==void 0)w.fragment=$(w.fragment);return w}function JK(w){let b=[];if(w.userinfo!==void 0)b.push(w.userinfo),b.push("@");if(w.host!==void 0){let $=unescape(w.host);if(!JY($)){let W=YY($);if(W.isIPV6===!0)$=`[${W.escapedHost}]`;else $=w.host}b.push($)}if(typeof w.port==="number"||typeof w.port==="string")b.push(":"),b.push(String(w.port));return b.length?b.join(""):void 0}HY.exports={nonSimpleDomain:bK,recomposeAuthority:JK,normalizeComponentEncoding:GK,removeDotSegments:XK,isIPv4:JY,isUUID:wK,normalizeIPv6:YY,stringArrayToHexStripped:s$}});var FY=I((GR,AY)=>{var{isUUID:YK}=e$(),HK=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,zK=["http","https","ws","wss","urn","urn:uuid"];function DK(w){return zK.indexOf(w)!==-1}function a$(w){if(w.secure===!0)return!0;else if(w.secure===!1)return!1;else if(w.scheme)return w.scheme.length===3&&(w.scheme[0]==="w"||w.scheme[0]==="W")&&(w.scheme[1]==="s"||w.scheme[1]==="S")&&(w.scheme[2]==="s"||w.scheme[2]==="S");else return!1}function zY(w){if(!w.host)w.error=w.error||"HTTP URIs must have a host.";return w}function DY(w){let b=String(w.scheme).toLowerCase()==="https";if(w.port===(b?443:80)||w.port==="")w.port=void 0;if(!w.path)w.path="/";return w}function BK(w){return w.secure=a$(w),w.resourceName=(w.path||"/")+(w.query?"?"+w.query:""),w.path=void 0,w.query=void 0,w}function AK(w){if(w.port===(a$(w)?443:80)||w.port==="")w.port=void 0;if(typeof w.secure==="boolean")w.scheme=w.secure?"wss":"ws",w.secure=void 0;if(w.resourceName){let[b,$]=w.resourceName.split("?");w.path=b&&b!=="/"?b:void 0,w.query=$,w.resourceName=void 0}return w.fragment=void 0,w}function FK(w,b){if(!w.path)return w.error="URN can not be parsed",w;let $=w.path.match(HK);if($){let W=b.scheme||w.scheme||"urn";w.nid=$[1].toLowerCase(),w.nss=$[2];let Q=`${W}:${b.nid||w.nid}`,X=w9(Q);if(w.path=void 0,X)w=X.parse(w,b)}else w.error=w.error||"URN can not be parsed.";return w}function LK(w,b){if(w.nid===void 0)throw Error("URN without nid cannot be serialized");let $=b.scheme||w.scheme||"urn",W=w.nid.toLowerCase(),Q=`${$}:${b.nid||W}`,X=w9(Q);if(X)w=X.serialize(w,b);let G=w,J=w.nss;return G.path=`${W||b.nid}:${J}`,b.skipEscape=!0,G}function UK(w,b){let $=w;if($.uuid=$.nss,$.nss=void 0,!b.tolerant&&(!$.uuid||!YK($.uuid)))$.error=$.error||"UUID is not valid.";return $}function KK(w){let b=w;return b.nss=(w.uuid||"").toLowerCase(),b}var BY={scheme:"http",domainHost:!0,parse:zY,serialize:DY},OK={scheme:"https",domainHost:BY.domainHost,parse:zY,serialize:DY},N6={scheme:"ws",domainHost:!0,parse:BK,serialize:AK},ZK={scheme:"wss",domainHost:N6.domainHost,parse:N6.parse,serialize:N6.serialize},VK={scheme:"urn",parse:FK,serialize:LK,skipNormalize:!0},MK={scheme:"urn:uuid",parse:UK,serialize:KK,skipNormalize:!0},E6={http:BY,https:OK,ws:N6,wss:ZK,urn:VK,"urn:uuid":MK};Object.setPrototypeOf(E6,null);function w9(w){return w&&(E6[w]||E6[w.toLowerCase()])||void 0}AY.exports={wsIsSecure:a$,SCHEMES:E6,isValidSchemeName:DK,getSchemeHandler:w9}});var KY=I((JR,R6)=>{var{normalizeIPv6:jK,removeDotSegments:Qb,recomposeAuthority:qK,normalizeComponentEncoding:T6,isIPv4:PK,nonSimpleDomain:IK}=e$(),{SCHEMES:NK,getSchemeHandler:LY}=FY();function EK(w,b){if(typeof w==="string")w=aw(z1(w,b),b);else if(typeof w==="object")w=z1(aw(w,b),b);return w}function TK(w,b,$){let W=$?Object.assign({scheme:"null"},$):{scheme:"null"},Q=UY(z1(w,W),z1(b,W),W,!0);return W.skipEscape=!0,aw(Q,W)}function UY(w,b,$,W){let Q={};if(!W)w=z1(aw(w,$),$),b=z1(aw(b,$),$);if($=$||{},!$.tolerant&&b.scheme)Q.scheme=b.scheme,Q.userinfo=b.userinfo,Q.host=b.host,Q.port=b.port,Q.path=Qb(b.path||""),Q.query=b.query;else{if(b.userinfo!==void 0||b.host!==void 0||b.port!==void 0)Q.userinfo=b.userinfo,Q.host=b.host,Q.port=b.port,Q.path=Qb(b.path||""),Q.query=b.query;else{if(!b.path)if(Q.path=w.path,b.query!==void 0)Q.query=b.query;else Q.query=w.query;else{if(b.path[0]==="/")Q.path=Qb(b.path);else{if((w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)&&!w.path)Q.path="/"+b.path;else if(!w.path)Q.path=b.path;else Q.path=w.path.slice(0,w.path.lastIndexOf("/")+1)+b.path;Q.path=Qb(Q.path)}Q.query=b.query}Q.userinfo=w.userinfo,Q.host=w.host,Q.port=w.port}Q.scheme=w.scheme}return Q.fragment=b.fragment,Q}function RK(w,b,$){if(typeof w==="string")w=unescape(w),w=aw(T6(z1(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=aw(T6(w,!0),{...$,skipEscape:!0});if(typeof b==="string")b=unescape(b),b=aw(T6(z1(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=aw(T6(b,!0),{...$,skipEscape:!0});return w.toLowerCase()===b.toLowerCase()}function aw(w,b){let $={host:w.host,scheme:w.scheme,userinfo:w.userinfo,port:w.port,path:w.path,query:w.query,nid:w.nid,nss:w.nss,uuid:w.uuid,fragment:w.fragment,reference:w.reference,resourceName:w.resourceName,secure:w.secure,error:""},W=Object.assign({},b),Q=[],X=LY(W.scheme||$.scheme);if(X&&X.serialize)X.serialize($,W);if($.path!==void 0)if(!W.skipEscape){if($.path=escape($.path),$.scheme!==void 0)$.path=$.path.split("%3A").join(":")}else $.path=unescape($.path);if(W.reference!=="suffix"&&$.scheme)Q.push($.scheme,":");let G=qK($);if(G!==void 0){if(W.reference!=="suffix")Q.push("//");if(Q.push(G),$.path&&$.path[0]!=="/")Q.push("/")}if($.path!==void 0){let J=$.path;if(!W.absolutePath&&(!X||!X.absolutePath))J=Qb(J);if(G===void 0&&J[0]==="/"&&J[1]==="/")J="/%2F"+J.slice(2);Q.push(J)}if($.query!==void 0)Q.push("?",$.query);if($.fragment!==void 0)Q.push("#",$.fragment);return Q.join("")}var SK=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function z1(w,b){let $=Object.assign({},b),W={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},Q=!1;if($.reference==="suffix")if($.scheme)w=$.scheme+":"+w;else w="//"+w;let X=w.match(SK);if(X){if(W.scheme=X[1],W.userinfo=X[3],W.host=X[4],W.port=parseInt(X[5],10),W.path=X[6]||"",W.query=X[7],W.fragment=X[8],isNaN(W.port))W.port=X[5];if(W.host)if(PK(W.host)===!1){let Y=jK(W.host);W.host=Y.host.toLowerCase(),Q=Y.isIPV6}else Q=!0;if(W.scheme===void 0&&W.userinfo===void 0&&W.host===void 0&&W.port===void 0&&W.query===void 0&&!W.path)W.reference="same-document";else if(W.scheme===void 0)W.reference="relative";else if(W.fragment===void 0)W.reference="absolute";else W.reference="uri";if($.reference&&$.reference!=="suffix"&&$.reference!==W.reference)W.error=W.error||"URI is not a "+$.reference+" reference.";let G=LY($.scheme||W.scheme);if(!$.unicodeSupport&&(!G||!G.unicodeSupport)){if(W.host&&($.domainHost||G&&G.domainHost)&&Q===!1&&IK(W.host))try{W.host=URL.domainToASCII(W.host.toLowerCase())}catch(J){W.error=W.error||"Host's domain name can not be converted to ASCII: "+J}}if(!G||G&&!G.skipNormalize){if(w.indexOf("%")!==-1){if(W.scheme!==void 0)W.scheme=unescape(W.scheme);if(W.host!==void 0)W.host=unescape(W.host)}if(W.path)W.path=escape(unescape(W.path));if(W.fragment)W.fragment=encodeURI(decodeURIComponent(W.fragment))}if(G&&G.parse)G.parse(W,$)}else W.error=W.error||"URI can not be parsed.";return W}var b9={SCHEMES:NK,normalize:EK,resolve:TK,resolveComponent:UY,equal:RK,serialize:aw,parse:z1};R6.exports=b9;R6.exports.default=b9;R6.exports.fastUri=b9});var VY=I((ZY)=>{Object.defineProperty(ZY,"__esModule",{value:!0});var OY=KY();OY.code='require("ajv/dist/runtime/uri").default';ZY.default=OY});var TY=I((D1)=>{Object.defineProperty(D1,"__esModule",{value:!0});D1.CodeGen=D1.Name=D1.nil=D1.stringify=D1.str=D1._=D1.KeywordCxt=void 0;var CK=bb();Object.defineProperty(D1,"KeywordCxt",{enumerable:!0,get:function(){return CK.KeywordCxt}});var X0=c();Object.defineProperty(D1,"_",{enumerable:!0,get:function(){return X0._}});Object.defineProperty(D1,"str",{enumerable:!0,get:function(){return X0.str}});Object.defineProperty(D1,"stringify",{enumerable:!0,get:function(){return X0.stringify}});Object.defineProperty(D1,"nil",{enumerable:!0,get:function(){return X0.nil}});Object.defineProperty(D1,"Name",{enumerable:!0,get:function(){return X0.Name}});Object.defineProperty(D1,"CodeGen",{enumerable:!0,get:function(){return X0.CodeGen}});var kK=q6(),IY=$b(),_K=_$(),Xb=I6(),xK=c(),Gb=e0(),S6=s0(),W9=o(),MY=XY(),hK=VY(),NY=(w,b)=>new RegExp(w,b);NY.code="new RegExp";var yK=["removeAdditional","useDefaults","coerceTypes"],fK=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),uK={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},cK={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},jY=200;function mK(w){var b,$,W,Q,X,G,J,Y,H,z,B,A,F,U,M,q,P,k,S,l,_,rw,$1,z4,D4;let V0=w.strict,B4=(b=w.code)===null||b===void 0?void 0:b.optimize,zW=B4===!0||B4===void 0?1:B4||0,DW=(W=($=w.code)===null||$===void 0?void 0:$.regExp)!==null&&W!==void 0?W:NY,f3=(Q=w.uriResolver)!==null&&Q!==void 0?Q:hK.default;return{strictSchema:(G=(X=w.strictSchema)!==null&&X!==void 0?X:V0)!==null&&G!==void 0?G:!0,strictNumbers:(Y=(J=w.strictNumbers)!==null&&J!==void 0?J:V0)!==null&&Y!==void 0?Y:!0,strictTypes:(z=(H=w.strictTypes)!==null&&H!==void 0?H:V0)!==null&&z!==void 0?z:"log",strictTuples:(A=(B=w.strictTuples)!==null&&B!==void 0?B:V0)!==null&&A!==void 0?A:"log",strictRequired:(U=(F=w.strictRequired)!==null&&F!==void 0?F:V0)!==null&&U!==void 0?U:!1,code:w.code?{...w.code,optimize:zW,regExp:DW}:{optimize:zW,regExp:DW},loopRequired:(M=w.loopRequired)!==null&&M!==void 0?M:jY,loopEnum:(q=w.loopEnum)!==null&&q!==void 0?q:jY,meta:(P=w.meta)!==null&&P!==void 0?P:!0,messages:(k=w.messages)!==null&&k!==void 0?k:!0,inlineRefs:(S=w.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(l=w.schemaId)!==null&&l!==void 0?l:"$id",addUsedSchema:(_=w.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(rw=w.validateSchema)!==null&&rw!==void 0?rw:!0,validateFormats:($1=w.validateFormats)!==null&&$1!==void 0?$1:!0,unicodeRegExp:(z4=w.unicodeRegExp)!==null&&z4!==void 0?z4:!0,int32range:(D4=w.int32range)!==null&&D4!==void 0?D4:!0,uriResolver:f3}}class v6{constructor(w={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,w=this.opts={...w,...mK(w)};let{es5:b,lines:$}=this.opts.code;this.scope=new xK.ValueScope({scope:{},prefixes:fK,es5:b,lines:$}),this.logger=dK(w.logger);let W=w.validateFormats;if(w.validateFormats=!1,this.RULES=(0,_K.getRules)(),qY.call(this,uK,w,"NOT SUPPORTED"),qY.call(this,cK,w,"DEPRECATED","warn"),this._metaOpts=nK.call(this),w.formats)gK.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),w.keywords)iK.call(this,w.keywords);if(typeof w.meta=="object")this.addMetaSchema(w.meta);lK.call(this),w.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:w,meta:b,schemaId:$}=this.opts,W=MY;if($==="id")W={...MY},W.id=W.$id,delete W.$id;if(b&&w)this.addMetaSchema(W,W[$],!1)}defaultMeta(){let{meta:w,schemaId:b}=this.opts;return this.opts.defaultMeta=typeof w=="object"?w[b]||w:void 0}validate(w,b){let $;if(typeof w=="string"){if($=this.getSchema(w),!$)throw Error(`no schema with key or ref "${w}"`)}else $=this.compile(w);let W=$(b);if(!("$async"in $))this.errors=$.errors;return W}compile(w,b){let $=this._addSchema(w,b);return $.validate||this._compileSchemaEnv($)}compileAsync(w,b){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:$}=this.opts;return W.call(this,w,b);async function W(H,z){await Q.call(this,H.$schema);let B=this._addSchema(H,z);return B.validate||X.call(this,B)}async function Q(H){if(H&&!this.getSchema(H))await W.call(this,{$ref:H},!0)}async function X(H){try{return this._compileSchemaEnv(H)}catch(z){if(!(z instanceof IY.default))throw z;return G.call(this,z),await J.call(this,z.missingSchema),X.call(this,H)}}function G({missingSchema:H,missingRef:z}){if(this.refs[H])throw Error(`AnySchema ${H} is loaded but ${z} cannot be resolved`)}async function J(H){let z=await Y.call(this,H);if(!this.refs[H])await Q.call(this,z.$schema);if(!this.refs[H])this.addSchema(z,H,b)}async function Y(H){let z=this._loading[H];if(z)return z;try{return await(this._loading[H]=$(H))}finally{delete this._loading[H]}}}addSchema(w,b,$,W=this.opts.validateSchema){if(Array.isArray(w)){for(let X of w)this.addSchema(X,void 0,$,W);return this}let Q;if(typeof w==="object"){let{schemaId:X}=this.opts;if(Q=w[X],Q!==void 0&&typeof Q!="string")throw Error(`schema ${X} must be string`)}return b=(0,Gb.normalizeId)(b||Q),this._checkUnique(b),this.schemas[b]=this._addSchema(w,$,b,W,!0),this}addMetaSchema(w,b,$=this.opts.validateSchema){return this.addSchema(w,b,!0,$),this}validateSchema(w,b){if(typeof w=="boolean")return!0;let $;if($=w.$schema,$!==void 0&&typeof $!="string")throw Error("$schema must be a string");if($=$||this.opts.defaultMeta||this.defaultMeta(),!$)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let W=this.validate($,w);if(!W&&b){let Q="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(Q);else throw Error(Q)}return W}getSchema(w){let b;while(typeof(b=PY.call(this,w))=="string")w=b;if(b===void 0){let{schemaId:$}=this.opts,W=new Xb.SchemaEnv({schema:{},schemaId:$});if(b=Xb.resolveSchema.call(this,W,w),!b)return;this.refs[w]=b}return b.validate||this._compileSchemaEnv(b)}removeSchema(w){if(w instanceof RegExp)return this._removeAllSchemas(this.schemas,w),this._removeAllSchemas(this.refs,w),this;switch(typeof w){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let b=PY.call(this,w);if(typeof b=="object")this._cache.delete(b.schema);return delete this.schemas[w],delete this.refs[w],this}case"object":{let b=w;this._cache.delete(b);let $=w[this.opts.schemaId];if($)$=(0,Gb.normalizeId)($),delete this.schemas[$],delete this.refs[$];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(w){for(let b of w)this.addKeyword(b);return this}addKeyword(w,b){let $;if(typeof w=="string"){if($=w,typeof b=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),b.keyword=$}else if(typeof w=="object"&&b===void 0){if(b=w,$=b.keyword,Array.isArray($)&&!$.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(tK.call(this,$,b),!b)return(0,W9.eachItem)($,(Q)=>$9.call(this,Q)),this;sK.call(this,b);let W={...b,type:(0,S6.getJSONTypes)(b.type),schemaType:(0,S6.getJSONTypes)(b.schemaType)};return(0,W9.eachItem)($,W.type.length===0?(Q)=>$9.call(this,Q,W):(Q)=>W.type.forEach((X)=>$9.call(this,Q,W,X))),this}getKeyword(w){let b=this.RULES.all[w];return typeof b=="object"?b.definition:!!b}removeKeyword(w){let{RULES:b}=this;delete b.keywords[w],delete b.all[w];for(let $ of b.rules){let W=$.rules.findIndex((Q)=>Q.keyword===w);if(W>=0)$.rules.splice(W,1)}return this}addFormat(w,b){if(typeof b=="string")b=new RegExp(b);return this.formats[w]=b,this}errorsText(w=this.errors,{separator:b=", ",dataVar:$="data"}={}){if(!w||w.length===0)return"No errors";return w.map((W)=>`${$}${W.instancePath} ${W.message}`).reduce((W,Q)=>W+b+Q)}$dataMetaSchema(w,b){let $=this.RULES.all;w=JSON.parse(JSON.stringify(w));for(let W of b){let Q=W.split("/").slice(1),X=w;for(let G of Q)X=X[G];for(let G in $){let J=$[G];if(typeof J!="object")continue;let{$data:Y}=J.definition,H=X[G];if(Y&&H)X[G]=EY(H)}}return w}_removeAllSchemas(w,b){for(let $ in w){let W=w[$];if(!b||b.test($)){if(typeof W=="string")delete w[$];else if(W&&!W.meta)this._cache.delete(W.schema),delete w[$]}}}_addSchema(w,b,$,W=this.opts.validateSchema,Q=this.opts.addUsedSchema){let X,{schemaId:G}=this.opts;if(typeof w=="object")X=w[G];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof w!="boolean")throw Error("schema must be object or boolean");let J=this._cache.get(w);if(J!==void 0)return J;$=(0,Gb.normalizeId)(X||$);let Y=Gb.getSchemaRefs.call(this,w,$);if(J=new Xb.SchemaEnv({schema:w,schemaId:G,meta:b,baseId:$,localRefs:Y}),this._cache.set(J.schema,J),Q&&!$.startsWith("#")){if($)this._checkUnique($);this.refs[$]=J}if(W)this.validateSchema(w,!0);return J}_checkUnique(w){if(this.schemas[w]||this.refs[w])throw Error(`schema with key or id "${w}" already exists`)}_compileSchemaEnv(w){if(w.meta)this._compileMetaSchema(w);else Xb.compileSchema.call(this,w);if(!w.validate)throw Error("ajv implementation error");return w.validate}_compileMetaSchema(w){let b=this.opts;this.opts=this._metaOpts;try{Xb.compileSchema.call(this,w)}finally{this.opts=b}}}v6.ValidationError=kK.default;v6.MissingRefError=IY.default;D1.default=v6;function qY(w,b,$,W="error"){for(let Q in w){let X=Q;if(X in b)this.logger[W](`${$}: option ${Q}. ${w[X]}`)}}function PY(w){return w=(0,Gb.normalizeId)(w),this.schemas[w]||this.refs[w]}function lK(){let w=this.opts.schemas;if(!w)return;if(Array.isArray(w))this.addSchema(w);else for(let b in w)this.addSchema(w[b],b)}function gK(){for(let w in this.opts.formats){let b=this.opts.formats[w];if(b)this.addFormat(w,b)}}function iK(w){if(Array.isArray(w)){this.addVocabulary(w);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let b in w){let $=w[b];if(!$.keyword)$.keyword=b;this.addKeyword($)}}function nK(){let w={...this.opts};for(let b of yK)delete w[b];return w}var pK={log(){},warn(){},error(){}};function dK(w){if(w===!1)return pK;if(w===void 0)return console;if(w.log&&w.warn&&w.error)return w;throw Error("logger must implement log, warn and error methods")}var oK=/^[a-z_$][a-z0-9_$:-]*$/i;function tK(w,b){let{RULES:$}=this;if((0,W9.eachItem)(w,(W)=>{if($.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!oK.test(W))throw Error(`Keyword ${W} has invalid name`)}),!b)return;if(b.$data&&!(("code"in b)||("validate"in b)))throw Error('$data keyword must have "code" or "validate" function')}function $9(w,b,$){var W;let Q=b===null||b===void 0?void 0:b.post;if($&&Q)throw Error('keyword with "post" flag cannot have "type"');let{RULES:X}=this,G=Q?X.post:X.rules.find(({type:Y})=>Y===$);if(!G)G={type:$,rules:[]},X.rules.push(G);if(X.keywords[w]=!0,!b)return;let J={keyword:w,definition:{...b,type:(0,S6.getJSONTypes)(b.type),schemaType:(0,S6.getJSONTypes)(b.schemaType)}};if(b.before)rK.call(this,G,J,b.before);else G.rules.push(J);X.all[w]=J,(W=b.implements)===null||W===void 0||W.forEach((Y)=>this.addKeyword(Y))}function rK(w,b,$){let W=w.rules.findIndex((Q)=>Q.keyword===$);if(W>=0)w.rules.splice(W,0,b);else w.rules.push(b),this.logger.warn(`rule ${$} is not defined`)}function sK(w){let{metaSchema:b}=w;if(b===void 0)return;if(w.$data&&this.opts.$data)b=EY(b);w.validateSchema=this.compile(b,!0)}var eK={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function EY(w){return{anyOf:[w,eK]}}});var SY=I((RY)=>{Object.defineProperty(RY,"__esModule",{value:!0});var bO={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};RY.default=bO});var hY=I((_Y)=>{Object.defineProperty(_Y,"__esModule",{value:!0});_Y.callRef=_Y.getValidate=void 0;var WO=$b(),vY=fw(),Tw=c(),G0=Y1(),CY=I6(),C6=o(),QO={keyword:"$ref",schemaType:"string",code(w){let{gen:b,schema:$,it:W}=w,{baseId:Q,schemaEnv:X,validateName:G,opts:J,self:Y}=W,{root:H}=X;if(($==="#"||$==="#/")&&Q===H.baseId)return B();let z=CY.resolveRef.call(Y,H,Q,$);if(z===void 0)throw new WO.default(W.opts.uriResolver,Q,$);if(z instanceof CY.SchemaEnv)return A(z);return F(z);function B(){if(X===H)return k6(w,G,X,X.$async);let U=b.scopeValue("root",{ref:H});return k6(w,Tw._`${U}.validate`,H,H.$async)}function A(U){let M=kY(w,U);k6(w,M,U,U.$async)}function F(U){let M=b.scopeValue("schema",J.code.source===!0?{ref:U,code:(0,Tw.stringify)(U)}:{ref:U}),q=b.name("valid"),P=w.subschema({schema:U,dataTypes:[],schemaPath:Tw.nil,topSchemaRef:M,errSchemaPath:$},q);w.mergeEvaluated(P),w.ok(q)}}};function kY(w,b){let{gen:$}=w;return b.validate?$.scopeValue("validate",{ref:b.validate}):Tw._`${$.scopeValue("wrapper",{ref:b})}.validate`}_Y.getValidate=kY;function k6(w,b,$,W){let{gen:Q,it:X}=w,{allErrors:G,schemaEnv:J,opts:Y}=X,H=Y.passContext?G0.default.this:Tw.nil;if(W)z();else B();function z(){if(!J.$async)throw Error("async schema referenced by sync schema");let U=Q.let("valid");Q.try(()=>{if(Q.code(Tw._`await ${(0,vY.callValidateCode)(w,b,H)}`),F(b),!G)Q.assign(U,!0)},(M)=>{if(Q.if(Tw._`!(${M} instanceof ${X.ValidationError})`,()=>Q.throw(M)),A(M),!G)Q.assign(U,!1)}),w.ok(U)}function B(){w.result((0,vY.callValidateCode)(w,b,H),()=>F(b),()=>A(b))}function A(U){let M=Tw._`${U}.errors`;Q.assign(G0.default.vErrors,Tw._`${G0.default.vErrors} === null ? ${M} : ${G0.default.vErrors}.concat(${M})`),Q.assign(G0.default.errors,Tw._`${G0.default.vErrors}.length`)}function F(U){var M;if(!X.opts.unevaluated)return;let q=(M=$===null||$===void 0?void 0:$.validate)===null||M===void 0?void 0:M.evaluated;if(X.props!==!0)if(q&&!q.dynamicProps){if(q.props!==void 0)X.props=C6.mergeEvaluated.props(Q,q.props,X.props)}else{let P=Q.var("props",Tw._`${U}.evaluated.props`);X.props=C6.mergeEvaluated.props(Q,P,X.props,Tw.Name)}if(X.items!==!0)if(q&&!q.dynamicItems){if(q.items!==void 0)X.items=C6.mergeEvaluated.items(Q,q.items,X.items)}else{let P=Q.var("items",Tw._`${U}.evaluated.items`);X.items=C6.mergeEvaluated.items(Q,P,X.items,Tw.Name)}}}_Y.callRef=k6;_Y.default=QO});var fY=I((yY)=>{Object.defineProperty(yY,"__esModule",{value:!0});var JO=SY(),YO=hY(),HO=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",JO.default,YO.default];yY.default=HO});var cY=I((uY)=>{Object.defineProperty(uY,"__esModule",{value:!0});var _6=c(),v1=_6.operators,x6={maximum:{okStr:"<=",ok:v1.LTE,fail:v1.GT},minimum:{okStr:">=",ok:v1.GTE,fail:v1.LT},exclusiveMaximum:{okStr:"<",ok:v1.LT,fail:v1.GTE},exclusiveMinimum:{okStr:">",ok:v1.GT,fail:v1.LTE}},DO={message:({keyword:w,schemaCode:b})=>_6.str`must be ${x6[w].okStr} ${b}`,params:({keyword:w,schemaCode:b})=>_6._`{comparison: ${x6[w].okStr}, limit: ${b}}`},BO={keyword:Object.keys(x6),type:"number",schemaType:"number",$data:!0,error:DO,code(w){let{keyword:b,data:$,schemaCode:W}=w;w.fail$data(_6._`${$} ${x6[b].fail} ${W} || isNaN(${$})`)}};uY.default=BO});var lY=I((mY)=>{Object.defineProperty(mY,"__esModule",{value:!0});var Jb=c(),FO={message:({schemaCode:w})=>Jb.str`must be multiple of ${w}`,params:({schemaCode:w})=>Jb._`{multipleOf: ${w}}`},LO={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:FO,code(w){let{gen:b,data:$,schemaCode:W,it:Q}=w,X=Q.opts.multipleOfPrecision,G=b.let("res"),J=X?Jb._`Math.abs(Math.round(${G}) - ${G}) > 1e-${X}`:Jb._`${G} !== parseInt(${G})`;w.fail$data(Jb._`(${W} === 0 || (${G} = ${$}/${W}, ${J}))`)}};mY.default=LO});var nY=I((iY)=>{Object.defineProperty(iY,"__esModule",{value:!0});function gY(w){let b=w.length,$=0,W=0,Q;while(W<b)if($++,Q=w.charCodeAt(W++),Q>=55296&&Q<=56319&&W<b){if(Q=w.charCodeAt(W),(Q&64512)===56320)W++}return $}iY.default=gY;gY.code='require("ajv/dist/runtime/ucs2length").default'});var dY=I((pY)=>{Object.defineProperty(pY,"__esModule",{value:!0});var m1=c(),OO=o(),ZO=nY(),VO={message({keyword:w,schemaCode:b}){let $=w==="maxLength"?"more":"fewer";return m1.str`must NOT have ${$} than ${b} characters`},params:({schemaCode:w})=>m1._`{limit: ${w}}`},MO={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:VO,code(w){let{keyword:b,data:$,schemaCode:W,it:Q}=w,X=b==="maxLength"?m1.operators.GT:m1.operators.LT,G=Q.opts.unicode===!1?m1._`${$}.length`:m1._`${(0,OO.useFunc)(w.gen,ZO.default)}(${$})`;w.fail$data(m1._`${G} ${X} ${W}`)}};pY.default=MO});var tY=I((oY)=>{Object.defineProperty(oY,"__esModule",{value:!0});var qO=fw(),h6=c(),PO={message:({schemaCode:w})=>h6.str`must match pattern "${w}"`,params:({schemaCode:w})=>h6._`{pattern: ${w}}`},IO={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:PO,code(w){let{data:b,$data:$,schema:W,schemaCode:Q,it:X}=w,G=X.opts.unicodeRegExp?"u":"",J=$?h6._`(new RegExp(${Q}, ${G}))`:(0,qO.usePattern)(w,W);w.fail$data(h6._`!${J}.test(${b})`)}};oY.default=IO});var sY=I((rY)=>{Object.defineProperty(rY,"__esModule",{value:!0});var Yb=c(),EO={message({keyword:w,schemaCode:b}){let $=w==="maxProperties"?"more":"fewer";return Yb.str`must NOT have ${$} than ${b} properties`},params:({schemaCode:w})=>Yb._`{limit: ${w}}`},TO={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:EO,code(w){let{keyword:b,data:$,schemaCode:W}=w,Q=b==="maxProperties"?Yb.operators.GT:Yb.operators.LT;w.fail$data(Yb._`Object.keys(${$}).length ${Q} ${W}`)}};rY.default=TO});var aY=I((eY)=>{Object.defineProperty(eY,"__esModule",{value:!0});var Hb=fw(),zb=c(),SO=o(),vO={message:({params:{missingProperty:w}})=>zb.str`must have required property '${w}'`,params:({params:{missingProperty:w}})=>zb._`{missingProperty: ${w}}`},CO={keyword:"required",type:"object",schemaType:"array",$data:!0,error:vO,code(w){let{gen:b,schema:$,schemaCode:W,data:Q,$data:X,it:G}=w,{opts:J}=G;if(!X&&$.length===0)return;let Y=$.length>=J.loopRequired;if(G.allErrors)H();else z();if(J.strictRequired){let F=w.parentSchema.properties,{definedProperties:U}=w.it;for(let M of $)if((F===null||F===void 0?void 0:F[M])===void 0&&!U.has(M)){let q=G.schemaEnv.baseId+G.errSchemaPath,P=`required property "${M}" is not defined at "${q}" (strictRequired)`;(0,SO.checkStrictMode)(G,P,G.opts.strictRequired)}}function H(){if(Y||X)w.block$data(zb.nil,B);else for(let F of $)(0,Hb.checkReportMissingProp)(w,F)}function z(){let F=b.let("missing");if(Y||X){let U=b.let("valid",!0);w.block$data(U,()=>A(F,U)),w.ok(U)}else b.if((0,Hb.checkMissingProp)(w,$,F)),(0,Hb.reportMissingProp)(w,F),b.else()}function B(){b.forOf("prop",W,(F)=>{w.setParams({missingProperty:F}),b.if((0,Hb.noPropertyInData)(b,Q,F,J.ownProperties),()=>w.error())})}function A(F,U){w.setParams({missingProperty:F}),b.forOf(F,W,()=>{b.assign(U,(0,Hb.propertyInData)(b,Q,F,J.ownProperties)),b.if((0,zb.not)(U),()=>{w.error(),b.break()})},zb.nil)}}};eY.default=CO});var b7=I((w7)=>{Object.defineProperty(w7,"__esModule",{value:!0});var Db=c(),_O={message({keyword:w,schemaCode:b}){let $=w==="maxItems"?"more":"fewer";return Db.str`must NOT have ${$} than ${b} items`},params:({schemaCode:w})=>Db._`{limit: ${w}}`},xO={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:_O,code(w){let{keyword:b,data:$,schemaCode:W}=w,Q=b==="maxItems"?Db.operators.GT:Db.operators.LT;w.fail$data(Db._`${$}.length ${Q} ${W}`)}};w7.default=xO});var y6=I((W7)=>{Object.defineProperty(W7,"__esModule",{value:!0});var $7=l$();$7.code='require("ajv/dist/runtime/equal").default';W7.default=$7});var X7=I((Q7)=>{Object.defineProperty(Q7,"__esModule",{value:!0});var Q9=s0(),Zw=c(),fO=o(),uO=y6(),cO={message:({params:{i:w,j:b}})=>Zw.str`must NOT have duplicate items (items ## ${b} and ${w} are identical)`,params:({params:{i:w,j:b}})=>Zw._`{i: ${w}, j: ${b}}`},mO={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:cO,code(w){let{gen:b,data:$,$data:W,schema:Q,parentSchema:X,schemaCode:G,it:J}=w;if(!W&&!Q)return;let Y=b.let("valid"),H=X.items?(0,Q9.getSchemaTypes)(X.items):[];w.block$data(Y,z,Zw._`${G} === false`),w.ok(Y);function z(){let U=b.let("i",Zw._`${$}.length`),M=b.let("j");w.setParams({i:U,j:M}),b.assign(Y,!0),b.if(Zw._`${U} > 1`,()=>(B()?A:F)(U,M))}function B(){return H.length>0&&!H.some((U)=>U==="object"||U==="array")}function A(U,M){let q=b.name("item"),P=(0,Q9.checkDataTypes)(H,q,J.opts.strictNumbers,Q9.DataType.Wrong),k=b.const("indices",Zw._`{}`);b.for(Zw._`;${U}--;`,()=>{if(b.let(q,Zw._`${$}[${U}]`),b.if(P,Zw._`continue`),H.length>1)b.if(Zw._`typeof ${q} == "string"`,Zw._`${q} += "_"`);b.if(Zw._`typeof ${k}[${q}] == "number"`,()=>{b.assign(M,Zw._`${k}[${q}]`),w.error(),b.assign(Y,!1).break()}).code(Zw._`${k}[${q}] = ${U}`)})}function F(U,M){let q=(0,fO.useFunc)(b,uO.default),P=b.name("outer");b.label(P).for(Zw._`;${U}--;`,()=>b.for(Zw._`${M} = ${U}; ${M}--;`,()=>b.if(Zw._`${q}(${$}[${U}], ${$}[${M}])`,()=>{w.error(),b.assign(Y,!1).break(P)})))}}};Q7.default=mO});var J7=I((G7)=>{Object.defineProperty(G7,"__esModule",{value:!0});var X9=c(),gO=o(),iO=y6(),nO={message:"must be equal to constant",params:({schemaCode:w})=>X9._`{allowedValue: ${w}}`},pO={keyword:"const",$data:!0,error:nO,code(w){let{gen:b,data:$,$data:W,schemaCode:Q,schema:X}=w;if(W||X&&typeof X=="object")w.fail$data(X9._`!${(0,gO.useFunc)(b,iO.default)}(${$}, ${Q})`);else w.fail(X9._`${X} !== ${$}`)}};G7.default=pO});var H7=I((Y7)=>{Object.defineProperty(Y7,"__esModule",{value:!0});var Bb=c(),oO=o(),tO=y6(),rO={message:"must be equal to one of the allowed values",params:({schemaCode:w})=>Bb._`{allowedValues: ${w}}`},sO={keyword:"enum",schemaType:"array",$data:!0,error:rO,code(w){let{gen:b,data:$,$data:W,schema:Q,schemaCode:X,it:G}=w;if(!W&&Q.length===0)throw Error("enum must have non-empty array");let J=Q.length>=G.opts.loopEnum,Y,H=()=>Y!==null&&Y!==void 0?Y:Y=(0,oO.useFunc)(b,tO.default),z;if(J||W)z=b.let("valid"),w.block$data(z,B);else{if(!Array.isArray(Q))throw Error("ajv implementation error");let F=b.const("vSchema",X);z=(0,Bb.or)(...Q.map((U,M)=>A(F,M)))}w.pass(z);function B(){b.assign(z,!1),b.forOf("v",X,(F)=>b.if(Bb._`${H()}(${$}, ${F})`,()=>b.assign(z,!0).break()))}function A(F,U){let M=Q[U];return typeof M==="object"&&M!==null?Bb._`${H()}(${$}, ${F}[${U}])`:Bb._`${$} === ${M}`}}};Y7.default=sO});var D7=I((z7)=>{Object.defineProperty(z7,"__esModule",{value:!0});var aO=cY(),wZ=lY(),bZ=dY(),$Z=tY(),WZ=sY(),QZ=aY(),XZ=b7(),GZ=X7(),JZ=J7(),YZ=H7(),HZ=[aO.default,wZ.default,bZ.default,$Z.default,WZ.default,QZ.default,XZ.default,GZ.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},JZ.default,YZ.default];z7.default=HZ});var J9=I((A7)=>{Object.defineProperty(A7,"__esModule",{value:!0});A7.validateAdditionalItems=void 0;var l1=c(),G9=o(),DZ={message:({params:{len:w}})=>l1.str`must NOT have more than ${w} items`,params:({params:{len:w}})=>l1._`{limit: ${w}}`},BZ={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:DZ,code(w){let{parentSchema:b,it:$}=w,{items:W}=b;if(!Array.isArray(W)){(0,G9.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}B7(w,W)}};function B7(w,b){let{gen:$,schema:W,data:Q,keyword:X,it:G}=w;G.items=!0;let J=$.const("len",l1._`${Q}.length`);if(W===!1)w.setParams({len:b.length}),w.pass(l1._`${J} <= ${b.length}`);else if(typeof W=="object"&&!(0,G9.alwaysValidSchema)(G,W)){let H=$.var("valid",l1._`${J} <= ${b.length}`);$.if((0,l1.not)(H),()=>Y(H)),w.ok(H)}function Y(H){$.forRange("i",b.length,J,(z)=>{if(w.subschema({keyword:X,dataProp:z,dataPropType:G9.Type.Num},H),!G.allErrors)$.if((0,l1.not)(H),()=>$.break())})}}A7.validateAdditionalItems=B7;A7.default=BZ});var Y9=I((K7)=>{Object.defineProperty(K7,"__esModule",{value:!0});K7.validateTuple=void 0;var L7=c(),f6=o(),FZ=fw(),LZ={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(w){let{schema:b,it:$}=w;if(Array.isArray(b))return U7(w,"additionalItems",b);if($.items=!0,(0,f6.alwaysValidSchema)($,b))return;w.ok((0,FZ.validateArray)(w))}};function U7(w,b,$=w.schema){let{gen:W,parentSchema:Q,data:X,keyword:G,it:J}=w;if(z(Q),J.opts.unevaluated&&$.length&&J.items!==!0)J.items=f6.mergeEvaluated.items(W,$.length,J.items);let Y=W.name("valid"),H=W.const("len",L7._`${X}.length`);$.forEach((B,A)=>{if((0,f6.alwaysValidSchema)(J,B))return;W.if(L7._`${H} > ${A}`,()=>w.subschema({keyword:G,schemaProp:A,dataProp:A},Y)),w.ok(Y)});function z(B){let{opts:A,errSchemaPath:F}=J,U=$.length,M=U===B.minItems&&(U===B.maxItems||B[b]===!1);if(A.strictTuples&&!M){let q=`"${G}" is ${U}-tuple, but minItems or maxItems/${b} are not specified or different at path "${F}"`;(0,f6.checkStrictMode)(J,q,A.strictTuples)}}}K7.validateTuple=U7;K7.default=LZ});var V7=I((Z7)=>{Object.defineProperty(Z7,"__esModule",{value:!0});var KZ=Y9(),OZ={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(w)=>(0,KZ.validateTuple)(w,"items")};Z7.default=OZ});var q7=I((j7)=>{Object.defineProperty(j7,"__esModule",{value:!0});var M7=c(),VZ=o(),MZ=fw(),jZ=J9(),qZ={message:({params:{len:w}})=>M7.str`must NOT have more than ${w} items`,params:({params:{len:w}})=>M7._`{limit: ${w}}`},PZ={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:qZ,code(w){let{schema:b,parentSchema:$,it:W}=w,{prefixItems:Q}=$;if(W.items=!0,(0,VZ.alwaysValidSchema)(W,b))return;if(Q)(0,jZ.validateAdditionalItems)(w,Q);else w.ok((0,MZ.validateArray)(w))}};j7.default=PZ});var I7=I((P7)=>{Object.defineProperty(P7,"__esModule",{value:!0});var uw=c(),u6=o(),NZ={message:({params:{min:w,max:b}})=>b===void 0?uw.str`must contain at least ${w} valid item(s)`:uw.str`must contain at least ${w} and no more than ${b} valid item(s)`,params:({params:{min:w,max:b}})=>b===void 0?uw._`{minContains: ${w}}`:uw._`{minContains: ${w}, maxContains: ${b}}`},EZ={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:NZ,code(w){let{gen:b,schema:$,parentSchema:W,data:Q,it:X}=w,G,J,{minContains:Y,maxContains:H}=W;if(X.opts.next)G=Y===void 0?1:Y,J=H;else G=1;let z=b.const("len",uw._`${Q}.length`);if(w.setParams({min:G,max:J}),J===void 0&&G===0){(0,u6.checkStrictMode)(X,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(J!==void 0&&G>J){(0,u6.checkStrictMode)(X,'"minContains" > "maxContains" is always invalid'),w.fail();return}if((0,u6.alwaysValidSchema)(X,$)){let M=uw._`${z} >= ${G}`;if(J!==void 0)M=uw._`${M} && ${z} <= ${J}`;w.pass(M);return}X.items=!0;let B=b.name("valid");if(J===void 0&&G===1)F(B,()=>b.if(B,()=>b.break()));else if(G===0){if(b.let(B,!0),J!==void 0)b.if(uw._`${Q}.length > 0`,A)}else b.let(B,!1),A();w.result(B,()=>w.reset());function A(){let M=b.name("_valid"),q=b.let("count",0);F(M,()=>b.if(M,()=>U(q)))}function F(M,q){b.forRange("i",0,z,(P)=>{w.subschema({keyword:"contains",dataProp:P,dataPropType:u6.Type.Num,compositeRule:!0},M),q()})}function U(M){if(b.code(uw._`${M}++`),J===void 0)b.if(uw._`${M} >= ${G}`,()=>b.assign(B,!0).break());else if(b.if(uw._`${M} > ${J}`,()=>b.assign(B,!1).break()),G===1)b.assign(B,!0);else b.if(uw._`${M} >= ${G}`,()=>b.assign(B,!0))}}};P7.default=EZ});var v7=I((T7)=>{Object.defineProperty(T7,"__esModule",{value:!0});T7.validateSchemaDeps=T7.validatePropertyDeps=T7.error=void 0;var H9=c(),RZ=o(),Ab=fw();T7.error={message:({params:{property:w,depsCount:b,deps:$}})=>{let W=b===1?"property":"properties";return H9.str`must have ${W} ${$} when property ${w} is present`},params:({params:{property:w,depsCount:b,deps:$,missingProperty:W}})=>H9._`{property: ${w},
7
7
  missingProperty: ${W},
8
8
  depsCount: ${b},
9
- deps: ${$}}`};var RZ={keyword:"dependencies",type:"object",schemaType:"object",error:E7.error,code(w){let[b,$]=SZ(w);I7(w,b),N7(w,$)}};function SZ({schema:w}){let b={},$={};for(let W in w){if(W==="__proto__")continue;let Q=Array.isArray(w[W])?b:$;Q[W]=w[W]}return[b,$]}function I7(w,b=w.schema){let{gen:$,data:W,it:Q}=w;if(Object.keys(b).length===0)return;let X=$.let("missing");for(let G in b){let J=b[G];if(J.length===0)continue;let Y=(0,Bb.propertyInData)($,W,G,Q.opts.ownProperties);if(w.setParams({property:G,depsCount:J.length,deps:J.join(", ")}),Q.allErrors)$.if(Y,()=>{for(let H of J)(0,Bb.checkReportMissingProp)(w,H)});else $.if(H9._`${Y} && (${(0,Bb.checkMissingProp)(w,J,X)})`),(0,Bb.reportMissingProp)(w,X),$.else()}}E7.validatePropertyDeps=I7;function N7(w,b=w.schema){let{gen:$,data:W,keyword:Q,it:X}=w,G=$.name("valid");for(let J in b){if((0,TZ.alwaysValidSchema)(X,b[J]))continue;$.if((0,Bb.propertyInData)($,W,J,X.opts.ownProperties),()=>{let Y=w.subschema({keyword:Q,schemaProp:J},G);w.mergeValidEvaluated(Y,G)},()=>$.var(G,!0)),w.ok(G)}}E7.validateSchemaDeps=N7;E7.default=RZ});var k7=I((C7)=>{Object.defineProperty(C7,"__esModule",{value:!0});var v7=f(),kZ=o(),_Z={message:"property name must be valid",params:({params:w})=>v7._`{propertyName: ${w.propertyName}}`},xZ={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:_Z,code(w){let{gen:b,schema:$,data:W,it:Q}=w;if((0,kZ.alwaysValidSchema)(Q,$))return;let X=b.name("valid");b.forIn("key",W,(G)=>{w.setParams({propertyName:G}),w.subschema({keyword:"propertyNames",data:G,dataTypes:["string"],propertyName:G,compositeRule:!0},X),b.if((0,v7.not)(X),()=>{if(w.error(!0),!Q.allErrors)b.break()})}),w.ok(X)}};C7.default=xZ});var z9=I((_7)=>{Object.defineProperty(_7,"__esModule",{value:!0});var f6=hw(),nw=f(),yZ=Y1(),c6=o(),uZ={message:"must NOT have additional properties",params:({params:w})=>nw._`{additionalProperty: ${w.additionalProperty}}`},fZ={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:uZ,code(w){let{gen:b,schema:$,parentSchema:W,data:Q,errsCount:X,it:G}=w;if(!X)throw Error("ajv implementation error");let{allErrors:J,opts:Y}=G;if(G.props=!0,Y.removeAdditional!=="all"&&(0,c6.alwaysValidSchema)(G,$))return;let H=(0,f6.allSchemaProperties)(W.properties),z=(0,f6.allSchemaProperties)(W.patternProperties);B(),w.ok(nw._`${X} === ${yZ.default.errors}`);function B(){b.forIn("key",Q,(q)=>{if(!H.length&&!z.length)U(q);else b.if(A(q),()=>U(q))})}function A(q){let P;if(H.length>8){let k=(0,c6.schemaRefOrVal)(G,W.properties,"properties");P=(0,f6.isOwnProperty)(b,k,q)}else if(H.length)P=(0,nw.or)(...H.map((k)=>nw._`${q} === ${k}`));else P=nw.nil;if(z.length)P=(0,nw.or)(P,...z.map((k)=>nw._`${(0,f6.usePattern)(w,k)}.test(${q})`));return(0,nw.not)(P)}function F(q){b.code(nw._`delete ${Q}[${q}]`)}function U(q){if(Y.removeAdditional==="all"||Y.removeAdditional&&$===!1){F(q);return}if($===!1){if(w.setParams({additionalProperty:q}),w.error(),!J)b.break();return}if(typeof $=="object"&&!(0,c6.alwaysValidSchema)(G,$)){let P=b.name("valid");if(Y.removeAdditional==="failing")V(q,P,!1),b.if((0,nw.not)(P),()=>{w.reset(),F(q)});else if(V(q,P),!J)b.if((0,nw.not)(P),()=>b.break())}}function V(q,P,k){let S={keyword:"additionalProperties",dataProp:q,dataPropType:c6.Type.Str};if(k===!1)Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1});w.subschema(S,P)}}};_7.default=fZ});var u7=I((y7)=>{Object.defineProperty(y7,"__esModule",{value:!0});var mZ=wb(),x7=hw(),D9=o(),h7=z9(),lZ={keyword:"properties",type:"object",schemaType:"object",code(w){let{gen:b,schema:$,parentSchema:W,data:Q,it:X}=w;if(X.opts.removeAdditional==="all"&&W.additionalProperties===void 0)h7.default.code(new mZ.KeywordCxt(X,h7.default,"additionalProperties"));let G=(0,x7.allSchemaProperties)($);for(let B of G)X.definedProperties.add(B);if(X.opts.unevaluated&&G.length&&X.props!==!0)X.props=D9.mergeEvaluated.props(b,(0,D9.toHash)(G),X.props);let J=G.filter((B)=>!(0,D9.alwaysValidSchema)(X,$[B]));if(J.length===0)return;let Y=b.name("valid");for(let B of J){if(H(B))z(B);else{if(b.if((0,x7.propertyInData)(b,Q,B,X.opts.ownProperties)),z(B),!X.allErrors)b.else().var(Y,!0);b.endIf()}w.it.definedProperties.add(B),w.ok(Y)}function H(B){return X.opts.useDefaults&&!X.compositeRule&&$[B].default!==void 0}function z(B){w.subschema({keyword:"properties",schemaProp:B,dataProp:B},Y)}}};y7.default=lZ});var g7=I((l7)=>{Object.defineProperty(l7,"__esModule",{value:!0});var f7=hw(),m6=f(),c7=o(),m7=o(),iZ={keyword:"patternProperties",type:"object",schemaType:"object",code(w){let{gen:b,schema:$,data:W,parentSchema:Q,it:X}=w,{opts:G}=X,J=(0,f7.allSchemaProperties)($),Y=J.filter((V)=>(0,c7.alwaysValidSchema)(X,$[V]));if(J.length===0||Y.length===J.length&&(!X.opts.unevaluated||X.props===!0))return;let H=G.strictSchema&&!G.allowMatchingProperties&&Q.properties,z=b.name("valid");if(X.props!==!0&&!(X.props instanceof m6.Name))X.props=(0,m7.evaluatedPropsToName)(b,X.props);let{props:B}=X;A();function A(){for(let V of J){if(H)F(V);if(X.allErrors)U(V);else b.var(z,!0),U(V),b.if(z)}}function F(V){for(let q in H)if(new RegExp(V).test(q))(0,c7.checkStrictMode)(X,`property ${q} matches pattern ${V} (use allowMatchingProperties)`)}function U(V){b.forIn("key",W,(q)=>{b.if(m6._`${(0,f7.usePattern)(w,V)}.test(${q})`,()=>{let P=Y.includes(V);if(!P)w.subschema({keyword:"patternProperties",schemaProp:V,dataProp:q,dataPropType:m7.Type.Str},z);if(X.opts.unevaluated&&B!==!0)b.assign(m6._`${B}[${q}]`,!0);else if(!P&&!X.allErrors)b.if((0,m6.not)(z),()=>b.break())})})}}};l7.default=iZ});var n7=I((i7)=>{Object.defineProperty(i7,"__esModule",{value:!0});var pZ=o(),dZ={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(w){let{gen:b,schema:$,it:W}=w;if((0,pZ.alwaysValidSchema)(W,$)){w.fail();return}let Q=b.name("valid");w.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},Q),w.failResult(Q,()=>w.reset(),()=>w.error())},error:{message:"must NOT be valid"}};i7.default=dZ});var d7=I((p7)=>{Object.defineProperty(p7,"__esModule",{value:!0});var tZ=hw(),rZ={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:tZ.validateUnion,error:{message:"must match a schema in anyOf"}};p7.default=rZ});var t7=I((o7)=>{Object.defineProperty(o7,"__esModule",{value:!0});var l6=f(),eZ=o(),aZ={message:"must match exactly one schema in oneOf",params:({params:w})=>l6._`{passingSchemas: ${w.passing}}`},wM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:aZ,code(w){let{gen:b,schema:$,parentSchema:W,it:Q}=w;if(!Array.isArray($))throw Error("ajv implementation error");if(Q.opts.discriminator&&W.discriminator)return;let X=$,G=b.let("valid",!1),J=b.let("passing",null),Y=b.name("_valid");w.setParams({passing:J}),b.block(H),w.result(G,()=>w.reset(),()=>w.error(!0));function H(){X.forEach((z,B)=>{let A;if((0,eZ.alwaysValidSchema)(Q,z))b.var(Y,!0);else A=w.subschema({keyword:"oneOf",schemaProp:B,compositeRule:!0},Y);if(B>0)b.if(l6._`${Y} && ${G}`).assign(G,!1).assign(J,l6._`[${J}, ${B}]`).else();b.if(Y,()=>{if(b.assign(G,!0),b.assign(J,B),A)w.mergeEvaluated(A,l6.Name)})})}}};o7.default=wM});var s7=I((r7)=>{Object.defineProperty(r7,"__esModule",{value:!0});var $M=o(),WM={keyword:"allOf",schemaType:"array",code(w){let{gen:b,schema:$,it:W}=w;if(!Array.isArray($))throw Error("ajv implementation error");let Q=b.name("valid");$.forEach((X,G)=>{if((0,$M.alwaysValidSchema)(W,X))return;let J=w.subschema({keyword:"allOf",schemaProp:G},Q);w.ok(Q),w.mergeEvaluated(J)})}};r7.default=WM});var bH=I((wH)=>{Object.defineProperty(wH,"__esModule",{value:!0});var g6=f(),a7=o(),XM={message:({params:w})=>g6.str`must match "${w.ifClause}" schema`,params:({params:w})=>g6._`{failingKeyword: ${w.ifClause}}`},GM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:XM,code(w){let{gen:b,parentSchema:$,it:W}=w;if($.then===void 0&&$.else===void 0)(0,a7.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let Q=e7(W,"then"),X=e7(W,"else");if(!Q&&!X)return;let G=b.let("valid",!0),J=b.name("_valid");if(Y(),w.reset(),Q&&X){let z=b.let("ifClause");w.setParams({ifClause:z}),b.if(J,H("then",z),H("else",z))}else if(Q)b.if(J,H("then"));else b.if((0,g6.not)(J),H("else"));w.pass(G,()=>w.error(!0));function Y(){let z=w.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},J);w.mergeEvaluated(z)}function H(z,B){return()=>{let A=w.subschema({keyword:z},J);if(b.assign(G,J),w.mergeValidEvaluated(A,G),B)b.assign(B,g6._`${z}`);else w.setParams({ifClause:z})}}}};function e7(w,b){let $=w.schema[b];return $!==void 0&&!(0,a7.alwaysValidSchema)(w,$)}wH.default=GM});var WH=I(($H)=>{Object.defineProperty($H,"__esModule",{value:!0});var YM=o(),HM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:w,parentSchema:b,it:$}){if(b.if===void 0)(0,YM.checkStrictMode)($,`"${w}" without "if" is ignored`)}};$H.default=HM});var XH=I((QH)=>{Object.defineProperty(QH,"__esModule",{value:!0});var DM=J9(),BM=Z7(),AM=Y9(),FM=j7(),LM=P7(),UM=S7(),KM=k7(),OM=z9(),ZM=u7(),MM=g7(),VM=n7(),jM=d7(),qM=t7(),PM=s7(),IM=bH(),NM=WH();function EM(w=!1){let b=[VM.default,jM.default,qM.default,PM.default,IM.default,NM.default,KM.default,OM.default,UM.default,ZM.default,MM.default];if(w)b.push(BM.default,FM.default);else b.push(DM.default,AM.default);return b.push(LM.default),b}QH.default=EM});var JH=I((GH)=>{Object.defineProperty(GH,"__esModule",{value:!0});var Hw=f(),RM={message:({schemaCode:w})=>Hw.str`must match format "${w}"`,params:({schemaCode:w})=>Hw._`{format: ${w}}`},SM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:RM,code(w,b){let{gen:$,data:W,$data:Q,schema:X,schemaCode:G,it:J}=w,{opts:Y,errSchemaPath:H,schemaEnv:z,self:B}=J;if(!Y.validateFormats)return;if(Q)A();else F();function A(){let U=$.scopeValue("formats",{ref:B.formats,code:Y.code.formats}),V=$.const("fDef",Hw._`${U}[${G}]`),q=$.let("fType"),P=$.let("format");$.if(Hw._`typeof ${V} == "object" && !(${V} instanceof RegExp)`,()=>$.assign(q,Hw._`${V}.type || "string"`).assign(P,Hw._`${V}.validate`),()=>$.assign(q,Hw._`"string"`).assign(P,V)),w.fail$data((0,Hw.or)(k(),S()));function k(){if(Y.strictSchema===!1)return Hw.nil;return Hw._`${G} && !${P}`}function S(){let m=z.$async?Hw._`(${V}.async ? await ${P}(${W}) : ${P}(${W}))`:Hw._`${P}(${W})`,_=Hw._`(typeof ${P} == "function" ? ${m} : ${P}.test(${W}))`;return Hw._`${P} && ${P} !== true && ${q} === ${b} && !${_}`}}function F(){let U=B.formats[X];if(!U){k();return}if(U===!0)return;let[V,q,P]=S(U);if(V===b)w.pass(m());function k(){if(Y.strictSchema===!1){B.logger.warn(_());return}throw Error(_());function _(){return`unknown format "${X}" ignored in schema at path "${H}"`}}function S(_){let tw=_ instanceof RegExp?(0,Hw.regexpCode)(_):Y.code.formats?Hw._`${Y.code.formats}${(0,Hw.getProperty)(X)}`:void 0,$1=$.scopeValue("formats",{key:X,ref:_,code:tw});if(typeof _=="object"&&!(_ instanceof RegExp))return[_.type||"string",_.validate,Hw._`${$1}.validate`];return["string",_,$1]}function m(){if(typeof U=="object"&&!(U instanceof RegExp)&&U.async){if(!z.$async)throw Error("async format in sync schema");return Hw._`await ${P}(${W})`}return typeof q=="function"?Hw._`${P}(${W})`:Hw._`${P}.test(${W})`}}}};GH.default=SM});var HH=I((YH)=>{Object.defineProperty(YH,"__esModule",{value:!0});var CM=JH(),kM=[CM.default];YH.default=kM});var BH=I((zH)=>{Object.defineProperty(zH,"__esModule",{value:!0});zH.contentVocabulary=zH.metadataVocabulary=void 0;zH.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];zH.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var LH=I((FH)=>{Object.defineProperty(FH,"__esModule",{value:!0});var hM=yY(),yM=z7(),uM=XH(),fM=HH(),AH=BH(),cM=[hM.default,yM.default,(0,uM.default)(),fM.default,AH.metadataVocabulary,AH.contentVocabulary];FH.default=cM});var ZH=I((KH)=>{Object.defineProperty(KH,"__esModule",{value:!0});KH.DiscrError=void 0;var UH;(function(w){w.Tag="tag",w.Mapping="mapping"})(UH||(KH.DiscrError=UH={}))});var jH=I((VH)=>{Object.defineProperty(VH,"__esModule",{value:!0});var G0=f(),B9=ZH(),MH=P6(),lM=bb(),gM=o(),iM={message:({params:{discrError:w,tagName:b}})=>w===B9.DiscrError.Tag?`tag "${b}" must be string`:`value of tag "${b}" must be in oneOf`,params:({params:{discrError:w,tag:b,tagName:$}})=>G0._`{error: ${w}, tag: ${$}, tagValue: ${b}}`},nM={keyword:"discriminator",type:"object",schemaType:"object",error:iM,code(w){let{gen:b,data:$,schema:W,parentSchema:Q,it:X}=w,{oneOf:G}=Q;if(!X.opts.discriminator)throw Error("discriminator: requires discriminator option");let J=W.propertyName;if(typeof J!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!G)throw Error("discriminator: requires oneOf keyword");let Y=b.let("valid",!1),H=b.const("tag",G0._`${$}${(0,G0.getProperty)(J)}`);b.if(G0._`typeof ${H} == "string"`,()=>z(),()=>w.error(!1,{discrError:B9.DiscrError.Tag,tag:H,tagName:J})),w.ok(Y);function z(){let F=A();b.if(!1);for(let U in F)b.elseIf(G0._`${H} === ${U}`),b.assign(Y,B(F[U]));b.else(),w.error(!1,{discrError:B9.DiscrError.Mapping,tag:H,tagName:J}),b.endIf()}function B(F){let U=b.name("valid"),V=w.subschema({keyword:"oneOf",schemaProp:F},U);return w.mergeEvaluated(V,G0.Name),U}function A(){var F;let U={},V=P(Q),q=!0;for(let m=0;m<G.length;m++){let _=G[m];if((_===null||_===void 0?void 0:_.$ref)&&!(0,gM.schemaHasRulesButRef)(_,X.self.RULES)){let $1=_.$ref;if(_=MH.resolveRef.call(X.self,X.schemaEnv.root,X.baseId,$1),_ instanceof MH.SchemaEnv)_=_.schema;if(_===void 0)throw new lM.default(X.opts.uriResolver,X.baseId,$1)}let tw=(F=_===null||_===void 0?void 0:_.properties)===null||F===void 0?void 0:F[J];if(typeof tw!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${J}"`);q=q&&(V||P(_)),k(tw,m)}if(!q)throw Error(`discriminator: "${J}" must be required`);return U;function P({required:m}){return Array.isArray(m)&&m.includes(J)}function k(m,_){if(m.const)S(m.const,_);else if(m.enum)for(let tw of m.enum)S(tw,_);else throw Error(`discriminator: "properties/${J}" must have "const" or "enum"`)}function S(m,_){if(typeof m!="string"||m in U)throw Error(`discriminator: "${J}" values must be unique strings`);U[m]=_}}}};VH.default=nM});var qH=I((wS,dM)=>{dM.exports={$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:!0,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:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},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:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},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:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},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:!0}});var F9=I((Tw,A9)=>{Object.defineProperty(Tw,"__esModule",{value:!0});Tw.MissingRefError=Tw.ValidationError=Tw.CodeGen=Tw.Name=Tw.nil=Tw.stringify=Tw.str=Tw._=Tw.KeywordCxt=Tw.Ajv=void 0;var oM=EY(),tM=LH(),rM=jH(),PH=qH(),sM=["/properties"],i6="http://json-schema.org/draft-07/schema";class Ab extends oM.default{_addVocabularies(){if(super._addVocabularies(),tM.default.forEach((w)=>this.addVocabulary(w)),this.opts.discriminator)this.addKeyword(rM.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let w=this.opts.$data?this.$dataMetaSchema(PH,sM):PH;this.addMetaSchema(w,i6,!1),this.refs["http://json-schema.org/schema"]=i6}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i6)?i6:void 0)}}Tw.Ajv=Ab;A9.exports=Tw=Ab;A9.exports.Ajv=Ab;Object.defineProperty(Tw,"__esModule",{value:!0});Tw.default=Ab;var eM=wb();Object.defineProperty(Tw,"KeywordCxt",{enumerable:!0,get:function(){return eM.KeywordCxt}});var J0=f();Object.defineProperty(Tw,"_",{enumerable:!0,get:function(){return J0._}});Object.defineProperty(Tw,"str",{enumerable:!0,get:function(){return J0.str}});Object.defineProperty(Tw,"stringify",{enumerable:!0,get:function(){return J0.stringify}});Object.defineProperty(Tw,"nil",{enumerable:!0,get:function(){return J0.nil}});Object.defineProperty(Tw,"Name",{enumerable:!0,get:function(){return J0.Name}});Object.defineProperty(Tw,"CodeGen",{enumerable:!0,get:function(){return J0.CodeGen}});var aM=j6();Object.defineProperty(Tw,"ValidationError",{enumerable:!0,get:function(){return aM.default}});var wV=bb();Object.defineProperty(Tw,"MissingRefError",{enumerable:!0,get:function(){return wV.default}})});var _H=I((CH)=>{Object.defineProperty(CH,"__esModule",{value:!0});CH.formatNames=CH.fastFormats=CH.fullFormats=void 0;function aw(w,b){return{validate:w,compare:b}}CH.fullFormats={date:aw(TH,O9),time:aw(U9(!0),Z9),"date-time":aw(IH(!0),SH),"iso-time":aw(U9(),RH),"iso-date-time":aw(IH(),vH),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:YV,"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:LV,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:HV,int32:{type:"number",validate:BV},int64:{type:"number",validate:AV},float:{type:"number",validate:EH},double:{type:"number",validate:EH},password:!0,binary:!0};CH.fastFormats={...CH.fullFormats,date:aw(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,O9),time:aw(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Z9),"date-time":aw(/^\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,SH),"iso-time":aw(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,RH),"iso-date-time":aw(/^\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,vH),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};CH.formatNames=Object.keys(CH.fullFormats);function WV(w){return w%4===0&&(w%100!==0||w%400===0)}var QV=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,XV=[0,31,28,31,30,31,30,31,31,30,31,30,31];function TH(w){let b=QV.exec(w);if(!b)return!1;let $=+b[1],W=+b[2],Q=+b[3];return W>=1&&W<=12&&Q>=1&&Q<=(W===2&&WV($)?29:XV[W])}function O9(w,b){if(!(w&&b))return;if(w>b)return 1;if(w<b)return-1;return 0}var L9=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function U9(w){return function($){let W=L9.exec($);if(!W)return!1;let Q=+W[1],X=+W[2],G=+W[3],J=W[4],Y=W[5]==="-"?-1:1,H=+(W[6]||0),z=+(W[7]||0);if(H>23||z>59||w&&!J)return!1;if(Q<=23&&X<=59&&G<60)return!0;let B=X-z*Y,A=Q-H*Y-(B<0?1:0);return(A===23||A===-1)&&(B===59||B===-1)&&G<61}}function Z9(w,b){if(!(w&&b))return;let $=new Date("2020-01-01T"+w).valueOf(),W=new Date("2020-01-01T"+b).valueOf();if(!($&&W))return;return $-W}function RH(w,b){if(!(w&&b))return;let $=L9.exec(w),W=L9.exec(b);if(!($&&W))return;if(w=$[1]+$[2]+$[3],b=W[1]+W[2]+W[3],w>b)return 1;if(w<b)return-1;return 0}var K9=/t|\s/i;function IH(w){let b=U9(w);return function(W){let Q=W.split(K9);return Q.length===2&&TH(Q[0])&&b(Q[1])}}function SH(w,b){if(!(w&&b))return;let $=new Date(w).valueOf(),W=new Date(b).valueOf();if(!($&&W))return;return $-W}function vH(w,b){if(!(w&&b))return;let[$,W]=w.split(K9),[Q,X]=b.split(K9),G=O9($,Q);if(G===void 0)return;return G||Z9(W,X)}var GV=/\/|:/,JV=/^(?:[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;function YV(w){return GV.test(w)&&JV.test(w)}var NH=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function HV(w){return NH.lastIndex=0,NH.test(w)}var zV=-2147483648,DV=2147483647;function BV(w){return Number.isInteger(w)&&w<=DV&&w>=zV}function AV(w){return Number.isInteger(w)}function EH(){return!0}var FV=/[^\\]\\Z/;function LV(w){if(FV.test(w))return!1;try{return new RegExp(w),!0}catch(b){return!1}}});var hH=I((xH)=>{Object.defineProperty(xH,"__esModule",{value:!0});xH.formatLimitDefinition=void 0;var KV=F9(),pw=f(),v1=pw.operators,n6={formatMaximum:{okStr:"<=",ok:v1.LTE,fail:v1.GT},formatMinimum:{okStr:">=",ok:v1.GTE,fail:v1.LT},formatExclusiveMaximum:{okStr:"<",ok:v1.LT,fail:v1.GTE},formatExclusiveMinimum:{okStr:">",ok:v1.GT,fail:v1.LTE}},OV={message:({keyword:w,schemaCode:b})=>pw.str`should be ${n6[w].okStr} ${b}`,params:({keyword:w,schemaCode:b})=>pw._`{comparison: ${n6[w].okStr}, limit: ${b}}`};xH.formatLimitDefinition={keyword:Object.keys(n6),type:"string",schemaType:"string",$data:!0,error:OV,code(w){let{gen:b,data:$,schemaCode:W,keyword:Q,it:X}=w,{opts:G,self:J}=X;if(!G.validateFormats)return;let Y=new KV.KeywordCxt(X,J.RULES.all.format.definition,"format");if(Y.$data)H();else z();function H(){let A=b.scopeValue("formats",{ref:J.formats,code:G.code.formats}),F=b.const("fmt",pw._`${A}[${Y.schemaCode}]`);w.fail$data((0,pw.or)(pw._`typeof ${F} != "object"`,pw._`${F} instanceof RegExp`,pw._`typeof ${F}.compare != "function"`,B(F)))}function z(){let A=Y.schema,F=J.formats[A];if(!F||F===!0)return;if(typeof F!="object"||F instanceof RegExp||typeof F.compare!="function")throw Error(`"${Q}": format "${A}" does not define "compare" function`);let U=b.scopeValue("formats",{key:A,ref:F,code:G.code.formats?pw._`${G.code.formats}${(0,pw.getProperty)(A)}`:void 0});w.fail$data(B(U))}function B(A){return pw._`${A}.compare(${$}, ${W}) ${n6[Q].fail} 0`}},dependencies:["format"]};var ZV=(w)=>{return w.addKeyword(xH.formatLimitDefinition),w};xH.default=ZV});var cH=I((Fb,fH)=>{Object.defineProperty(Fb,"__esModule",{value:!0});var Y0=_H(),VV=hH(),j9=f(),yH=new j9.Name("fullFormats"),jV=new j9.Name("fastFormats"),q9=(w,b={keywords:!0})=>{if(Array.isArray(b))return uH(w,b,Y0.fullFormats,yH),w;let[$,W]=b.mode==="fast"?[Y0.fastFormats,jV]:[Y0.fullFormats,yH],Q=b.formats||Y0.formatNames;if(uH(w,Q,$,W),b.keywords)(0,VV.default)(w);return w};q9.get=(w,b="full")=>{let W=(b==="fast"?Y0.fastFormats:Y0.fullFormats)[w];if(!W)throw Error(`Unknown format "${w}"`);return W};function uH(w,b,$,W){var Q,X;(Q=(X=w.opts.code).formats)!==null&&Q!==void 0||(X.formats=j9._`require("ajv-formats/dist/formats").${W}`);for(let G of b)w.addFormat(G,$[G])}fH.exports=Fb=q9;Object.defineProperty(Fb,"__esModule",{value:!0});Fb.default=q9});import{AsyncLocalStorage as r3}from"node:async_hooks";class rw extends Error{statusCode;rawDetails;code;context;constructor(w,b,$,W,Q){super(w);this.statusCode=b;this.rawDetails=$;this.code=W;this.context=Q;this.name="McpApiError"}}function d3(w){if(w instanceof rw)return{message:w.message,statusCode:w.statusCode,code:w.code,rawDetails:w.rawDetails,context:w.context};if(w instanceof Error)return{message:w.message};return{message:String(w)}}function o3(w){let b=w.match(/api key is missing required scopes?:\s*(.+)$/i);if(!b?.[1])return[];return[...new Set(b[1].match(/[a-z_]+:[a-z_]+/gi)??[])]}function t3(w){let b=d3(w),$=b.message.trim()||"Unknown error",W=$.toLowerCase(),Q=b.rawDetails?.trim()||$;if(b.context?.title||b.context?.description||b.context?.howToFix||b.context?.docsUrl)return{title:b.context.title??(b.statusCode===409?"Request conflict":"API request failed"),description:b.context.description??$,howToFix:b.context.howToFix??"Review the details below, adjust the tool input, and retry.",docsUrl:b.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.code==="MCP_AUTH_REQUIRED"||W.includes("sequenzy_api_key environment variable is required"))return{title:"Missing MCP API key",description:"The MCP server started without a Sequenzy API key, so it cannot authenticate any tool or resource request.",howToFix:"Add `SEQUENZY_API_KEY` to the MCP server environment, or run `npx @sequenzy/setup` to configure the integration automatically.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.statusCode===401||b.code==="UNAUTHORIZED")return{title:"Authentication failed",description:"The MCP server reached Sequenzy, but the current API key was rejected.",howToFix:"Replace `SEQUENZY_API_KEY` with a valid personal API key, then restart the MCP client so it reconnects with fresh credentials.",docsUrl:"https://docs.sequenzy.com/authentication",details:Q};let X=o3($);if(X.length>0){let G=X.map((Y)=>`\`${Y}\``).join(", "),J=X.every((Y)=>Y.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${X.length===1?"scope":"scopes"}: ${G}.`,howToFix:`For a local API-key connection, call \`get_account\` to inspect \`apiKeyPermissions\` and open \`apiKeyPermissions.manageUrl\` (or \`companies[].settingsUrl\` → API Keys). If \`get_account\` also requires \`account:read\`, open ${"https://sequenzy.com/dashboard"} directly and use the MCP setup or Settings → API Keys. Create a replacement key with ${J} including ${G}, replace \`SEQUENZY_API_KEY\`, and restart the client. For hosted OAuth MCP, disconnect and reauthorize the Sequenzy connection with a preset or Custom permissions including ${G}. Existing key permissions cannot be edited in place.`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}if(b.statusCode===403||W.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to access the requested company or action.",howToFix:"Use an API key that belongs to the right account, or select a company the key can access before retrying the tool call.",docsUrl:"https://docs.sequenzy.com/authentication",details:Q};if(W.includes("no company available")||W.includes("company not found"))return{title:"Company selection required",description:"The MCP server could not resolve a company for this request.",howToFix:"Call `get_account` to inspect available companies, then call `select_company`, or pass `companyId` explicitly in the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.statusCode===404||W.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the requested campaign, template, sequence, company, or subscriber.",howToFix:"List or fetch the resource collection first, then retry the tool with a confirmed ID or email value.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("already exists"))return{title:"Resource already exists",description:"Sequenzy rejected this MCP request because it would create a duplicate resource.",howToFix:"List the existing resources first, reuse the matching resource when appropriate, or retry with a unique name or domain.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.statusCode===409)return{title:"Request conflict",description:"Sequenzy rejected this request because the resource changed or an operation is already in progress.",howToFix:"Refresh the resource state, choose the lifecycle action allowed by its current status, and retry at most once.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.statusCode===429||W.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this MCP request because too many requests were sent too quickly.",howToFix:"Wait briefly before retrying. If the client is looping, reduce retries or add backoff before the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.code==="NETWORK_ERROR"||W.includes("fetch failed"))return{title:"Network or configuration error",description:"The MCP server could not reach the Sequenzy API from this environment.",howToFix:"Check connectivity and verify `SEQUENZY_API_URL` if you override it in the MCP environment.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("unknown tool")||W.includes("unknown resource"))return{title:"Unsupported MCP request",description:"The client asked for a tool or resource name that this Sequenzy MCP server does not expose.",howToFix:"Refresh the client's tool list and call only the names returned by `list_tools` or `list_resources`.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("is required")||W.includes("invalid"))return{title:"Invalid MCP input",description:"The tool call was missing a required field or included an invalid value.",howToFix:"Review the tool schema, supply the missing argument, and retry the request with corrected input.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.statusCode&&b.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If it still fails, keep the details below and consult the docs before escalating.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the details below, adjust the tool input or credentials, and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}function U1(w){let b=t3(w);return[`Sequenzy MCP error: ${b.title}`,`Description: ${b.description}`,`How to fix: ${b.howToFix}`,`Docs: ${b.docsUrl}`,`Details: ${b.details}`].join(`
10
- `)}var s3="https://api.sequenzy.com",e3=new Set(["/api/v1/media/upload-bytes","/v1/media/upload-bytes"]),M0=new r3,AW=!1;function FW(){AW=!0}function Pb(){return AW}var LW=null;function K1(){let w=M0.getStore();if(w)return w.selectedCompanyId??null;return LW}function Ib(w){let b=M0.getStore();if(b){b.selectedCompanyId=w;return}LW=w}function F4(w,b){return M0.run(w,b)}function UW(){return M0.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??s3}function KW(){return M0.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function OW(w,b){let $=KW();if(!$)throw new rw("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let W={"Content-Type":w,Authorization:`Bearer ${$}`},Q=b??K1();if(Q)W["x-company-id"]=Q;return W}function ZW(){if(KW())return;console.error(U1(new rw("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function Rw(w,b){let $=w[b];return typeof $==="string"&&$.trim()!==""?$.trim():void 0}function a3(w){if(w===void 0)return;if(typeof w==="string")return w.trim()||void 0;return JSON.stringify(w)}function MW(w){if(!w.trim())return{message:"Request failed"};try{let b=JSON.parse(w);if(typeof b==="string")return{message:b};let $=typeof b.error==="object"&&b.error!==null?b.error:void 0,W=Rw(b,"code")??($?Rw($,"code"):void 0),Q=(typeof b.error==="string"?b.error:void 0)??($?Rw($,"message"):void 0)??Rw(b,"message")??Rw(b,"error")??w,X=Rw(b,"howToFix")??Rw(b,"resolution"),G={...Rw(b,"title")?{title:Rw(b,"title")}:{},...Rw(b,"description")?{description:Rw(b,"description")}:{},...X?{howToFix:X}:{},...Rw(b,"docsUrl")?{docsUrl:Rw(b,"docsUrl")}:{}},J=a3(b.details);if(Object.keys(G).length>0||J)return{message:Q,...W?{code:W}:{},...J?{details:J}:{},...Object.keys(G).length>0?{context:G}:{}};if(typeof b.error==="string")return{message:b.error,...W?{code:W}:{}};if($)return{message:Q,...W?{code:W}:{}};return{message:Q,...W?{code:W}:{}}}catch{return{message:w}}}async function D(w,b,$,W){let Q=OW("application/json",W),X;try{X=await fetch(`${UW()}${b}`,{method:w,headers:Q,body:$?JSON.stringify($):void 0})}catch(G){throw new rw(G instanceof Error?G.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!X.ok){let G=await X.text(),J=MW(G);throw new rw(J.message,X.status,J.details??G,J.code,J.context)}return X.json()}async function VW(w,b,$,W){let Q=new URL(UW()).origin,X=new URL(w,`${Q}/`);if(X.origin!==Q){if(!e3.has(X.pathname))throw new rw("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");X=new URL(`${X.pathname}${X.search}`,`${Q}/`)}let G;try{G=await fetch(X,{method:"PUT",headers:OW($,W),body:b})}catch(J){throw new rw(J instanceof Error?J.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!G.ok){let J=await G.text(),Y=MW(J);throw new rw(Y.message,G.status,Y.details??J,Y.code,Y.context)}}var mj=Object.freeze({status:"aborted"});function O(w,b,$){function W(J,Y){var H;Object.defineProperty(J,"_zod",{value:J._zod??{},enumerable:!1}),(H=J._zod).traits??(H.traits=new Set),J._zod.traits.add(w),b(J,Y);for(let z in G.prototype)if(!(z in J))Object.defineProperty(J,z,{value:G.prototype[z].bind(J)});J._zod.constr=G,J._zod.def=Y}let Q=$?.Parent??Object;class X extends Q{}Object.defineProperty(X,"name",{value:w});function G(J){var Y;let H=$?.Parent?new X:this;W(H,J),(Y=H._zod).deferred??(Y.deferred=[]);for(let z of H._zod.deferred)z();return H}return Object.defineProperty(G,"init",{value:W}),Object.defineProperty(G,Symbol.hasInstance,{value:(J)=>{if($?.Parent&&J instanceof $.Parent)return!0;return J?._zod?.traits?.has(w)}}),Object.defineProperty(G,"name",{value:w}),G}var lj=Symbol("zod_brand");class W1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class V0 extends Error{constructor(w){super(`Encountered unidirectional transform during encode: ${w}`);this.name="ZodEncodeError"}}var Nb={};function kw(w){if(w)Object.assign(Nb,w);return Nb}var d={};BW(d,{unwrapMessage:()=>j0,uint8ArrayToHex:()=>Pz,uint8ArrayToBase64url:()=>jz,uint8ArrayToBase64:()=>TW,stringifyPrimitive:()=>Sb,shallowClone:()=>qW,safeExtend:()=>Uz,required:()=>Zz,randomString:()=>Hz,propertyKeyTypes:()=>Z4,promiseAllObject:()=>Yz,primitiveTypes:()=>PW,prefixIssues:()=>X1,pick:()=>Az,partial:()=>Oz,optionalKeys:()=>M4,omit:()=>Fz,objectClone:()=>Xz,numKeys:()=>zz,nullish:()=>q0,normalizeParams:()=>v,mergeDefs:()=>Z1,merge:()=>Kz,jsonStringifyReplacer:()=>i1,joinValues:()=>Eb,issue:()=>p1,isPlainObject:()=>M1,isObject:()=>_1,hexToUint8Array:()=>qz,getSizableOrigin:()=>NW,getParsedType:()=>Dz,getLengthableOrigin:()=>I0,getEnumValues:()=>U4,getElementAtPath:()=>Jz,floatSafeRemainder:()=>K4,finalizeIssue:()=>cw,extend:()=>Lz,escapeRegex:()=>Q1,esc:()=>Tb,defineLazy:()=>s,createTransparentProxy:()=>Bz,cloneDef:()=>Gz,clone:()=>fw,cleanRegex:()=>P0,cleanEnum:()=>Mz,captureStackTrace:()=>Rb,cached:()=>n1,base64urlToUint8Array:()=>Vz,base64ToUint8Array:()=>EW,assignProp:()=>O1,assertNotEqual:()=>bz,assertNever:()=>Wz,assertIs:()=>$z,assertEqual:()=>wz,assert:()=>Qz,allowsEval:()=>O4,aborted:()=>V1,NUMBER_FORMAT_RANGES:()=>V4,Class:()=>RW,BIGINT_FORMAT_RANGES:()=>IW});function wz(w){return w}function bz(w){return w}function $z(w){}function Wz(w){throw Error()}function Qz(w){}function U4(w){let b=Object.values(w).filter((W)=>typeof W==="number");return Object.entries(w).filter(([W,Q])=>b.indexOf(+W)===-1).map(([W,Q])=>Q)}function Eb(w,b="|"){return w.map(($)=>Sb($)).join(b)}function i1(w,b){if(typeof b==="bigint")return b.toString();return b}function n1(w){return{get value(){{let $=w();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function q0(w){return w===null||w===void 0}function P0(w){let b=w.startsWith("^")?1:0,$=w.endsWith("$")?w.length-1:w.length;return w.slice(b,$)}function K4(w,b){let $=(w.toString().split(".")[1]||"").length,W=b.toString(),Q=(W.split(".")[1]||"").length;if(Q===0&&/\d?e-\d?/.test(W)){let Y=W.match(/\d?e-(\d?)/);if(Y?.[1])Q=Number.parseInt(Y[1])}let X=$>Q?$:Q,G=Number.parseInt(w.toFixed(X).replace(".","")),J=Number.parseInt(b.toFixed(X).replace(".",""));return G%J/10**X}var jW=Symbol("evaluating");function s(w,b,$){let W=void 0;Object.defineProperty(w,b,{get(){if(W===jW)return;if(W===void 0)W=jW,W=$();return W},set(Q){Object.defineProperty(w,b,{value:Q})},configurable:!0})}function Xz(w){return Object.create(Object.getPrototypeOf(w),Object.getOwnPropertyDescriptors(w))}function O1(w,b,$){Object.defineProperty(w,b,{value:$,writable:!0,enumerable:!0,configurable:!0})}function Z1(...w){let b={};for(let $ of w){let W=Object.getOwnPropertyDescriptors($);Object.assign(b,W)}return Object.defineProperties({},b)}function Gz(w){return Z1(w._zod.def)}function Jz(w,b){if(!b)return w;return b.reduce(($,W)=>$?.[W],w)}function Yz(w){let b=Object.keys(w),$=b.map((W)=>w[W]);return Promise.all($).then((W)=>{let Q={};for(let X=0;X<b.length;X++)Q[b[X]]=W[X];return Q})}function Hz(w=10){let $="";for(let W=0;W<w;W++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function Tb(w){return JSON.stringify(w)}var Rb="captureStackTrace"in Error?Error.captureStackTrace:(...w)=>{};function _1(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}var O4=n1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(w){return!1}});function M1(w){if(_1(w)===!1)return!1;let b=w.constructor;if(b===void 0)return!0;let $=b.prototype;if(_1($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function qW(w){if(M1(w))return{...w};if(Array.isArray(w))return[...w];return w}function zz(w){let b=0;for(let $ in w)if(Object.prototype.hasOwnProperty.call(w,$))b++;return b}var Dz=(w)=>{let b=typeof w;switch(b){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(w)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(w))return"array";if(w===null)return"null";if(w.then&&typeof w.then==="function"&&w.catch&&typeof w.catch==="function")return"promise";if(typeof Map<"u"&&w instanceof Map)return"map";if(typeof Set<"u"&&w instanceof Set)return"set";if(typeof Date<"u"&&w instanceof Date)return"date";if(typeof File<"u"&&w instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${b}`)}},Z4=new Set(["string","number","symbol"]),PW=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Q1(w){return w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fw(w,b,$){let W=new w._zod.constr(b??w._zod.def);if(!b||$?.parent)W._zod.parent=w;return W}function v(w){let b=w;if(!b)return{};if(typeof b==="string")return{error:()=>b};if(b?.message!==void 0){if(b?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");b.error=b.message}if(delete b.message,typeof b.error==="string")return{...b,error:()=>b.error};return b}function Bz(w){let b;return new Proxy({},{get($,W,Q){return b??(b=w()),Reflect.get(b,W,Q)},set($,W,Q,X){return b??(b=w()),Reflect.set(b,W,Q,X)},has($,W){return b??(b=w()),Reflect.has(b,W)},deleteProperty($,W){return b??(b=w()),Reflect.deleteProperty(b,W)},ownKeys($){return b??(b=w()),Reflect.ownKeys(b)},getOwnPropertyDescriptor($,W){return b??(b=w()),Reflect.getOwnPropertyDescriptor(b,W)},defineProperty($,W,Q){return b??(b=w()),Reflect.defineProperty(b,W,Q)}})}function Sb(w){if(typeof w==="bigint")return w.toString()+"n";if(typeof w==="string")return`"${w}"`;return`${w}`}function M4(w){return Object.keys(w).filter((b)=>{return w[b]._zod.optin==="optional"&&w[b]._zod.optout==="optional"})}var V4={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},IW={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Az(w,b){let $=w._zod.def,W=Z1(w._zod.def,{get shape(){let Q={};for(let X in b){if(!(X in $.shape))throw Error(`Unrecognized key: "${X}"`);if(!b[X])continue;Q[X]=$.shape[X]}return O1(this,"shape",Q),Q},checks:[]});return fw(w,W)}function Fz(w,b){let $=w._zod.def,W=Z1(w._zod.def,{get shape(){let Q={...w._zod.def.shape};for(let X in b){if(!(X in $.shape))throw Error(`Unrecognized key: "${X}"`);if(!b[X])continue;delete Q[X]}return O1(this,"shape",Q),Q},checks:[]});return fw(w,W)}function Lz(w,b){if(!M1(b))throw Error("Invalid input to extend: expected a plain object");let $=w._zod.def.checks;if($&&$.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let Q=Z1(w._zod.def,{get shape(){let X={...w._zod.def.shape,...b};return O1(this,"shape",X),X},checks:[]});return fw(w,Q)}function Uz(w,b){if(!M1(b))throw Error("Invalid input to safeExtend: expected a plain object");let $={...w._zod.def,get shape(){let W={...w._zod.def.shape,...b};return O1(this,"shape",W),W},checks:w._zod.def.checks};return fw(w,$)}function Kz(w,b){let $=Z1(w._zod.def,{get shape(){let W={...w._zod.def.shape,...b._zod.def.shape};return O1(this,"shape",W),W},get catchall(){return b._zod.def.catchall},checks:[]});return fw(w,$)}function Oz(w,b,$){let W=Z1(b._zod.def,{get shape(){let Q=b._zod.def.shape,X={...Q};if($)for(let G in $){if(!(G in Q))throw Error(`Unrecognized key: "${G}"`);if(!$[G])continue;X[G]=w?new w({type:"optional",innerType:Q[G]}):Q[G]}else for(let G in Q)X[G]=w?new w({type:"optional",innerType:Q[G]}):Q[G];return O1(this,"shape",X),X},checks:[]});return fw(b,W)}function Zz(w,b,$){let W=Z1(b._zod.def,{get shape(){let Q=b._zod.def.shape,X={...Q};if($)for(let G in $){if(!(G in X))throw Error(`Unrecognized key: "${G}"`);if(!$[G])continue;X[G]=new w({type:"nonoptional",innerType:Q[G]})}else for(let G in Q)X[G]=new w({type:"nonoptional",innerType:Q[G]});return O1(this,"shape",X),X},checks:[]});return fw(b,W)}function V1(w,b=0){if(w.aborted===!0)return!0;for(let $=b;$<w.issues.length;$++)if(w.issues[$]?.continue!==!0)return!0;return!1}function X1(w,b){return b.map(($)=>{var W;return(W=$).path??(W.path=[]),$.path.unshift(w),$})}function j0(w){return typeof w==="string"?w:w?.message}function cw(w,b,$){let W={...w,path:w.path??[]};if(!w.message){let Q=j0(w.inst?._zod.def?.error?.(w))??j0(b?.error?.(w))??j0($.customError?.(w))??j0($.localeError?.(w))??"Invalid input";W.message=Q}if(delete W.inst,delete W.continue,!b?.reportInput)delete W.input;return W}function NW(w){if(w instanceof Set)return"set";if(w instanceof Map)return"map";if(w instanceof File)return"file";return"unknown"}function I0(w){if(Array.isArray(w))return"array";if(typeof w==="string")return"string";return"unknown"}function p1(...w){let[b,$,W]=w;if(typeof b==="string")return{message:b,code:"custom",input:$,inst:W};return{...b}}function Mz(w){return Object.entries(w).filter(([b,$])=>{return Number.isNaN(Number.parseInt(b,10))}).map((b)=>b[1])}function EW(w){let b=atob(w),$=new Uint8Array(b.length);for(let W=0;W<b.length;W++)$[W]=b.charCodeAt(W);return $}function TW(w){let b="";for(let $=0;$<w.length;$++)b+=String.fromCharCode(w[$]);return btoa(b)}function Vz(w){let b=w.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-b.length%4)%4);return EW(b+$)}function jz(w){return TW(w).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function qz(w){let b=w.replace(/^0x/,"");if(b.length%2!==0)throw Error("Invalid hex string length");let $=new Uint8Array(b.length/2);for(let W=0;W<b.length;W+=2)$[W/2]=Number.parseInt(b.slice(W,W+2),16);return $}function Pz(w){return Array.from(w).map((b)=>b.toString(16).padStart(2,"0")).join("")}class RW{constructor(...w){}}var SW=(w,b)=>{w.name="$ZodError",Object.defineProperty(w,"_zod",{value:w._zod,enumerable:!1}),Object.defineProperty(w,"issues",{value:b,enumerable:!1}),w.message=JSON.stringify(b,i1,2),Object.defineProperty(w,"toString",{value:()=>w.message,enumerable:!1})},vb=O("$ZodError",SW),j4=O("$ZodError",SW,{Parent:Error});function vW(w,b=($)=>$.message){let $={},W=[];for(let Q of w.issues)if(Q.path.length>0)$[Q.path[0]]=$[Q.path[0]]||[],$[Q.path[0]].push(b(Q));else W.push(b(Q));return{formErrors:W,fieldErrors:$}}function CW(w,b=($)=>$.message){let $={_errors:[]},W=(Q)=>{for(let X of Q.issues)if(X.code==="invalid_union"&&X.errors.length)X.errors.map((G)=>W({issues:G}));else if(X.code==="invalid_key")W({issues:X.issues});else if(X.code==="invalid_element")W({issues:X.issues});else if(X.path.length===0)$._errors.push(b(X));else{let G=$,J=0;while(J<X.path.length){let Y=X.path[J];if(J!==X.path.length-1)G[Y]=G[Y]||{_errors:[]};else G[Y]=G[Y]||{_errors:[]},G[Y]._errors.push(b(X));G=G[Y],J++}}};return W(w),$}var Cb=(w)=>(b,$,W,Q)=>{let X=W?Object.assign(W,{async:!1}):{async:!1},G=b._zod.run({value:$,issues:[]},X);if(G instanceof Promise)throw new W1;if(G.issues.length){let J=new(Q?.Err??w)(G.issues.map((Y)=>cw(Y,X,kw())));throw Rb(J,Q?.callee),J}return G.value};var kb=(w)=>async(b,$,W,Q)=>{let X=W?Object.assign(W,{async:!0}):{async:!0},G=b._zod.run({value:$,issues:[]},X);if(G instanceof Promise)G=await G;if(G.issues.length){let J=new(Q?.Err??w)(G.issues.map((Y)=>cw(Y,X,kw())));throw Rb(J,Q?.callee),J}return G.value};var N0=(w)=>(b,$,W)=>{let Q=W?{...W,async:!1}:{async:!1},X=b._zod.run({value:$,issues:[]},Q);if(X instanceof Promise)throw new W1;return X.issues.length?{success:!1,error:new(w??vb)(X.issues.map((G)=>cw(G,Q,kw())))}:{success:!0,data:X.value}},E0=N0(j4),T0=(w)=>async(b,$,W)=>{let Q=W?Object.assign(W,{async:!0}):{async:!0},X=b._zod.run({value:$,issues:[]},Q);if(X instanceof Promise)X=await X;return X.issues.length?{success:!1,error:new w(X.issues.map((G)=>cw(G,Q,kw())))}:{success:!0,data:X.value}},_b=T0(j4),kW=(w)=>(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return Cb(w)(b,$,Q)};var _W=(w)=>(b,$,W)=>{return Cb(w)(b,$,W)};var xW=(w)=>async(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return kb(w)(b,$,Q)};var hW=(w)=>async(b,$,W)=>{return kb(w)(b,$,W)};var yW=(w)=>(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return N0(w)(b,$,Q)};var uW=(w)=>(b,$,W)=>{return N0(w)(b,$,W)};var fW=(w)=>async(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return T0(w)(b,$,Q)};var cW=(w)=>async(b,$,W)=>{return T0(w)(b,$,W)};var mW=/^[cC][^\s-]{8,}$/,lW=/^[0-9a-z]+$/,gW=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,iW=/^[0-9a-vA-V]{20}$/,nW=/^[A-Za-z0-9]{27}$/,pW=/^[a-zA-Z0-9_-]{21}$/,dW=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var oW=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,q4=(w)=>{if(!w)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${w}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var tW=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function rW(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var sW=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,eW=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,aW=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,wQ=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bQ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,P4=/^[A-Za-z0-9_-]*$/,$Q=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;var WQ=/^\+(?:[0-9]){6,14}[0-9]$/,QQ="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",XQ=new RegExp(`^${QQ}$`);function GQ(w){return typeof w.precision==="number"?w.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":w.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${w.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function JQ(w){return new RegExp(`^${GQ(w)}$`)}function YQ(w){let b=GQ({precision:w.precision}),$=["Z"];if(w.local)$.push("");if(w.offset)$.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let W=`${b}(?:${$.join("|")})`;return new RegExp(`^${QQ}T(?:${W})$`)}var HQ=(w)=>{let b=w?`[\\s\\S]{${w?.minimum??0},${w?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${b}$`)};var zQ=/^-?\d+$/,DQ=/^-?\d+(?:\.\d+)?/,BQ=/^(?:true|false)$/i,AQ=/^null$/i;var FQ=/^[^A-Z]*$/,LQ=/^[^a-z]*$/;var Fw=O("$ZodCheck",(w,b)=>{var $;w._zod??(w._zod={}),w._zod.def=b,($=w._zod).onattach??($.onattach=[])}),UQ={number:"number",bigint:"bigint",object:"date"},I4=O("$ZodCheckLessThan",(w,b)=>{Fw.init(w,b);let $=UQ[typeof b.value];w._zod.onattach.push((W)=>{let Q=W._zod.bag,X=(b.inclusive?Q.maximum:Q.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(b.value<X)if(b.inclusive)Q.maximum=b.value;else Q.exclusiveMaximum=b.value}),w._zod.check=(W)=>{if(b.inclusive?W.value<=b.value:W.value<b.value)return;W.issues.push({origin:$,code:"too_big",maximum:b.value,input:W.value,inclusive:b.inclusive,inst:w,continue:!b.abort})}}),N4=O("$ZodCheckGreaterThan",(w,b)=>{Fw.init(w,b);let $=UQ[typeof b.value];w._zod.onattach.push((W)=>{let Q=W._zod.bag,X=(b.inclusive?Q.minimum:Q.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(b.value>X)if(b.inclusive)Q.minimum=b.value;else Q.exclusiveMinimum=b.value}),w._zod.check=(W)=>{if(b.inclusive?W.value>=b.value:W.value>b.value)return;W.issues.push({origin:$,code:"too_small",minimum:b.value,input:W.value,inclusive:b.inclusive,inst:w,continue:!b.abort})}}),KQ=O("$ZodCheckMultipleOf",(w,b)=>{Fw.init(w,b),w._zod.onattach.push(($)=>{var W;(W=$._zod.bag).multipleOf??(W.multipleOf=b.value)}),w._zod.check=($)=>{if(typeof $.value!==typeof b.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof $.value==="bigint"?$.value%b.value===BigInt(0):K4($.value,b.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:b.value,input:$.value,inst:w,continue:!b.abort})}}),OQ=O("$ZodCheckNumberFormat",(w,b)=>{Fw.init(w,b),b.format=b.format||"float64";let $=b.format?.includes("int"),W=$?"int":"number",[Q,X]=V4[b.format];w._zod.onattach.push((G)=>{let J=G._zod.bag;if(J.format=b.format,J.minimum=Q,J.maximum=X,$)J.pattern=zQ}),w._zod.check=(G)=>{let J=G.value;if($){if(!Number.isInteger(J)){G.issues.push({expected:W,format:b.format,code:"invalid_type",continue:!1,input:J,inst:w});return}if(!Number.isSafeInteger(J)){if(J>0)G.issues.push({input:J,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:w,origin:W,continue:!b.abort});else G.issues.push({input:J,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:w,origin:W,continue:!b.abort});return}}if(J<Q)G.issues.push({origin:"number",input:J,code:"too_small",minimum:Q,inclusive:!0,inst:w,continue:!b.abort});if(J>X)G.issues.push({origin:"number",input:J,code:"too_big",maximum:X,inst:w})}});var ZQ=O("$ZodCheckMaxLength",(w,b)=>{var $;Fw.init(w,b),($=w._zod.def).when??($.when=(W)=>{let Q=W.value;return!q0(Q)&&Q.length!==void 0}),w._zod.onattach.push((W)=>{let Q=W._zod.bag.maximum??Number.POSITIVE_INFINITY;if(b.maximum<Q)W._zod.bag.maximum=b.maximum}),w._zod.check=(W)=>{let Q=W.value;if(Q.length<=b.maximum)return;let G=I0(Q);W.issues.push({origin:G,code:"too_big",maximum:b.maximum,inclusive:!0,input:Q,inst:w,continue:!b.abort})}}),MQ=O("$ZodCheckMinLength",(w,b)=>{var $;Fw.init(w,b),($=w._zod.def).when??($.when=(W)=>{let Q=W.value;return!q0(Q)&&Q.length!==void 0}),w._zod.onattach.push((W)=>{let Q=W._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(b.minimum>Q)W._zod.bag.minimum=b.minimum}),w._zod.check=(W)=>{let Q=W.value;if(Q.length>=b.minimum)return;let G=I0(Q);W.issues.push({origin:G,code:"too_small",minimum:b.minimum,inclusive:!0,input:Q,inst:w,continue:!b.abort})}}),VQ=O("$ZodCheckLengthEquals",(w,b)=>{var $;Fw.init(w,b),($=w._zod.def).when??($.when=(W)=>{let Q=W.value;return!q0(Q)&&Q.length!==void 0}),w._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.minimum=b.length,Q.maximum=b.length,Q.length=b.length}),w._zod.check=(W)=>{let Q=W.value,X=Q.length;if(X===b.length)return;let G=I0(Q),J=X>b.length;W.issues.push({origin:G,...J?{code:"too_big",maximum:b.length}:{code:"too_small",minimum:b.length},inclusive:!0,exact:!0,input:W.value,inst:w,continue:!b.abort})}}),R0=O("$ZodCheckStringFormat",(w,b)=>{var $,W;if(Fw.init(w,b),w._zod.onattach.push((Q)=>{let X=Q._zod.bag;if(X.format=b.format,b.pattern)X.patterns??(X.patterns=new Set),X.patterns.add(b.pattern)}),b.pattern)($=w._zod).check??($.check=(Q)=>{if(b.pattern.lastIndex=0,b.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:b.format,input:Q.value,...b.pattern?{pattern:b.pattern.toString()}:{},inst:w,continue:!b.abort})});else(W=w._zod).check??(W.check=()=>{})}),jQ=O("$ZodCheckRegex",(w,b)=>{R0.init(w,b),w._zod.check=($)=>{if(b.pattern.lastIndex=0,b.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:"regex",input:$.value,pattern:b.pattern.toString(),inst:w,continue:!b.abort})}}),qQ=O("$ZodCheckLowerCase",(w,b)=>{b.pattern??(b.pattern=FQ),R0.init(w,b)}),PQ=O("$ZodCheckUpperCase",(w,b)=>{b.pattern??(b.pattern=LQ),R0.init(w,b)}),IQ=O("$ZodCheckIncludes",(w,b)=>{Fw.init(w,b);let $=Q1(b.includes),W=new RegExp(typeof b.position==="number"?`^.{${b.position}}${$}`:$);b.pattern=W,w._zod.onattach.push((Q)=>{let X=Q._zod.bag;X.patterns??(X.patterns=new Set),X.patterns.add(W)}),w._zod.check=(Q)=>{if(Q.value.includes(b.includes,b.position))return;Q.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:b.includes,input:Q.value,inst:w,continue:!b.abort})}}),NQ=O("$ZodCheckStartsWith",(w,b)=>{Fw.init(w,b);let $=new RegExp(`^${Q1(b.prefix)}.*`);b.pattern??(b.pattern=$),w._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),w._zod.check=(W)=>{if(W.value.startsWith(b.prefix))return;W.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:b.prefix,input:W.value,inst:w,continue:!b.abort})}}),EQ=O("$ZodCheckEndsWith",(w,b)=>{Fw.init(w,b);let $=new RegExp(`.*${Q1(b.suffix)}$`);b.pattern??(b.pattern=$),w._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),w._zod.check=(W)=>{if(W.value.endsWith(b.suffix))return;W.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:b.suffix,input:W.value,inst:w,continue:!b.abort})}});var TQ=O("$ZodCheckOverwrite",(w,b)=>{Fw.init(w,b),w._zod.check=($)=>{$.value=b.tx($.value)}});class E4{constructor(w=[]){if(this.content=[],this.indent=0,this)this.args=w}indented(w){this.indent+=1,w(this),this.indent-=1}write(w){if(typeof w==="function"){w(this,{execution:"sync"}),w(this,{execution:"async"});return}let $=w.split(`
9
+ deps: ${$}}`};var SZ={keyword:"dependencies",type:"object",schemaType:"object",error:T7.error,code(w){let[b,$]=vZ(w);N7(w,b),E7(w,$)}};function vZ({schema:w}){let b={},$={};for(let W in w){if(W==="__proto__")continue;let Q=Array.isArray(w[W])?b:$;Q[W]=w[W]}return[b,$]}function N7(w,b=w.schema){let{gen:$,data:W,it:Q}=w;if(Object.keys(b).length===0)return;let X=$.let("missing");for(let G in b){let J=b[G];if(J.length===0)continue;let Y=(0,Ab.propertyInData)($,W,G,Q.opts.ownProperties);if(w.setParams({property:G,depsCount:J.length,deps:J.join(", ")}),Q.allErrors)$.if(Y,()=>{for(let H of J)(0,Ab.checkReportMissingProp)(w,H)});else $.if(H9._`${Y} && (${(0,Ab.checkMissingProp)(w,J,X)})`),(0,Ab.reportMissingProp)(w,X),$.else()}}T7.validatePropertyDeps=N7;function E7(w,b=w.schema){let{gen:$,data:W,keyword:Q,it:X}=w,G=$.name("valid");for(let J in b){if((0,RZ.alwaysValidSchema)(X,b[J]))continue;$.if((0,Ab.propertyInData)($,W,J,X.opts.ownProperties),()=>{let Y=w.subschema({keyword:Q,schemaProp:J},G);w.mergeValidEvaluated(Y,G)},()=>$.var(G,!0)),w.ok(G)}}T7.validateSchemaDeps=E7;T7.default=SZ});var _7=I((k7)=>{Object.defineProperty(k7,"__esModule",{value:!0});var C7=c(),_Z=o(),xZ={message:"property name must be valid",params:({params:w})=>C7._`{propertyName: ${w.propertyName}}`},hZ={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:xZ,code(w){let{gen:b,schema:$,data:W,it:Q}=w;if((0,_Z.alwaysValidSchema)(Q,$))return;let X=b.name("valid");b.forIn("key",W,(G)=>{w.setParams({propertyName:G}),w.subschema({keyword:"propertyNames",data:G,dataTypes:["string"],propertyName:G,compositeRule:!0},X),b.if((0,C7.not)(X),()=>{if(w.error(!0),!Q.allErrors)b.break()})}),w.ok(X)}};k7.default=hZ});var z9=I((x7)=>{Object.defineProperty(x7,"__esModule",{value:!0});var c6=fw(),pw=c(),fZ=Y1(),m6=o(),uZ={message:"must NOT have additional properties",params:({params:w})=>pw._`{additionalProperty: ${w.additionalProperty}}`},cZ={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:uZ,code(w){let{gen:b,schema:$,parentSchema:W,data:Q,errsCount:X,it:G}=w;if(!X)throw Error("ajv implementation error");let{allErrors:J,opts:Y}=G;if(G.props=!0,Y.removeAdditional!=="all"&&(0,m6.alwaysValidSchema)(G,$))return;let H=(0,c6.allSchemaProperties)(W.properties),z=(0,c6.allSchemaProperties)(W.patternProperties);B(),w.ok(pw._`${X} === ${fZ.default.errors}`);function B(){b.forIn("key",Q,(q)=>{if(!H.length&&!z.length)U(q);else b.if(A(q),()=>U(q))})}function A(q){let P;if(H.length>8){let k=(0,m6.schemaRefOrVal)(G,W.properties,"properties");P=(0,c6.isOwnProperty)(b,k,q)}else if(H.length)P=(0,pw.or)(...H.map((k)=>pw._`${q} === ${k}`));else P=pw.nil;if(z.length)P=(0,pw.or)(P,...z.map((k)=>pw._`${(0,c6.usePattern)(w,k)}.test(${q})`));return(0,pw.not)(P)}function F(q){b.code(pw._`delete ${Q}[${q}]`)}function U(q){if(Y.removeAdditional==="all"||Y.removeAdditional&&$===!1){F(q);return}if($===!1){if(w.setParams({additionalProperty:q}),w.error(),!J)b.break();return}if(typeof $=="object"&&!(0,m6.alwaysValidSchema)(G,$)){let P=b.name("valid");if(Y.removeAdditional==="failing")M(q,P,!1),b.if((0,pw.not)(P),()=>{w.reset(),F(q)});else if(M(q,P),!J)b.if((0,pw.not)(P),()=>b.break())}}function M(q,P,k){let S={keyword:"additionalProperties",dataProp:q,dataPropType:m6.Type.Str};if(k===!1)Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1});w.subschema(S,P)}}};x7.default=cZ});var u7=I((f7)=>{Object.defineProperty(f7,"__esModule",{value:!0});var lZ=bb(),h7=fw(),D9=o(),y7=z9(),gZ={keyword:"properties",type:"object",schemaType:"object",code(w){let{gen:b,schema:$,parentSchema:W,data:Q,it:X}=w;if(X.opts.removeAdditional==="all"&&W.additionalProperties===void 0)y7.default.code(new lZ.KeywordCxt(X,y7.default,"additionalProperties"));let G=(0,h7.allSchemaProperties)($);for(let B of G)X.definedProperties.add(B);if(X.opts.unevaluated&&G.length&&X.props!==!0)X.props=D9.mergeEvaluated.props(b,(0,D9.toHash)(G),X.props);let J=G.filter((B)=>!(0,D9.alwaysValidSchema)(X,$[B]));if(J.length===0)return;let Y=b.name("valid");for(let B of J){if(H(B))z(B);else{if(b.if((0,h7.propertyInData)(b,Q,B,X.opts.ownProperties)),z(B),!X.allErrors)b.else().var(Y,!0);b.endIf()}w.it.definedProperties.add(B),w.ok(Y)}function H(B){return X.opts.useDefaults&&!X.compositeRule&&$[B].default!==void 0}function z(B){w.subschema({keyword:"properties",schemaProp:B,dataProp:B},Y)}}};f7.default=gZ});var i7=I((g7)=>{Object.defineProperty(g7,"__esModule",{value:!0});var c7=fw(),l6=c(),m7=o(),l7=o(),nZ={keyword:"patternProperties",type:"object",schemaType:"object",code(w){let{gen:b,schema:$,data:W,parentSchema:Q,it:X}=w,{opts:G}=X,J=(0,c7.allSchemaProperties)($),Y=J.filter((M)=>(0,m7.alwaysValidSchema)(X,$[M]));if(J.length===0||Y.length===J.length&&(!X.opts.unevaluated||X.props===!0))return;let H=G.strictSchema&&!G.allowMatchingProperties&&Q.properties,z=b.name("valid");if(X.props!==!0&&!(X.props instanceof l6.Name))X.props=(0,l7.evaluatedPropsToName)(b,X.props);let{props:B}=X;A();function A(){for(let M of J){if(H)F(M);if(X.allErrors)U(M);else b.var(z,!0),U(M),b.if(z)}}function F(M){for(let q in H)if(new RegExp(M).test(q))(0,m7.checkStrictMode)(X,`property ${q} matches pattern ${M} (use allowMatchingProperties)`)}function U(M){b.forIn("key",W,(q)=>{b.if(l6._`${(0,c7.usePattern)(w,M)}.test(${q})`,()=>{let P=Y.includes(M);if(!P)w.subschema({keyword:"patternProperties",schemaProp:M,dataProp:q,dataPropType:l7.Type.Str},z);if(X.opts.unevaluated&&B!==!0)b.assign(l6._`${B}[${q}]`,!0);else if(!P&&!X.allErrors)b.if((0,l6.not)(z),()=>b.break())})})}}};g7.default=nZ});var p7=I((n7)=>{Object.defineProperty(n7,"__esModule",{value:!0});var dZ=o(),oZ={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(w){let{gen:b,schema:$,it:W}=w;if((0,dZ.alwaysValidSchema)(W,$)){w.fail();return}let Q=b.name("valid");w.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},Q),w.failResult(Q,()=>w.reset(),()=>w.error())},error:{message:"must NOT be valid"}};n7.default=oZ});var o7=I((d7)=>{Object.defineProperty(d7,"__esModule",{value:!0});var rZ=fw(),sZ={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:rZ.validateUnion,error:{message:"must match a schema in anyOf"}};d7.default=sZ});var r7=I((t7)=>{Object.defineProperty(t7,"__esModule",{value:!0});var g6=c(),aZ=o(),wV={message:"must match exactly one schema in oneOf",params:({params:w})=>g6._`{passingSchemas: ${w.passing}}`},bV={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:wV,code(w){let{gen:b,schema:$,parentSchema:W,it:Q}=w;if(!Array.isArray($))throw Error("ajv implementation error");if(Q.opts.discriminator&&W.discriminator)return;let X=$,G=b.let("valid",!1),J=b.let("passing",null),Y=b.name("_valid");w.setParams({passing:J}),b.block(H),w.result(G,()=>w.reset(),()=>w.error(!0));function H(){X.forEach((z,B)=>{let A;if((0,aZ.alwaysValidSchema)(Q,z))b.var(Y,!0);else A=w.subschema({keyword:"oneOf",schemaProp:B,compositeRule:!0},Y);if(B>0)b.if(g6._`${Y} && ${G}`).assign(G,!1).assign(J,g6._`[${J}, ${B}]`).else();b.if(Y,()=>{if(b.assign(G,!0),b.assign(J,B),A)w.mergeEvaluated(A,g6.Name)})})}}};t7.default=bV});var e7=I((s7)=>{Object.defineProperty(s7,"__esModule",{value:!0});var WV=o(),QV={keyword:"allOf",schemaType:"array",code(w){let{gen:b,schema:$,it:W}=w;if(!Array.isArray($))throw Error("ajv implementation error");let Q=b.name("valid");$.forEach((X,G)=>{if((0,WV.alwaysValidSchema)(W,X))return;let J=w.subschema({keyword:"allOf",schemaProp:G},Q);w.ok(Q),w.mergeEvaluated(J)})}};s7.default=QV});var $H=I((bH)=>{Object.defineProperty(bH,"__esModule",{value:!0});var i6=c(),wH=o(),GV={message:({params:w})=>i6.str`must match "${w.ifClause}" schema`,params:({params:w})=>i6._`{failingKeyword: ${w.ifClause}}`},JV={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:GV,code(w){let{gen:b,parentSchema:$,it:W}=w;if($.then===void 0&&$.else===void 0)(0,wH.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let Q=a7(W,"then"),X=a7(W,"else");if(!Q&&!X)return;let G=b.let("valid",!0),J=b.name("_valid");if(Y(),w.reset(),Q&&X){let z=b.let("ifClause");w.setParams({ifClause:z}),b.if(J,H("then",z),H("else",z))}else if(Q)b.if(J,H("then"));else b.if((0,i6.not)(J),H("else"));w.pass(G,()=>w.error(!0));function Y(){let z=w.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},J);w.mergeEvaluated(z)}function H(z,B){return()=>{let A=w.subschema({keyword:z},J);if(b.assign(G,J),w.mergeValidEvaluated(A,G),B)b.assign(B,i6._`${z}`);else w.setParams({ifClause:z})}}}};function a7(w,b){let $=w.schema[b];return $!==void 0&&!(0,wH.alwaysValidSchema)(w,$)}bH.default=JV});var QH=I((WH)=>{Object.defineProperty(WH,"__esModule",{value:!0});var HV=o(),zV={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:w,parentSchema:b,it:$}){if(b.if===void 0)(0,HV.checkStrictMode)($,`"${w}" without "if" is ignored`)}};WH.default=zV});var GH=I((XH)=>{Object.defineProperty(XH,"__esModule",{value:!0});var BV=J9(),AV=V7(),FV=Y9(),LV=q7(),UV=I7(),KV=v7(),OV=_7(),ZV=z9(),VV=u7(),MV=i7(),jV=p7(),qV=o7(),PV=r7(),IV=e7(),NV=$H(),EV=QH();function TV(w=!1){let b=[jV.default,qV.default,PV.default,IV.default,NV.default,EV.default,OV.default,ZV.default,KV.default,VV.default,MV.default];if(w)b.push(AV.default,LV.default);else b.push(BV.default,FV.default);return b.push(UV.default),b}XH.default=TV});var YH=I((JH)=>{Object.defineProperty(JH,"__esModule",{value:!0});var zw=c(),SV={message:({schemaCode:w})=>zw.str`must match format "${w}"`,params:({schemaCode:w})=>zw._`{format: ${w}}`},vV={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:SV,code(w,b){let{gen:$,data:W,$data:Q,schema:X,schemaCode:G,it:J}=w,{opts:Y,errSchemaPath:H,schemaEnv:z,self:B}=J;if(!Y.validateFormats)return;if(Q)A();else F();function A(){let U=$.scopeValue("formats",{ref:B.formats,code:Y.code.formats}),M=$.const("fDef",zw._`${U}[${G}]`),q=$.let("fType"),P=$.let("format");$.if(zw._`typeof ${M} == "object" && !(${M} instanceof RegExp)`,()=>$.assign(q,zw._`${M}.type || "string"`).assign(P,zw._`${M}.validate`),()=>$.assign(q,zw._`"string"`).assign(P,M)),w.fail$data((0,zw.or)(k(),S()));function k(){if(Y.strictSchema===!1)return zw.nil;return zw._`${G} && !${P}`}function S(){let l=z.$async?zw._`(${M}.async ? await ${P}(${W}) : ${P}(${W}))`:zw._`${P}(${W})`,_=zw._`(typeof ${P} == "function" ? ${l} : ${P}.test(${W}))`;return zw._`${P} && ${P} !== true && ${q} === ${b} && !${_}`}}function F(){let U=B.formats[X];if(!U){k();return}if(U===!0)return;let[M,q,P]=S(U);if(M===b)w.pass(l());function k(){if(Y.strictSchema===!1){B.logger.warn(_());return}throw Error(_());function _(){return`unknown format "${X}" ignored in schema at path "${H}"`}}function S(_){let rw=_ instanceof RegExp?(0,zw.regexpCode)(_):Y.code.formats?zw._`${Y.code.formats}${(0,zw.getProperty)(X)}`:void 0,$1=$.scopeValue("formats",{key:X,ref:_,code:rw});if(typeof _=="object"&&!(_ instanceof RegExp))return[_.type||"string",_.validate,zw._`${$1}.validate`];return["string",_,$1]}function l(){if(typeof U=="object"&&!(U instanceof RegExp)&&U.async){if(!z.$async)throw Error("async format in sync schema");return zw._`await ${P}(${W})`}return typeof q=="function"?zw._`${P}(${W})`:zw._`${P}.test(${W})`}}}};JH.default=vV});var zH=I((HH)=>{Object.defineProperty(HH,"__esModule",{value:!0});var kV=YH(),_V=[kV.default];HH.default=_V});var AH=I((DH)=>{Object.defineProperty(DH,"__esModule",{value:!0});DH.contentVocabulary=DH.metadataVocabulary=void 0;DH.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];DH.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var UH=I((LH)=>{Object.defineProperty(LH,"__esModule",{value:!0});var yV=fY(),fV=D7(),uV=GH(),cV=zH(),FH=AH(),mV=[yV.default,fV.default,(0,uV.default)(),cV.default,FH.metadataVocabulary,FH.contentVocabulary];LH.default=mV});var VH=I((OH)=>{Object.defineProperty(OH,"__esModule",{value:!0});OH.DiscrError=void 0;var KH;(function(w){w.Tag="tag",w.Mapping="mapping"})(KH||(OH.DiscrError=KH={}))});var qH=I((jH)=>{Object.defineProperty(jH,"__esModule",{value:!0});var J0=c(),B9=VH(),MH=I6(),gV=$b(),iV=o(),nV={message:({params:{discrError:w,tagName:b}})=>w===B9.DiscrError.Tag?`tag "${b}" must be string`:`value of tag "${b}" must be in oneOf`,params:({params:{discrError:w,tag:b,tagName:$}})=>J0._`{error: ${w}, tag: ${$}, tagValue: ${b}}`},pV={keyword:"discriminator",type:"object",schemaType:"object",error:nV,code(w){let{gen:b,data:$,schema:W,parentSchema:Q,it:X}=w,{oneOf:G}=Q;if(!X.opts.discriminator)throw Error("discriminator: requires discriminator option");let J=W.propertyName;if(typeof J!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!G)throw Error("discriminator: requires oneOf keyword");let Y=b.let("valid",!1),H=b.const("tag",J0._`${$}${(0,J0.getProperty)(J)}`);b.if(J0._`typeof ${H} == "string"`,()=>z(),()=>w.error(!1,{discrError:B9.DiscrError.Tag,tag:H,tagName:J})),w.ok(Y);function z(){let F=A();b.if(!1);for(let U in F)b.elseIf(J0._`${H} === ${U}`),b.assign(Y,B(F[U]));b.else(),w.error(!1,{discrError:B9.DiscrError.Mapping,tag:H,tagName:J}),b.endIf()}function B(F){let U=b.name("valid"),M=w.subschema({keyword:"oneOf",schemaProp:F},U);return w.mergeEvaluated(M,J0.Name),U}function A(){var F;let U={},M=P(Q),q=!0;for(let l=0;l<G.length;l++){let _=G[l];if((_===null||_===void 0?void 0:_.$ref)&&!(0,iV.schemaHasRulesButRef)(_,X.self.RULES)){let $1=_.$ref;if(_=MH.resolveRef.call(X.self,X.schemaEnv.root,X.baseId,$1),_ instanceof MH.SchemaEnv)_=_.schema;if(_===void 0)throw new gV.default(X.opts.uriResolver,X.baseId,$1)}let rw=(F=_===null||_===void 0?void 0:_.properties)===null||F===void 0?void 0:F[J];if(typeof rw!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${J}"`);q=q&&(M||P(_)),k(rw,l)}if(!q)throw Error(`discriminator: "${J}" must be required`);return U;function P({required:l}){return Array.isArray(l)&&l.includes(J)}function k(l,_){if(l.const)S(l.const,_);else if(l.enum)for(let rw of l.enum)S(rw,_);else throw Error(`discriminator: "properties/${J}" must have "const" or "enum"`)}function S(l,_){if(typeof l!="string"||l in U)throw Error(`discriminator: "${J}" values must be unique strings`);U[l]=_}}}};jH.default=pV});var PH=I((bS,oV)=>{oV.exports={$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:!0,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:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},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:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},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:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},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:!0}});var F9=I((Rw,A9)=>{Object.defineProperty(Rw,"__esModule",{value:!0});Rw.MissingRefError=Rw.ValidationError=Rw.CodeGen=Rw.Name=Rw.nil=Rw.stringify=Rw.str=Rw._=Rw.KeywordCxt=Rw.Ajv=void 0;var tV=TY(),rV=UH(),sV=qH(),IH=PH(),eV=["/properties"],n6="http://json-schema.org/draft-07/schema";class Fb extends tV.default{_addVocabularies(){if(super._addVocabularies(),rV.default.forEach((w)=>this.addVocabulary(w)),this.opts.discriminator)this.addKeyword(sV.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let w=this.opts.$data?this.$dataMetaSchema(IH,eV):IH;this.addMetaSchema(w,n6,!1),this.refs["http://json-schema.org/schema"]=n6}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(n6)?n6:void 0)}}Rw.Ajv=Fb;A9.exports=Rw=Fb;A9.exports.Ajv=Fb;Object.defineProperty(Rw,"__esModule",{value:!0});Rw.default=Fb;var aV=bb();Object.defineProperty(Rw,"KeywordCxt",{enumerable:!0,get:function(){return aV.KeywordCxt}});var Y0=c();Object.defineProperty(Rw,"_",{enumerable:!0,get:function(){return Y0._}});Object.defineProperty(Rw,"str",{enumerable:!0,get:function(){return Y0.str}});Object.defineProperty(Rw,"stringify",{enumerable:!0,get:function(){return Y0.stringify}});Object.defineProperty(Rw,"nil",{enumerable:!0,get:function(){return Y0.nil}});Object.defineProperty(Rw,"Name",{enumerable:!0,get:function(){return Y0.Name}});Object.defineProperty(Rw,"CodeGen",{enumerable:!0,get:function(){return Y0.CodeGen}});var wM=q6();Object.defineProperty(Rw,"ValidationError",{enumerable:!0,get:function(){return wM.default}});var bM=$b();Object.defineProperty(Rw,"MissingRefError",{enumerable:!0,get:function(){return bM.default}})});var xH=I((kH)=>{Object.defineProperty(kH,"__esModule",{value:!0});kH.formatNames=kH.fastFormats=kH.fullFormats=void 0;function w1(w,b){return{validate:w,compare:b}}kH.fullFormats={date:w1(RH,O9),time:w1(U9(!0),Z9),"date-time":w1(NH(!0),vH),"iso-time":w1(U9(),SH),"iso-date-time":w1(NH(),CH),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:HM,"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:UM,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:zM,int32:{type:"number",validate:AM},int64:{type:"number",validate:FM},float:{type:"number",validate:TH},double:{type:"number",validate:TH},password:!0,binary:!0};kH.fastFormats={...kH.fullFormats,date:w1(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,O9),time:w1(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Z9),"date-time":w1(/^\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,vH),"iso-time":w1(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,SH),"iso-date-time":w1(/^\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,CH),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};kH.formatNames=Object.keys(kH.fullFormats);function QM(w){return w%4===0&&(w%100!==0||w%400===0)}var XM=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,GM=[0,31,28,31,30,31,30,31,31,30,31,30,31];function RH(w){let b=XM.exec(w);if(!b)return!1;let $=+b[1],W=+b[2],Q=+b[3];return W>=1&&W<=12&&Q>=1&&Q<=(W===2&&QM($)?29:GM[W])}function O9(w,b){if(!(w&&b))return;if(w>b)return 1;if(w<b)return-1;return 0}var L9=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function U9(w){return function($){let W=L9.exec($);if(!W)return!1;let Q=+W[1],X=+W[2],G=+W[3],J=W[4],Y=W[5]==="-"?-1:1,H=+(W[6]||0),z=+(W[7]||0);if(H>23||z>59||w&&!J)return!1;if(Q<=23&&X<=59&&G<60)return!0;let B=X-z*Y,A=Q-H*Y-(B<0?1:0);return(A===23||A===-1)&&(B===59||B===-1)&&G<61}}function Z9(w,b){if(!(w&&b))return;let $=new Date("2020-01-01T"+w).valueOf(),W=new Date("2020-01-01T"+b).valueOf();if(!($&&W))return;return $-W}function SH(w,b){if(!(w&&b))return;let $=L9.exec(w),W=L9.exec(b);if(!($&&W))return;if(w=$[1]+$[2]+$[3],b=W[1]+W[2]+W[3],w>b)return 1;if(w<b)return-1;return 0}var K9=/t|\s/i;function NH(w){let b=U9(w);return function(W){let Q=W.split(K9);return Q.length===2&&RH(Q[0])&&b(Q[1])}}function vH(w,b){if(!(w&&b))return;let $=new Date(w).valueOf(),W=new Date(b).valueOf();if(!($&&W))return;return $-W}function CH(w,b){if(!(w&&b))return;let[$,W]=w.split(K9),[Q,X]=b.split(K9),G=O9($,Q);if(G===void 0)return;return G||Z9(W,X)}var JM=/\/|:/,YM=/^(?:[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;function HM(w){return JM.test(w)&&YM.test(w)}var EH=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function zM(w){return EH.lastIndex=0,EH.test(w)}var DM=-2147483648,BM=2147483647;function AM(w){return Number.isInteger(w)&&w<=BM&&w>=DM}function FM(w){return Number.isInteger(w)}function TH(){return!0}var LM=/[^\\]\\Z/;function UM(w){if(LM.test(w))return!1;try{return new RegExp(w),!0}catch(b){return!1}}});var yH=I((hH)=>{Object.defineProperty(hH,"__esModule",{value:!0});hH.formatLimitDefinition=void 0;var OM=F9(),dw=c(),C1=dw.operators,p6={formatMaximum:{okStr:"<=",ok:C1.LTE,fail:C1.GT},formatMinimum:{okStr:">=",ok:C1.GTE,fail:C1.LT},formatExclusiveMaximum:{okStr:"<",ok:C1.LT,fail:C1.GTE},formatExclusiveMinimum:{okStr:">",ok:C1.GT,fail:C1.LTE}},ZM={message:({keyword:w,schemaCode:b})=>dw.str`should be ${p6[w].okStr} ${b}`,params:({keyword:w,schemaCode:b})=>dw._`{comparison: ${p6[w].okStr}, limit: ${b}}`};hH.formatLimitDefinition={keyword:Object.keys(p6),type:"string",schemaType:"string",$data:!0,error:ZM,code(w){let{gen:b,data:$,schemaCode:W,keyword:Q,it:X}=w,{opts:G,self:J}=X;if(!G.validateFormats)return;let Y=new OM.KeywordCxt(X,J.RULES.all.format.definition,"format");if(Y.$data)H();else z();function H(){let A=b.scopeValue("formats",{ref:J.formats,code:G.code.formats}),F=b.const("fmt",dw._`${A}[${Y.schemaCode}]`);w.fail$data((0,dw.or)(dw._`typeof ${F} != "object"`,dw._`${F} instanceof RegExp`,dw._`typeof ${F}.compare != "function"`,B(F)))}function z(){let A=Y.schema,F=J.formats[A];if(!F||F===!0)return;if(typeof F!="object"||F instanceof RegExp||typeof F.compare!="function")throw Error(`"${Q}": format "${A}" does not define "compare" function`);let U=b.scopeValue("formats",{key:A,ref:F,code:G.code.formats?dw._`${G.code.formats}${(0,dw.getProperty)(A)}`:void 0});w.fail$data(B(U))}function B(A){return dw._`${A}.compare(${$}, ${W}) ${p6[Q].fail} 0`}},dependencies:["format"]};var VM=(w)=>{return w.addKeyword(hH.formatLimitDefinition),w};hH.default=VM});var mH=I((Lb,cH)=>{Object.defineProperty(Lb,"__esModule",{value:!0});var H0=xH(),jM=yH(),j9=c(),fH=new j9.Name("fullFormats"),qM=new j9.Name("fastFormats"),q9=(w,b={keywords:!0})=>{if(Array.isArray(b))return uH(w,b,H0.fullFormats,fH),w;let[$,W]=b.mode==="fast"?[H0.fastFormats,qM]:[H0.fullFormats,fH],Q=b.formats||H0.formatNames;if(uH(w,Q,$,W),b.keywords)(0,jM.default)(w);return w};q9.get=(w,b="full")=>{let W=(b==="fast"?H0.fastFormats:H0.fullFormats)[w];if(!W)throw Error(`Unknown format "${w}"`);return W};function uH(w,b,$,W){var Q,X;(Q=(X=w.opts.code).formats)!==null&&Q!==void 0||(X.formats=j9._`require("ajv-formats/dist/formats").${W}`);for(let G of b)w.addFormat(G,$[G])}cH.exports=Lb=q9;Object.defineProperty(Lb,"__esModule",{value:!0});Lb.default=q9});import{AsyncLocalStorage as s3}from"node:async_hooks";class sw extends Error{statusCode;rawDetails;code;context;constructor(w,b,$,W,Q){super(w);this.statusCode=b;this.rawDetails=$;this.code=W;this.context=Q;this.name="McpApiError"}}function o3(w){if(w instanceof sw)return{message:w.message,statusCode:w.statusCode,code:w.code,rawDetails:w.rawDetails,context:w.context};if(w instanceof Error)return{message:w.message};return{message:String(w)}}function t3(w){let b=w.match(/api key is missing required scopes?:\s*(.+)$/i);if(!b?.[1])return[];return[...new Set(b[1].match(/[a-z_]+:[a-z_]+/gi)??[])]}function r3(w){let b=o3(w),$=b.message.trim()||"Unknown error",W=$.toLowerCase(),Q=b.rawDetails?.trim()||$;if(b.context?.title||b.context?.description||b.context?.howToFix||b.context?.docsUrl)return{title:b.context.title??(b.statusCode===409?"Request conflict":"API request failed"),description:b.context.description??$,howToFix:b.context.howToFix??"Review the details below, adjust the tool input, and retry.",docsUrl:b.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.code==="MCP_AUTH_REQUIRED"||W.includes("sequenzy_api_key environment variable is required"))return{title:"Missing MCP API key",description:"The MCP server started without a Sequenzy API key, so it cannot authenticate any tool or resource request.",howToFix:"Add `SEQUENZY_API_KEY` to the MCP server environment, or run `npx @sequenzy/setup` to configure the integration automatically.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.statusCode===401||b.code==="UNAUTHORIZED")return{title:"Authentication failed",description:"The MCP server reached Sequenzy, but the current API key was rejected.",howToFix:"Replace `SEQUENZY_API_KEY` with a valid personal API key, then restart the MCP client so it reconnects with fresh credentials.",docsUrl:"https://docs.sequenzy.com/authentication",details:Q};let X=t3($);if(X.length>0){let G=X.map((Y)=>`\`${Y}\``).join(", "),J=X.every((Y)=>Y.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${X.length===1?"scope":"scopes"}: ${G}.`,howToFix:`For a local API-key connection, call \`get_account\` to inspect \`apiKeyPermissions\` and open \`apiKeyPermissions.manageUrl\` (or \`companies[].settingsUrl\` → API Keys). If \`get_account\` also requires \`account:read\`, open ${"https://sequenzy.com/dashboard"} directly and use the MCP setup or Settings → API Keys. Create a replacement key with ${J} including ${G}, replace \`SEQUENZY_API_KEY\`, and restart the client. For hosted OAuth MCP, disconnect and reauthorize the Sequenzy connection with a preset or Custom permissions including ${G}. Existing key permissions cannot be edited in place.`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}if(b.statusCode===403||W.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to access the requested company or action.",howToFix:"Use an API key that belongs to the right account, or select a company the key can access before retrying the tool call.",docsUrl:"https://docs.sequenzy.com/authentication",details:Q};if(W.includes("no company available")||W.includes("company not found"))return{title:"Company selection required",description:"The MCP server could not resolve a company for this request.",howToFix:"Call `get_account` to inspect available companies, then call `select_company`, or pass `companyId` explicitly in the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.statusCode===404||W.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the requested campaign, template, sequence, company, or subscriber.",howToFix:"List or fetch the resource collection first, then retry the tool with a confirmed ID or email value.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("already exists"))return{title:"Resource already exists",description:"Sequenzy rejected this MCP request because it would create a duplicate resource.",howToFix:"List the existing resources first, reuse the matching resource when appropriate, or retry with a unique name or domain.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.statusCode===409)return{title:"Request conflict",description:"Sequenzy rejected this request because the resource changed or an operation is already in progress.",howToFix:"Refresh the resource state, choose the lifecycle action allowed by its current status, and retry at most once.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.statusCode===429||W.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this MCP request because too many requests were sent too quickly.",howToFix:"Wait briefly before retrying. If the client is looping, reduce retries or add backoff before the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.code==="NETWORK_ERROR"||W.includes("fetch failed"))return{title:"Network or configuration error",description:"The MCP server could not reach the Sequenzy API from this environment.",howToFix:"Check connectivity and verify `SEQUENZY_API_URL` if you override it in the MCP environment.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("unknown tool")||W.includes("unknown resource"))return{title:"Unsupported MCP request",description:"The client asked for a tool or resource name that this Sequenzy MCP server does not expose.",howToFix:"Refresh the client's tool list and call only the names returned by `list_tools` or `list_resources`.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(W.includes("is required")||W.includes("invalid"))return{title:"Invalid MCP input",description:"The tool call was missing a required field or included an invalid value.",howToFix:"Review the tool schema, supply the missing argument, and retry the request with corrected input.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};if(b.statusCode&&b.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If it still fails, keep the details below and consult the docs before escalating.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the details below, adjust the tool input or credentials, and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:Q}}function K1(w){let b=r3(w);return[`Sequenzy MCP error: ${b.title}`,`Description: ${b.description}`,`How to fix: ${b.howToFix}`,`Docs: ${b.docsUrl}`,`Details: ${b.details}`].join(`
10
+ `)}var e3="https://api.sequenzy.com",a3=new Set(["/api/v1/media/upload-bytes","/v1/media/upload-bytes"]),M0=new s3,FW=!1;function LW(){FW=!0}function Ib(){return FW}var UW=null;function O1(){let w=M0.getStore();if(w)return w.selectedCompanyId??null;return UW}function Nb(w){let b=M0.getStore();if(b){b.selectedCompanyId=w;return}UW=w}function F4(w,b){return M0.run(w,b)}function KW(){return M0.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??e3}function OW(){return M0.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function ZW(w,b){let $=OW();if(!$)throw new sw("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let W={"Content-Type":w,Authorization:`Bearer ${$}`},Q=b??O1();if(Q)W["x-company-id"]=Q;return W}function VW(){if(OW())return;console.error(K1(new sw("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function Sw(w,b){let $=w[b];return typeof $==="string"&&$.trim()!==""?$.trim():void 0}function wz(w){if(w===void 0)return;if(typeof w==="string")return w.trim()||void 0;return JSON.stringify(w)}function MW(w){if(!w.trim())return{message:"Request failed"};try{let b=JSON.parse(w);if(typeof b==="string")return{message:b};let $=typeof b.error==="object"&&b.error!==null?b.error:void 0,W=Sw(b,"code")??($?Sw($,"code"):void 0),Q=(typeof b.error==="string"?b.error:void 0)??($?Sw($,"message"):void 0)??Sw(b,"message")??Sw(b,"error")??w,X=Sw(b,"howToFix")??Sw(b,"resolution"),G={...Sw(b,"title")?{title:Sw(b,"title")}:{},...Sw(b,"description")?{description:Sw(b,"description")}:{},...X?{howToFix:X}:{},...Sw(b,"docsUrl")?{docsUrl:Sw(b,"docsUrl")}:{}},J=wz(b.details);if(Object.keys(G).length>0||J)return{message:Q,...W?{code:W}:{},...J?{details:J}:{},...Object.keys(G).length>0?{context:G}:{}};if(typeof b.error==="string")return{message:b.error,...W?{code:W}:{}};if($)return{message:Q,...W?{code:W}:{}};return{message:Q,...W?{code:W}:{}}}catch{return{message:w}}}async function D(w,b,$,W){let Q=ZW("application/json",W),X;try{X=await fetch(`${KW()}${b}`,{method:w,headers:Q,body:$?JSON.stringify($):void 0})}catch(G){throw new sw(G instanceof Error?G.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!X.ok){let G=await X.text(),J=MW(G);throw new sw(J.message,X.status,J.details??G,J.code,J.context)}return X.json()}async function jW(w,b,$,W){let Q=new URL(KW()).origin,X=new URL(w,`${Q}/`);if(X.origin!==Q){if(!a3.has(X.pathname))throw new sw("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");X=new URL(`${X.pathname}${X.search}`,`${Q}/`)}let G;try{G=await fetch(X,{method:"PUT",headers:ZW($,W),body:b})}catch(J){throw new sw(J instanceof Error?J.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!G.ok){let J=await G.text(),Y=MW(J);throw new sw(Y.message,G.status,Y.details??J,Y.code,Y.context)}}var lj=Object.freeze({status:"aborted"});function O(w,b,$){function W(J,Y){var H;Object.defineProperty(J,"_zod",{value:J._zod??{},enumerable:!1}),(H=J._zod).traits??(H.traits=new Set),J._zod.traits.add(w),b(J,Y);for(let z in G.prototype)if(!(z in J))Object.defineProperty(J,z,{value:G.prototype[z].bind(J)});J._zod.constr=G,J._zod.def=Y}let Q=$?.Parent??Object;class X extends Q{}Object.defineProperty(X,"name",{value:w});function G(J){var Y;let H=$?.Parent?new X:this;W(H,J),(Y=H._zod).deferred??(Y.deferred=[]);for(let z of H._zod.deferred)z();return H}return Object.defineProperty(G,"init",{value:W}),Object.defineProperty(G,Symbol.hasInstance,{value:(J)=>{if($?.Parent&&J instanceof $.Parent)return!0;return J?._zod?.traits?.has(w)}}),Object.defineProperty(G,"name",{value:w}),G}var gj=Symbol("zod_brand");class W1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class j0 extends Error{constructor(w){super(`Encountered unidirectional transform during encode: ${w}`);this.name="ZodEncodeError"}}var Eb={};function xw(w){if(w)Object.assign(Eb,w);return Eb}var d={};AW(d,{unwrapMessage:()=>q0,uint8ArrayToHex:()=>Iz,uint8ArrayToBase64url:()=>qz,uint8ArrayToBase64:()=>RW,stringifyPrimitive:()=>vb,shallowClone:()=>PW,safeExtend:()=>Kz,required:()=>Vz,randomString:()=>zz,propertyKeyTypes:()=>Z4,promiseAllObject:()=>Hz,primitiveTypes:()=>IW,prefixIssues:()=>X1,pick:()=>Fz,partial:()=>Zz,optionalKeys:()=>V4,omit:()=>Lz,objectClone:()=>Gz,numKeys:()=>Dz,nullish:()=>P0,normalizeParams:()=>v,mergeDefs:()=>V1,merge:()=>Oz,jsonStringifyReplacer:()=>n1,joinValues:()=>Tb,issue:()=>d1,isPlainObject:()=>M1,isObject:()=>x1,hexToUint8Array:()=>Pz,getSizableOrigin:()=>EW,getParsedType:()=>Bz,getLengthableOrigin:()=>N0,getEnumValues:()=>U4,getElementAtPath:()=>Yz,floatSafeRemainder:()=>K4,finalizeIssue:()=>mw,extend:()=>Uz,escapeRegex:()=>Q1,esc:()=>Rb,defineLazy:()=>s,createTransparentProxy:()=>Az,cloneDef:()=>Jz,clone:()=>cw,cleanRegex:()=>I0,cleanEnum:()=>Mz,captureStackTrace:()=>Sb,cached:()=>p1,base64urlToUint8Array:()=>jz,base64ToUint8Array:()=>TW,assignProp:()=>Z1,assertNotEqual:()=>$z,assertNever:()=>Qz,assertIs:()=>Wz,assertEqual:()=>bz,assert:()=>Xz,allowsEval:()=>O4,aborted:()=>j1,NUMBER_FORMAT_RANGES:()=>M4,Class:()=>SW,BIGINT_FORMAT_RANGES:()=>NW});function bz(w){return w}function $z(w){return w}function Wz(w){}function Qz(w){throw Error()}function Xz(w){}function U4(w){let b=Object.values(w).filter((W)=>typeof W==="number");return Object.entries(w).filter(([W,Q])=>b.indexOf(+W)===-1).map(([W,Q])=>Q)}function Tb(w,b="|"){return w.map(($)=>vb($)).join(b)}function n1(w,b){if(typeof b==="bigint")return b.toString();return b}function p1(w){return{get value(){{let $=w();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function P0(w){return w===null||w===void 0}function I0(w){let b=w.startsWith("^")?1:0,$=w.endsWith("$")?w.length-1:w.length;return w.slice(b,$)}function K4(w,b){let $=(w.toString().split(".")[1]||"").length,W=b.toString(),Q=(W.split(".")[1]||"").length;if(Q===0&&/\d?e-\d?/.test(W)){let Y=W.match(/\d?e-(\d?)/);if(Y?.[1])Q=Number.parseInt(Y[1])}let X=$>Q?$:Q,G=Number.parseInt(w.toFixed(X).replace(".","")),J=Number.parseInt(b.toFixed(X).replace(".",""));return G%J/10**X}var qW=Symbol("evaluating");function s(w,b,$){let W=void 0;Object.defineProperty(w,b,{get(){if(W===qW)return;if(W===void 0)W=qW,W=$();return W},set(Q){Object.defineProperty(w,b,{value:Q})},configurable:!0})}function Gz(w){return Object.create(Object.getPrototypeOf(w),Object.getOwnPropertyDescriptors(w))}function Z1(w,b,$){Object.defineProperty(w,b,{value:$,writable:!0,enumerable:!0,configurable:!0})}function V1(...w){let b={};for(let $ of w){let W=Object.getOwnPropertyDescriptors($);Object.assign(b,W)}return Object.defineProperties({},b)}function Jz(w){return V1(w._zod.def)}function Yz(w,b){if(!b)return w;return b.reduce(($,W)=>$?.[W],w)}function Hz(w){let b=Object.keys(w),$=b.map((W)=>w[W]);return Promise.all($).then((W)=>{let Q={};for(let X=0;X<b.length;X++)Q[b[X]]=W[X];return Q})}function zz(w=10){let $="";for(let W=0;W<w;W++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function Rb(w){return JSON.stringify(w)}var Sb="captureStackTrace"in Error?Error.captureStackTrace:(...w)=>{};function x1(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}var O4=p1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(w){return!1}});function M1(w){if(x1(w)===!1)return!1;let b=w.constructor;if(b===void 0)return!0;let $=b.prototype;if(x1($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function PW(w){if(M1(w))return{...w};if(Array.isArray(w))return[...w];return w}function Dz(w){let b=0;for(let $ in w)if(Object.prototype.hasOwnProperty.call(w,$))b++;return b}var Bz=(w)=>{let b=typeof w;switch(b){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(w)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(w))return"array";if(w===null)return"null";if(w.then&&typeof w.then==="function"&&w.catch&&typeof w.catch==="function")return"promise";if(typeof Map<"u"&&w instanceof Map)return"map";if(typeof Set<"u"&&w instanceof Set)return"set";if(typeof Date<"u"&&w instanceof Date)return"date";if(typeof File<"u"&&w instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${b}`)}},Z4=new Set(["string","number","symbol"]),IW=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Q1(w){return w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cw(w,b,$){let W=new w._zod.constr(b??w._zod.def);if(!b||$?.parent)W._zod.parent=w;return W}function v(w){let b=w;if(!b)return{};if(typeof b==="string")return{error:()=>b};if(b?.message!==void 0){if(b?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");b.error=b.message}if(delete b.message,typeof b.error==="string")return{...b,error:()=>b.error};return b}function Az(w){let b;return new Proxy({},{get($,W,Q){return b??(b=w()),Reflect.get(b,W,Q)},set($,W,Q,X){return b??(b=w()),Reflect.set(b,W,Q,X)},has($,W){return b??(b=w()),Reflect.has(b,W)},deleteProperty($,W){return b??(b=w()),Reflect.deleteProperty(b,W)},ownKeys($){return b??(b=w()),Reflect.ownKeys(b)},getOwnPropertyDescriptor($,W){return b??(b=w()),Reflect.getOwnPropertyDescriptor(b,W)},defineProperty($,W,Q){return b??(b=w()),Reflect.defineProperty(b,W,Q)}})}function vb(w){if(typeof w==="bigint")return w.toString()+"n";if(typeof w==="string")return`"${w}"`;return`${w}`}function V4(w){return Object.keys(w).filter((b)=>{return w[b]._zod.optin==="optional"&&w[b]._zod.optout==="optional"})}var M4={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},NW={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Fz(w,b){let $=w._zod.def,W=V1(w._zod.def,{get shape(){let Q={};for(let X in b){if(!(X in $.shape))throw Error(`Unrecognized key: "${X}"`);if(!b[X])continue;Q[X]=$.shape[X]}return Z1(this,"shape",Q),Q},checks:[]});return cw(w,W)}function Lz(w,b){let $=w._zod.def,W=V1(w._zod.def,{get shape(){let Q={...w._zod.def.shape};for(let X in b){if(!(X in $.shape))throw Error(`Unrecognized key: "${X}"`);if(!b[X])continue;delete Q[X]}return Z1(this,"shape",Q),Q},checks:[]});return cw(w,W)}function Uz(w,b){if(!M1(b))throw Error("Invalid input to extend: expected a plain object");let $=w._zod.def.checks;if($&&$.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let Q=V1(w._zod.def,{get shape(){let X={...w._zod.def.shape,...b};return Z1(this,"shape",X),X},checks:[]});return cw(w,Q)}function Kz(w,b){if(!M1(b))throw Error("Invalid input to safeExtend: expected a plain object");let $={...w._zod.def,get shape(){let W={...w._zod.def.shape,...b};return Z1(this,"shape",W),W},checks:w._zod.def.checks};return cw(w,$)}function Oz(w,b){let $=V1(w._zod.def,{get shape(){let W={...w._zod.def.shape,...b._zod.def.shape};return Z1(this,"shape",W),W},get catchall(){return b._zod.def.catchall},checks:[]});return cw(w,$)}function Zz(w,b,$){let W=V1(b._zod.def,{get shape(){let Q=b._zod.def.shape,X={...Q};if($)for(let G in $){if(!(G in Q))throw Error(`Unrecognized key: "${G}"`);if(!$[G])continue;X[G]=w?new w({type:"optional",innerType:Q[G]}):Q[G]}else for(let G in Q)X[G]=w?new w({type:"optional",innerType:Q[G]}):Q[G];return Z1(this,"shape",X),X},checks:[]});return cw(b,W)}function Vz(w,b,$){let W=V1(b._zod.def,{get shape(){let Q=b._zod.def.shape,X={...Q};if($)for(let G in $){if(!(G in X))throw Error(`Unrecognized key: "${G}"`);if(!$[G])continue;X[G]=new w({type:"nonoptional",innerType:Q[G]})}else for(let G in Q)X[G]=new w({type:"nonoptional",innerType:Q[G]});return Z1(this,"shape",X),X},checks:[]});return cw(b,W)}function j1(w,b=0){if(w.aborted===!0)return!0;for(let $=b;$<w.issues.length;$++)if(w.issues[$]?.continue!==!0)return!0;return!1}function X1(w,b){return b.map(($)=>{var W;return(W=$).path??(W.path=[]),$.path.unshift(w),$})}function q0(w){return typeof w==="string"?w:w?.message}function mw(w,b,$){let W={...w,path:w.path??[]};if(!w.message){let Q=q0(w.inst?._zod.def?.error?.(w))??q0(b?.error?.(w))??q0($.customError?.(w))??q0($.localeError?.(w))??"Invalid input";W.message=Q}if(delete W.inst,delete W.continue,!b?.reportInput)delete W.input;return W}function EW(w){if(w instanceof Set)return"set";if(w instanceof Map)return"map";if(w instanceof File)return"file";return"unknown"}function N0(w){if(Array.isArray(w))return"array";if(typeof w==="string")return"string";return"unknown"}function d1(...w){let[b,$,W]=w;if(typeof b==="string")return{message:b,code:"custom",input:$,inst:W};return{...b}}function Mz(w){return Object.entries(w).filter(([b,$])=>{return Number.isNaN(Number.parseInt(b,10))}).map((b)=>b[1])}function TW(w){let b=atob(w),$=new Uint8Array(b.length);for(let W=0;W<b.length;W++)$[W]=b.charCodeAt(W);return $}function RW(w){let b="";for(let $=0;$<w.length;$++)b+=String.fromCharCode(w[$]);return btoa(b)}function jz(w){let b=w.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-b.length%4)%4);return TW(b+$)}function qz(w){return RW(w).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Pz(w){let b=w.replace(/^0x/,"");if(b.length%2!==0)throw Error("Invalid hex string length");let $=new Uint8Array(b.length/2);for(let W=0;W<b.length;W+=2)$[W/2]=Number.parseInt(b.slice(W,W+2),16);return $}function Iz(w){return Array.from(w).map((b)=>b.toString(16).padStart(2,"0")).join("")}class SW{constructor(...w){}}var vW=(w,b)=>{w.name="$ZodError",Object.defineProperty(w,"_zod",{value:w._zod,enumerable:!1}),Object.defineProperty(w,"issues",{value:b,enumerable:!1}),w.message=JSON.stringify(b,n1,2),Object.defineProperty(w,"toString",{value:()=>w.message,enumerable:!1})},Cb=O("$ZodError",vW),j4=O("$ZodError",vW,{Parent:Error});function CW(w,b=($)=>$.message){let $={},W=[];for(let Q of w.issues)if(Q.path.length>0)$[Q.path[0]]=$[Q.path[0]]||[],$[Q.path[0]].push(b(Q));else W.push(b(Q));return{formErrors:W,fieldErrors:$}}function kW(w,b=($)=>$.message){let $={_errors:[]},W=(Q)=>{for(let X of Q.issues)if(X.code==="invalid_union"&&X.errors.length)X.errors.map((G)=>W({issues:G}));else if(X.code==="invalid_key")W({issues:X.issues});else if(X.code==="invalid_element")W({issues:X.issues});else if(X.path.length===0)$._errors.push(b(X));else{let G=$,J=0;while(J<X.path.length){let Y=X.path[J];if(J!==X.path.length-1)G[Y]=G[Y]||{_errors:[]};else G[Y]=G[Y]||{_errors:[]},G[Y]._errors.push(b(X));G=G[Y],J++}}};return W(w),$}var kb=(w)=>(b,$,W,Q)=>{let X=W?Object.assign(W,{async:!1}):{async:!1},G=b._zod.run({value:$,issues:[]},X);if(G instanceof Promise)throw new W1;if(G.issues.length){let J=new(Q?.Err??w)(G.issues.map((Y)=>mw(Y,X,xw())));throw Sb(J,Q?.callee),J}return G.value};var _b=(w)=>async(b,$,W,Q)=>{let X=W?Object.assign(W,{async:!0}):{async:!0},G=b._zod.run({value:$,issues:[]},X);if(G instanceof Promise)G=await G;if(G.issues.length){let J=new(Q?.Err??w)(G.issues.map((Y)=>mw(Y,X,xw())));throw Sb(J,Q?.callee),J}return G.value};var E0=(w)=>(b,$,W)=>{let Q=W?{...W,async:!1}:{async:!1},X=b._zod.run({value:$,issues:[]},Q);if(X instanceof Promise)throw new W1;return X.issues.length?{success:!1,error:new(w??Cb)(X.issues.map((G)=>mw(G,Q,xw())))}:{success:!0,data:X.value}},T0=E0(j4),R0=(w)=>async(b,$,W)=>{let Q=W?Object.assign(W,{async:!0}):{async:!0},X=b._zod.run({value:$,issues:[]},Q);if(X instanceof Promise)X=await X;return X.issues.length?{success:!1,error:new w(X.issues.map((G)=>mw(G,Q,xw())))}:{success:!0,data:X.value}},xb=R0(j4),_W=(w)=>(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return kb(w)(b,$,Q)};var xW=(w)=>(b,$,W)=>{return kb(w)(b,$,W)};var hW=(w)=>async(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return _b(w)(b,$,Q)};var yW=(w)=>async(b,$,W)=>{return _b(w)(b,$,W)};var fW=(w)=>(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return E0(w)(b,$,Q)};var uW=(w)=>(b,$,W)=>{return E0(w)(b,$,W)};var cW=(w)=>async(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return R0(w)(b,$,Q)};var mW=(w)=>async(b,$,W)=>{return R0(w)(b,$,W)};var lW=/^[cC][^\s-]{8,}$/,gW=/^[0-9a-z]+$/,iW=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,nW=/^[0-9a-vA-V]{20}$/,pW=/^[A-Za-z0-9]{27}$/,dW=/^[a-zA-Z0-9_-]{21}$/,oW=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var tW=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,q4=(w)=>{if(!w)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${w}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var rW=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function sW(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var eW=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,aW=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,wQ=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bQ=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,$Q=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,P4=/^[A-Za-z0-9_-]*$/,WQ=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;var QQ=/^\+(?:[0-9]){6,14}[0-9]$/,XQ="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",GQ=new RegExp(`^${XQ}$`);function JQ(w){return typeof w.precision==="number"?w.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":w.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${w.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function YQ(w){return new RegExp(`^${JQ(w)}$`)}function HQ(w){let b=JQ({precision:w.precision}),$=["Z"];if(w.local)$.push("");if(w.offset)$.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let W=`${b}(?:${$.join("|")})`;return new RegExp(`^${XQ}T(?:${W})$`)}var zQ=(w)=>{let b=w?`[\\s\\S]{${w?.minimum??0},${w?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${b}$`)};var DQ=/^-?\d+$/,BQ=/^-?\d+(?:\.\d+)?/,AQ=/^(?:true|false)$/i,FQ=/^null$/i;var LQ=/^[^A-Z]*$/,UQ=/^[^a-z]*$/;var Fw=O("$ZodCheck",(w,b)=>{var $;w._zod??(w._zod={}),w._zod.def=b,($=w._zod).onattach??($.onattach=[])}),KQ={number:"number",bigint:"bigint",object:"date"},I4=O("$ZodCheckLessThan",(w,b)=>{Fw.init(w,b);let $=KQ[typeof b.value];w._zod.onattach.push((W)=>{let Q=W._zod.bag,X=(b.inclusive?Q.maximum:Q.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(b.value<X)if(b.inclusive)Q.maximum=b.value;else Q.exclusiveMaximum=b.value}),w._zod.check=(W)=>{if(b.inclusive?W.value<=b.value:W.value<b.value)return;W.issues.push({origin:$,code:"too_big",maximum:b.value,input:W.value,inclusive:b.inclusive,inst:w,continue:!b.abort})}}),N4=O("$ZodCheckGreaterThan",(w,b)=>{Fw.init(w,b);let $=KQ[typeof b.value];w._zod.onattach.push((W)=>{let Q=W._zod.bag,X=(b.inclusive?Q.minimum:Q.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(b.value>X)if(b.inclusive)Q.minimum=b.value;else Q.exclusiveMinimum=b.value}),w._zod.check=(W)=>{if(b.inclusive?W.value>=b.value:W.value>b.value)return;W.issues.push({origin:$,code:"too_small",minimum:b.value,input:W.value,inclusive:b.inclusive,inst:w,continue:!b.abort})}}),OQ=O("$ZodCheckMultipleOf",(w,b)=>{Fw.init(w,b),w._zod.onattach.push(($)=>{var W;(W=$._zod.bag).multipleOf??(W.multipleOf=b.value)}),w._zod.check=($)=>{if(typeof $.value!==typeof b.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof $.value==="bigint"?$.value%b.value===BigInt(0):K4($.value,b.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:b.value,input:$.value,inst:w,continue:!b.abort})}}),ZQ=O("$ZodCheckNumberFormat",(w,b)=>{Fw.init(w,b),b.format=b.format||"float64";let $=b.format?.includes("int"),W=$?"int":"number",[Q,X]=M4[b.format];w._zod.onattach.push((G)=>{let J=G._zod.bag;if(J.format=b.format,J.minimum=Q,J.maximum=X,$)J.pattern=DQ}),w._zod.check=(G)=>{let J=G.value;if($){if(!Number.isInteger(J)){G.issues.push({expected:W,format:b.format,code:"invalid_type",continue:!1,input:J,inst:w});return}if(!Number.isSafeInteger(J)){if(J>0)G.issues.push({input:J,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:w,origin:W,continue:!b.abort});else G.issues.push({input:J,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:w,origin:W,continue:!b.abort});return}}if(J<Q)G.issues.push({origin:"number",input:J,code:"too_small",minimum:Q,inclusive:!0,inst:w,continue:!b.abort});if(J>X)G.issues.push({origin:"number",input:J,code:"too_big",maximum:X,inst:w})}});var VQ=O("$ZodCheckMaxLength",(w,b)=>{var $;Fw.init(w,b),($=w._zod.def).when??($.when=(W)=>{let Q=W.value;return!P0(Q)&&Q.length!==void 0}),w._zod.onattach.push((W)=>{let Q=W._zod.bag.maximum??Number.POSITIVE_INFINITY;if(b.maximum<Q)W._zod.bag.maximum=b.maximum}),w._zod.check=(W)=>{let Q=W.value;if(Q.length<=b.maximum)return;let G=N0(Q);W.issues.push({origin:G,code:"too_big",maximum:b.maximum,inclusive:!0,input:Q,inst:w,continue:!b.abort})}}),MQ=O("$ZodCheckMinLength",(w,b)=>{var $;Fw.init(w,b),($=w._zod.def).when??($.when=(W)=>{let Q=W.value;return!P0(Q)&&Q.length!==void 0}),w._zod.onattach.push((W)=>{let Q=W._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(b.minimum>Q)W._zod.bag.minimum=b.minimum}),w._zod.check=(W)=>{let Q=W.value;if(Q.length>=b.minimum)return;let G=N0(Q);W.issues.push({origin:G,code:"too_small",minimum:b.minimum,inclusive:!0,input:Q,inst:w,continue:!b.abort})}}),jQ=O("$ZodCheckLengthEquals",(w,b)=>{var $;Fw.init(w,b),($=w._zod.def).when??($.when=(W)=>{let Q=W.value;return!P0(Q)&&Q.length!==void 0}),w._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.minimum=b.length,Q.maximum=b.length,Q.length=b.length}),w._zod.check=(W)=>{let Q=W.value,X=Q.length;if(X===b.length)return;let G=N0(Q),J=X>b.length;W.issues.push({origin:G,...J?{code:"too_big",maximum:b.length}:{code:"too_small",minimum:b.length},inclusive:!0,exact:!0,input:W.value,inst:w,continue:!b.abort})}}),S0=O("$ZodCheckStringFormat",(w,b)=>{var $,W;if(Fw.init(w,b),w._zod.onattach.push((Q)=>{let X=Q._zod.bag;if(X.format=b.format,b.pattern)X.patterns??(X.patterns=new Set),X.patterns.add(b.pattern)}),b.pattern)($=w._zod).check??($.check=(Q)=>{if(b.pattern.lastIndex=0,b.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:b.format,input:Q.value,...b.pattern?{pattern:b.pattern.toString()}:{},inst:w,continue:!b.abort})});else(W=w._zod).check??(W.check=()=>{})}),qQ=O("$ZodCheckRegex",(w,b)=>{S0.init(w,b),w._zod.check=($)=>{if(b.pattern.lastIndex=0,b.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:"regex",input:$.value,pattern:b.pattern.toString(),inst:w,continue:!b.abort})}}),PQ=O("$ZodCheckLowerCase",(w,b)=>{b.pattern??(b.pattern=LQ),S0.init(w,b)}),IQ=O("$ZodCheckUpperCase",(w,b)=>{b.pattern??(b.pattern=UQ),S0.init(w,b)}),NQ=O("$ZodCheckIncludes",(w,b)=>{Fw.init(w,b);let $=Q1(b.includes),W=new RegExp(typeof b.position==="number"?`^.{${b.position}}${$}`:$);b.pattern=W,w._zod.onattach.push((Q)=>{let X=Q._zod.bag;X.patterns??(X.patterns=new Set),X.patterns.add(W)}),w._zod.check=(Q)=>{if(Q.value.includes(b.includes,b.position))return;Q.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:b.includes,input:Q.value,inst:w,continue:!b.abort})}}),EQ=O("$ZodCheckStartsWith",(w,b)=>{Fw.init(w,b);let $=new RegExp(`^${Q1(b.prefix)}.*`);b.pattern??(b.pattern=$),w._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),w._zod.check=(W)=>{if(W.value.startsWith(b.prefix))return;W.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:b.prefix,input:W.value,inst:w,continue:!b.abort})}}),TQ=O("$ZodCheckEndsWith",(w,b)=>{Fw.init(w,b);let $=new RegExp(`.*${Q1(b.suffix)}$`);b.pattern??(b.pattern=$),w._zod.onattach.push((W)=>{let Q=W._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add($)}),w._zod.check=(W)=>{if(W.value.endsWith(b.suffix))return;W.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:b.suffix,input:W.value,inst:w,continue:!b.abort})}});var RQ=O("$ZodCheckOverwrite",(w,b)=>{Fw.init(w,b),w._zod.check=($)=>{$.value=b.tx($.value)}});class E4{constructor(w=[]){if(this.content=[],this.indent=0,this)this.args=w}indented(w){this.indent+=1,w(this),this.indent-=1}write(w){if(typeof w==="function"){w(this,{execution:"sync"}),w(this,{execution:"async"});return}let $=w.split(`
11
11
  `).filter((X)=>X),W=Math.min(...$.map((X)=>X.length-X.trimStart().length)),Q=$.map((X)=>X.slice(W)).map((X)=>" ".repeat(this.indent*2)+X);for(let X of Q)this.content.push(X)}compile(){let w=Function,b=this?.args,W=[...(this?.content??[""]).map((Q)=>` ${Q}`)];return new w(...b,W.join(`
12
- `))}}var SQ={major:4,minor:1,patch:12};var ww=O("$ZodType",(w,b)=>{var $;w??(w={}),w._zod.def=b,w._zod.bag=w._zod.bag||{},w._zod.version=SQ;let W=[...w._zod.def.checks??[]];if(w._zod.traits.has("$ZodCheck"))W.unshift(w);for(let Q of W)for(let X of Q._zod.onattach)X(w);if(W.length===0)($=w._zod).deferred??($.deferred=[]),w._zod.deferred?.push(()=>{w._zod.run=w._zod.parse});else{let Q=(G,J,Y)=>{let H=V1(G),z;for(let B of J){if(B._zod.def.when){if(!B._zod.def.when(G))continue}else if(H)continue;let A=G.issues.length,F=B._zod.check(G);if(F instanceof Promise&&Y?.async===!1)throw new W1;if(z||F instanceof Promise)z=(z??Promise.resolve()).then(async()=>{if(await F,G.issues.length===A)return;if(!H)H=V1(G,A)});else{if(G.issues.length===A)continue;if(!H)H=V1(G,A)}}if(z)return z.then(()=>{return G});return G},X=(G,J,Y)=>{if(V1(G))return G.aborted=!0,G;let H=Q(J,W,Y);if(H instanceof Promise){if(Y.async===!1)throw new W1;return H.then((z)=>w._zod.parse(z,Y))}return w._zod.parse(H,Y)};w._zod.run=(G,J)=>{if(J.skipChecks)return w._zod.parse(G,J);if(J.direction==="backward"){let H=w._zod.parse({value:G.value,issues:[]},{...J,skipChecks:!0});if(H instanceof Promise)return H.then((z)=>{return X(z,G,J)});return X(H,G,J)}let Y=w._zod.parse(G,J);if(Y instanceof Promise){if(J.async===!1)throw new W1;return Y.then((H)=>Q(H,W,J))}return Q(Y,W,J)}}w["~standard"]={validate:(Q)=>{try{let X=E0(w,Q);return X.success?{value:X.data}:{issues:X.error?.issues}}catch(X){return _b(w,Q).then((G)=>G.success?{value:G.data}:{issues:G.error?.issues})}},vendor:"zod",version:1}}),ub=O("$ZodString",(w,b)=>{ww.init(w,b),w._zod.pattern=[...w?._zod.bag?.patterns??[]].pop()??HQ(w._zod.bag),w._zod.parse=($,W)=>{if(b.coerce)try{$.value=String($.value)}catch(Q){}if(typeof $.value==="string")return $;return $.issues.push({expected:"string",code:"invalid_type",input:$.value,inst:w}),$}}),bw=O("$ZodStringFormat",(w,b)=>{R0.init(w,b),ub.init(w,b)}),fQ=O("$ZodGUID",(w,b)=>{b.pattern??(b.pattern=oW),bw.init(w,b)}),cQ=O("$ZodUUID",(w,b)=>{if(b.version){let W={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[b.version];if(W===void 0)throw Error(`Invalid UUID version: "${b.version}"`);b.pattern??(b.pattern=q4(W))}else b.pattern??(b.pattern=q4());bw.init(w,b)}),mQ=O("$ZodEmail",(w,b)=>{b.pattern??(b.pattern=tW),bw.init(w,b)}),lQ=O("$ZodURL",(w,b)=>{bw.init(w,b),w._zod.check=($)=>{try{let W=$.value.trim(),Q=new URL(W);if(b.hostname){if(b.hostname.lastIndex=0,!b.hostname.test(Q.hostname))$.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:$Q.source,input:$.value,inst:w,continue:!b.abort})}if(b.protocol){if(b.protocol.lastIndex=0,!b.protocol.test(Q.protocol.endsWith(":")?Q.protocol.slice(0,-1):Q.protocol))$.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:b.protocol.source,input:$.value,inst:w,continue:!b.abort})}if(b.normalize)$.value=Q.href;else $.value=W;return}catch(W){$.issues.push({code:"invalid_format",format:"url",input:$.value,inst:w,continue:!b.abort})}}}),gQ=O("$ZodEmoji",(w,b)=>{b.pattern??(b.pattern=rW()),bw.init(w,b)}),iQ=O("$ZodNanoID",(w,b)=>{b.pattern??(b.pattern=pW),bw.init(w,b)}),nQ=O("$ZodCUID",(w,b)=>{b.pattern??(b.pattern=mW),bw.init(w,b)}),pQ=O("$ZodCUID2",(w,b)=>{b.pattern??(b.pattern=lW),bw.init(w,b)}),dQ=O("$ZodULID",(w,b)=>{b.pattern??(b.pattern=gW),bw.init(w,b)}),oQ=O("$ZodXID",(w,b)=>{b.pattern??(b.pattern=iW),bw.init(w,b)}),tQ=O("$ZodKSUID",(w,b)=>{b.pattern??(b.pattern=nW),bw.init(w,b)}),rQ=O("$ZodISODateTime",(w,b)=>{b.pattern??(b.pattern=YQ(b)),bw.init(w,b)}),sQ=O("$ZodISODate",(w,b)=>{b.pattern??(b.pattern=XQ),bw.init(w,b)}),eQ=O("$ZodISOTime",(w,b)=>{b.pattern??(b.pattern=JQ(b)),bw.init(w,b)}),aQ=O("$ZodISODuration",(w,b)=>{b.pattern??(b.pattern=dW),bw.init(w,b)}),w8=O("$ZodIPv4",(w,b)=>{b.pattern??(b.pattern=sW),bw.init(w,b),w._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv4"})}),b8=O("$ZodIPv6",(w,b)=>{b.pattern??(b.pattern=eW),bw.init(w,b),w._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv6"}),w._zod.check=($)=>{try{new URL(`http://[${$.value}]`)}catch{$.issues.push({code:"invalid_format",format:"ipv6",input:$.value,inst:w,continue:!b.abort})}}}),$8=O("$ZodCIDRv4",(w,b)=>{b.pattern??(b.pattern=aW),bw.init(w,b)}),W8=O("$ZodCIDRv6",(w,b)=>{b.pattern??(b.pattern=wQ),bw.init(w,b),w._zod.check=($)=>{let W=$.value.split("/");try{if(W.length!==2)throw Error();let[Q,X]=W;if(!X)throw Error();let G=Number(X);if(`${G}`!==X)throw Error();if(G<0||G>128)throw Error();new URL(`http://[${Q}]`)}catch{$.issues.push({code:"invalid_format",format:"cidrv6",input:$.value,inst:w,continue:!b.abort})}}});function Q8(w){if(w==="")return!0;if(w.length%4!==0)return!1;try{return atob(w),!0}catch{return!1}}var X8=O("$ZodBase64",(w,b)=>{b.pattern??(b.pattern=bQ),bw.init(w,b),w._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),w._zod.check=($)=>{if(Q8($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:w,continue:!b.abort})}});function Tz(w){if(!P4.test(w))return!1;let b=w.replace(/[-_]/g,(W)=>W==="-"?"+":"/"),$=b.padEnd(Math.ceil(b.length/4)*4,"=");return Q8($)}var G8=O("$ZodBase64URL",(w,b)=>{b.pattern??(b.pattern=P4),bw.init(w,b),w._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),w._zod.check=($)=>{if(Tz($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:w,continue:!b.abort})}}),J8=O("$ZodE164",(w,b)=>{b.pattern??(b.pattern=WQ),bw.init(w,b)});function Rz(w,b=null){try{let $=w.split(".");if($.length!==3)return!1;let[W]=$;if(!W)return!1;let Q=JSON.parse(atob(W));if("typ"in Q&&Q?.typ!=="JWT")return!1;if(!Q.alg)return!1;if(b&&(!("alg"in Q)||Q.alg!==b))return!1;return!0}catch{return!1}}var Y8=O("$ZodJWT",(w,b)=>{bw.init(w,b),w._zod.check=($)=>{if(Rz($.value,b.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:w,continue:!b.abort})}});var R4=O("$ZodNumber",(w,b)=>{ww.init(w,b),w._zod.pattern=w._zod.bag.pattern??DQ,w._zod.parse=($,W)=>{if(b.coerce)try{$.value=Number($.value)}catch(G){}let Q=$.value;if(typeof Q==="number"&&!Number.isNaN(Q)&&Number.isFinite(Q))return $;let X=typeof Q==="number"?Number.isNaN(Q)?"NaN":!Number.isFinite(Q)?"Infinity":void 0:void 0;return $.issues.push({expected:"number",code:"invalid_type",input:Q,inst:w,...X?{received:X}:{}}),$}}),H8=O("$ZodNumber",(w,b)=>{OQ.init(w,b),R4.init(w,b)}),z8=O("$ZodBoolean",(w,b)=>{ww.init(w,b),w._zod.pattern=BQ,w._zod.parse=($,W)=>{if(b.coerce)try{$.value=Boolean($.value)}catch(X){}let Q=$.value;if(typeof Q==="boolean")return $;return $.issues.push({expected:"boolean",code:"invalid_type",input:Q,inst:w}),$}});var D8=O("$ZodNull",(w,b)=>{ww.init(w,b),w._zod.pattern=AQ,w._zod.values=new Set([null]),w._zod.parse=($,W)=>{let Q=$.value;if(Q===null)return $;return $.issues.push({expected:"null",code:"invalid_type",input:Q,inst:w}),$}});var B8=O("$ZodUnknown",(w,b)=>{ww.init(w,b),w._zod.parse=($)=>$}),A8=O("$ZodNever",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{return $.issues.push({expected:"never",code:"invalid_type",input:$.value,inst:w}),$}});function vQ(w,b,$){if(w.issues.length)b.issues.push(...X1($,w.issues));b.value[$]=w.value}var F8=O("$ZodArray",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{let Q=$.value;if(!Array.isArray(Q))return $.issues.push({expected:"array",code:"invalid_type",input:Q,inst:w}),$;$.value=Array(Q.length);let X=[];for(let G=0;G<Q.length;G++){let J=Q[G],Y=b.element._zod.run({value:J,issues:[]},W);if(Y instanceof Promise)X.push(Y.then((H)=>vQ(H,$,G)));else vQ(Y,$,G)}if(X.length)return Promise.all(X).then(()=>$);return $}});function yb(w,b,$,W){if(w.issues.length)b.issues.push(...X1($,w.issues));if(w.value===void 0){if($ in W)b.value[$]=void 0}else b.value[$]=w.value}function L8(w){let b=Object.keys(w.shape);for(let W of b)if(!w.shape?.[W]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${W}": expected a Zod schema`);let $=M4(w.shape);return{...w,keys:b,keySet:new Set(b),numKeys:b.length,optionalKeys:new Set($)}}function U8(w,b,$,W,Q,X){let G=[],J=Q.keySet,Y=Q.catchall._zod,H=Y.def.type;for(let z of Object.keys(b)){if(J.has(z))continue;if(H==="never"){G.push(z);continue}let B=Y.run({value:b[z],issues:[]},W);if(B instanceof Promise)w.push(B.then((A)=>yb(A,$,z,b)));else yb(B,$,z,b)}if(G.length)$.issues.push({code:"unrecognized_keys",keys:G,input:b,inst:X});if(!w.length)return $;return Promise.all(w).then(()=>{return $})}var Sz=O("$ZodObject",(w,b)=>{if(ww.init(w,b),!Object.getOwnPropertyDescriptor(b,"shape")?.get){let J=b.shape;Object.defineProperty(b,"shape",{get:()=>{let Y={...J};return Object.defineProperty(b,"shape",{value:Y}),Y}})}let W=n1(()=>L8(b));s(w._zod,"propValues",()=>{let J=b.shape,Y={};for(let H in J){let z=J[H]._zod;if(z.values){Y[H]??(Y[H]=new Set);for(let B of z.values)Y[H].add(B)}}return Y});let Q=_1,X=b.catchall,G;w._zod.parse=(J,Y)=>{G??(G=W.value);let H=J.value;if(!Q(H))return J.issues.push({expected:"object",code:"invalid_type",input:H,inst:w}),J;J.value={};let z=[],B=G.shape;for(let A of G.keys){let U=B[A]._zod.run({value:H[A],issues:[]},Y);if(U instanceof Promise)z.push(U.then((V)=>yb(V,J,A,H)));else yb(U,J,A,H)}if(!X)return z.length?Promise.all(z).then(()=>J):J;return U8(z,H,J,Y,W.value,w)}}),K8=O("$ZodObjectJIT",(w,b)=>{Sz.init(w,b);let $=w._zod.parse,W=n1(()=>L8(b)),Q=(A)=>{let F=new E4(["shape","payload","ctx"]),U=W.value,V=(S)=>{let m=Tb(S);return`shape[${m}]._zod.run({ value: input[${m}], issues: [] }, ctx)`};F.write("const input = payload.value;");let q=Object.create(null),P=0;for(let S of U.keys)q[S]=`key_${P++}`;F.write("const newResult = {};");for(let S of U.keys){let m=q[S],_=Tb(S);F.write(`const ${m} = ${V(S)};`),F.write(`
13
- if (${m}.issues.length) {
14
- payload.issues = payload.issues.concat(${m}.issues.map(iss => ({
12
+ `))}}var vQ={major:4,minor:1,patch:12};var ww=O("$ZodType",(w,b)=>{var $;w??(w={}),w._zod.def=b,w._zod.bag=w._zod.bag||{},w._zod.version=vQ;let W=[...w._zod.def.checks??[]];if(w._zod.traits.has("$ZodCheck"))W.unshift(w);for(let Q of W)for(let X of Q._zod.onattach)X(w);if(W.length===0)($=w._zod).deferred??($.deferred=[]),w._zod.deferred?.push(()=>{w._zod.run=w._zod.parse});else{let Q=(G,J,Y)=>{let H=j1(G),z;for(let B of J){if(B._zod.def.when){if(!B._zod.def.when(G))continue}else if(H)continue;let A=G.issues.length,F=B._zod.check(G);if(F instanceof Promise&&Y?.async===!1)throw new W1;if(z||F instanceof Promise)z=(z??Promise.resolve()).then(async()=>{if(await F,G.issues.length===A)return;if(!H)H=j1(G,A)});else{if(G.issues.length===A)continue;if(!H)H=j1(G,A)}}if(z)return z.then(()=>{return G});return G},X=(G,J,Y)=>{if(j1(G))return G.aborted=!0,G;let H=Q(J,W,Y);if(H instanceof Promise){if(Y.async===!1)throw new W1;return H.then((z)=>w._zod.parse(z,Y))}return w._zod.parse(H,Y)};w._zod.run=(G,J)=>{if(J.skipChecks)return w._zod.parse(G,J);if(J.direction==="backward"){let H=w._zod.parse({value:G.value,issues:[]},{...J,skipChecks:!0});if(H instanceof Promise)return H.then((z)=>{return X(z,G,J)});return X(H,G,J)}let Y=w._zod.parse(G,J);if(Y instanceof Promise){if(J.async===!1)throw new W1;return Y.then((H)=>Q(H,W,J))}return Q(Y,W,J)}}w["~standard"]={validate:(Q)=>{try{let X=T0(w,Q);return X.success?{value:X.data}:{issues:X.error?.issues}}catch(X){return xb(w,Q).then((G)=>G.success?{value:G.data}:{issues:G.error?.issues})}},vendor:"zod",version:1}}),ub=O("$ZodString",(w,b)=>{ww.init(w,b),w._zod.pattern=[...w?._zod.bag?.patterns??[]].pop()??zQ(w._zod.bag),w._zod.parse=($,W)=>{if(b.coerce)try{$.value=String($.value)}catch(Q){}if(typeof $.value==="string")return $;return $.issues.push({expected:"string",code:"invalid_type",input:$.value,inst:w}),$}}),bw=O("$ZodStringFormat",(w,b)=>{S0.init(w,b),ub.init(w,b)}),cQ=O("$ZodGUID",(w,b)=>{b.pattern??(b.pattern=tW),bw.init(w,b)}),mQ=O("$ZodUUID",(w,b)=>{if(b.version){let W={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[b.version];if(W===void 0)throw Error(`Invalid UUID version: "${b.version}"`);b.pattern??(b.pattern=q4(W))}else b.pattern??(b.pattern=q4());bw.init(w,b)}),lQ=O("$ZodEmail",(w,b)=>{b.pattern??(b.pattern=rW),bw.init(w,b)}),gQ=O("$ZodURL",(w,b)=>{bw.init(w,b),w._zod.check=($)=>{try{let W=$.value.trim(),Q=new URL(W);if(b.hostname){if(b.hostname.lastIndex=0,!b.hostname.test(Q.hostname))$.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:WQ.source,input:$.value,inst:w,continue:!b.abort})}if(b.protocol){if(b.protocol.lastIndex=0,!b.protocol.test(Q.protocol.endsWith(":")?Q.protocol.slice(0,-1):Q.protocol))$.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:b.protocol.source,input:$.value,inst:w,continue:!b.abort})}if(b.normalize)$.value=Q.href;else $.value=W;return}catch(W){$.issues.push({code:"invalid_format",format:"url",input:$.value,inst:w,continue:!b.abort})}}}),iQ=O("$ZodEmoji",(w,b)=>{b.pattern??(b.pattern=sW()),bw.init(w,b)}),nQ=O("$ZodNanoID",(w,b)=>{b.pattern??(b.pattern=dW),bw.init(w,b)}),pQ=O("$ZodCUID",(w,b)=>{b.pattern??(b.pattern=lW),bw.init(w,b)}),dQ=O("$ZodCUID2",(w,b)=>{b.pattern??(b.pattern=gW),bw.init(w,b)}),oQ=O("$ZodULID",(w,b)=>{b.pattern??(b.pattern=iW),bw.init(w,b)}),tQ=O("$ZodXID",(w,b)=>{b.pattern??(b.pattern=nW),bw.init(w,b)}),rQ=O("$ZodKSUID",(w,b)=>{b.pattern??(b.pattern=pW),bw.init(w,b)}),sQ=O("$ZodISODateTime",(w,b)=>{b.pattern??(b.pattern=HQ(b)),bw.init(w,b)}),eQ=O("$ZodISODate",(w,b)=>{b.pattern??(b.pattern=GQ),bw.init(w,b)}),aQ=O("$ZodISOTime",(w,b)=>{b.pattern??(b.pattern=YQ(b)),bw.init(w,b)}),w8=O("$ZodISODuration",(w,b)=>{b.pattern??(b.pattern=oW),bw.init(w,b)}),b8=O("$ZodIPv4",(w,b)=>{b.pattern??(b.pattern=eW),bw.init(w,b),w._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv4"})}),$8=O("$ZodIPv6",(w,b)=>{b.pattern??(b.pattern=aW),bw.init(w,b),w._zod.onattach.push(($)=>{let W=$._zod.bag;W.format="ipv6"}),w._zod.check=($)=>{try{new URL(`http://[${$.value}]`)}catch{$.issues.push({code:"invalid_format",format:"ipv6",input:$.value,inst:w,continue:!b.abort})}}}),W8=O("$ZodCIDRv4",(w,b)=>{b.pattern??(b.pattern=wQ),bw.init(w,b)}),Q8=O("$ZodCIDRv6",(w,b)=>{b.pattern??(b.pattern=bQ),bw.init(w,b),w._zod.check=($)=>{let W=$.value.split("/");try{if(W.length!==2)throw Error();let[Q,X]=W;if(!X)throw Error();let G=Number(X);if(`${G}`!==X)throw Error();if(G<0||G>128)throw Error();new URL(`http://[${Q}]`)}catch{$.issues.push({code:"invalid_format",format:"cidrv6",input:$.value,inst:w,continue:!b.abort})}}});function X8(w){if(w==="")return!0;if(w.length%4!==0)return!1;try{return atob(w),!0}catch{return!1}}var G8=O("$ZodBase64",(w,b)=>{b.pattern??(b.pattern=$Q),bw.init(w,b),w._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),w._zod.check=($)=>{if(X8($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:w,continue:!b.abort})}});function Rz(w){if(!P4.test(w))return!1;let b=w.replace(/[-_]/g,(W)=>W==="-"?"+":"/"),$=b.padEnd(Math.ceil(b.length/4)*4,"=");return X8($)}var J8=O("$ZodBase64URL",(w,b)=>{b.pattern??(b.pattern=P4),bw.init(w,b),w._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),w._zod.check=($)=>{if(Rz($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:w,continue:!b.abort})}}),Y8=O("$ZodE164",(w,b)=>{b.pattern??(b.pattern=QQ),bw.init(w,b)});function Sz(w,b=null){try{let $=w.split(".");if($.length!==3)return!1;let[W]=$;if(!W)return!1;let Q=JSON.parse(atob(W));if("typ"in Q&&Q?.typ!=="JWT")return!1;if(!Q.alg)return!1;if(b&&(!("alg"in Q)||Q.alg!==b))return!1;return!0}catch{return!1}}var H8=O("$ZodJWT",(w,b)=>{bw.init(w,b),w._zod.check=($)=>{if(Sz($.value,b.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:w,continue:!b.abort})}});var R4=O("$ZodNumber",(w,b)=>{ww.init(w,b),w._zod.pattern=w._zod.bag.pattern??BQ,w._zod.parse=($,W)=>{if(b.coerce)try{$.value=Number($.value)}catch(G){}let Q=$.value;if(typeof Q==="number"&&!Number.isNaN(Q)&&Number.isFinite(Q))return $;let X=typeof Q==="number"?Number.isNaN(Q)?"NaN":!Number.isFinite(Q)?"Infinity":void 0:void 0;return $.issues.push({expected:"number",code:"invalid_type",input:Q,inst:w,...X?{received:X}:{}}),$}}),z8=O("$ZodNumber",(w,b)=>{ZQ.init(w,b),R4.init(w,b)}),D8=O("$ZodBoolean",(w,b)=>{ww.init(w,b),w._zod.pattern=AQ,w._zod.parse=($,W)=>{if(b.coerce)try{$.value=Boolean($.value)}catch(X){}let Q=$.value;if(typeof Q==="boolean")return $;return $.issues.push({expected:"boolean",code:"invalid_type",input:Q,inst:w}),$}});var B8=O("$ZodNull",(w,b)=>{ww.init(w,b),w._zod.pattern=FQ,w._zod.values=new Set([null]),w._zod.parse=($,W)=>{let Q=$.value;if(Q===null)return $;return $.issues.push({expected:"null",code:"invalid_type",input:Q,inst:w}),$}});var A8=O("$ZodUnknown",(w,b)=>{ww.init(w,b),w._zod.parse=($)=>$}),F8=O("$ZodNever",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{return $.issues.push({expected:"never",code:"invalid_type",input:$.value,inst:w}),$}});function CQ(w,b,$){if(w.issues.length)b.issues.push(...X1($,w.issues));b.value[$]=w.value}var L8=O("$ZodArray",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{let Q=$.value;if(!Array.isArray(Q))return $.issues.push({expected:"array",code:"invalid_type",input:Q,inst:w}),$;$.value=Array(Q.length);let X=[];for(let G=0;G<Q.length;G++){let J=Q[G],Y=b.element._zod.run({value:J,issues:[]},W);if(Y instanceof Promise)X.push(Y.then((H)=>CQ(H,$,G)));else CQ(Y,$,G)}if(X.length)return Promise.all(X).then(()=>$);return $}});function fb(w,b,$,W){if(w.issues.length)b.issues.push(...X1($,w.issues));if(w.value===void 0){if($ in W)b.value[$]=void 0}else b.value[$]=w.value}function U8(w){let b=Object.keys(w.shape);for(let W of b)if(!w.shape?.[W]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${W}": expected a Zod schema`);let $=V4(w.shape);return{...w,keys:b,keySet:new Set(b),numKeys:b.length,optionalKeys:new Set($)}}function K8(w,b,$,W,Q,X){let G=[],J=Q.keySet,Y=Q.catchall._zod,H=Y.def.type;for(let z of Object.keys(b)){if(J.has(z))continue;if(H==="never"){G.push(z);continue}let B=Y.run({value:b[z],issues:[]},W);if(B instanceof Promise)w.push(B.then((A)=>fb(A,$,z,b)));else fb(B,$,z,b)}if(G.length)$.issues.push({code:"unrecognized_keys",keys:G,input:b,inst:X});if(!w.length)return $;return Promise.all(w).then(()=>{return $})}var vz=O("$ZodObject",(w,b)=>{if(ww.init(w,b),!Object.getOwnPropertyDescriptor(b,"shape")?.get){let J=b.shape;Object.defineProperty(b,"shape",{get:()=>{let Y={...J};return Object.defineProperty(b,"shape",{value:Y}),Y}})}let W=p1(()=>U8(b));s(w._zod,"propValues",()=>{let J=b.shape,Y={};for(let H in J){let z=J[H]._zod;if(z.values){Y[H]??(Y[H]=new Set);for(let B of z.values)Y[H].add(B)}}return Y});let Q=x1,X=b.catchall,G;w._zod.parse=(J,Y)=>{G??(G=W.value);let H=J.value;if(!Q(H))return J.issues.push({expected:"object",code:"invalid_type",input:H,inst:w}),J;J.value={};let z=[],B=G.shape;for(let A of G.keys){let U=B[A]._zod.run({value:H[A],issues:[]},Y);if(U instanceof Promise)z.push(U.then((M)=>fb(M,J,A,H)));else fb(U,J,A,H)}if(!X)return z.length?Promise.all(z).then(()=>J):J;return K8(z,H,J,Y,W.value,w)}}),O8=O("$ZodObjectJIT",(w,b)=>{vz.init(w,b);let $=w._zod.parse,W=p1(()=>U8(b)),Q=(A)=>{let F=new E4(["shape","payload","ctx"]),U=W.value,M=(S)=>{let l=Rb(S);return`shape[${l}]._zod.run({ value: input[${l}], issues: [] }, ctx)`};F.write("const input = payload.value;");let q=Object.create(null),P=0;for(let S of U.keys)q[S]=`key_${P++}`;F.write("const newResult = {};");for(let S of U.keys){let l=q[S],_=Rb(S);F.write(`const ${l} = ${M(S)};`),F.write(`
13
+ if (${l}.issues.length) {
14
+ payload.issues = payload.issues.concat(${l}.issues.map(iss => ({
15
15
  ...iss,
16
16
  path: iss.path ? [${_}, ...iss.path] : [${_}]
17
17
  })));
18
18
  }
19
19
 
20
20
 
21
- if (${m}.value === undefined) {
21
+ if (${l}.value === undefined) {
22
22
  if (${_} in input) {
23
23
  newResult[${_}] = undefined;
24
24
  }
25
25
  } else {
26
- newResult[${_}] = ${m}.value;
26
+ newResult[${_}] = ${l}.value;
27
27
  }
28
28
 
29
- `)}F.write("payload.value = newResult;"),F.write("return payload;");let k=F.compile();return(S,m)=>k(A,S,m)},X,G=_1,J=!Nb.jitless,H=J&&O4.value,z=b.catchall,B;w._zod.parse=(A,F)=>{B??(B=W.value);let U=A.value;if(!G(U))return A.issues.push({expected:"object",code:"invalid_type",input:U,inst:w}),A;if(J&&H&&F?.async===!1&&F.jitless!==!0){if(!X)X=Q(b.shape);if(A=X(A,F),!z)return A;return U8([],U,A,F,B,w)}return $(A,F)}});function CQ(w,b,$,W){for(let X of w)if(X.issues.length===0)return b.value=X.value,b;let Q=w.filter((X)=>!V1(X));if(Q.length===1)return b.value=Q[0].value,Q[0];return b.issues.push({code:"invalid_union",input:b.value,inst:$,errors:w.map((X)=>X.issues.map((G)=>cw(G,W,kw())))}),b}var S4=O("$ZodUnion",(w,b)=>{ww.init(w,b),s(w._zod,"optin",()=>b.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),s(w._zod,"optout",()=>b.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),s(w._zod,"values",()=>{if(b.options.every((Q)=>Q._zod.values))return new Set(b.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),s(w._zod,"pattern",()=>{if(b.options.every((Q)=>Q._zod.pattern)){let Q=b.options.map((X)=>X._zod.pattern);return new RegExp(`^(${Q.map((X)=>P0(X.source)).join("|")})$`)}return});let $=b.options.length===1,W=b.options[0]._zod.run;w._zod.parse=(Q,X)=>{if($)return W(Q,X);let G=!1,J=[];for(let Y of b.options){let H=Y._zod.run({value:Q.value,issues:[]},X);if(H instanceof Promise)J.push(H),G=!0;else{if(H.issues.length===0)return H;J.push(H)}}if(!G)return CQ(J,Q,w,X);return Promise.all(J).then((Y)=>{return CQ(Y,Q,w,X)})}}),O8=O("$ZodDiscriminatedUnion",(w,b)=>{S4.init(w,b);let $=w._zod.parse;s(w._zod,"propValues",()=>{let Q={};for(let X of b.options){let G=X._zod.propValues;if(!G||Object.keys(G).length===0)throw Error(`Invalid discriminated union option at index "${b.options.indexOf(X)}"`);for(let[J,Y]of Object.entries(G)){if(!Q[J])Q[J]=new Set;for(let H of Y)Q[J].add(H)}}return Q});let W=n1(()=>{let Q=b.options,X=new Map;for(let G of Q){let J=G._zod.propValues?.[b.discriminator];if(!J||J.size===0)throw Error(`Invalid discriminated union option at index "${b.options.indexOf(G)}"`);for(let Y of J){if(X.has(Y))throw Error(`Duplicate discriminator value "${String(Y)}"`);X.set(Y,G)}}return X});w._zod.parse=(Q,X)=>{let G=Q.value;if(!_1(G))return Q.issues.push({code:"invalid_type",expected:"object",input:G,inst:w}),Q;let J=W.value.get(G?.[b.discriminator]);if(J)return J._zod.run(Q,X);if(b.unionFallback)return $(Q,X);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:b.discriminator,input:G,path:[b.discriminator],inst:w}),Q}}),Z8=O("$ZodIntersection",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{let Q=$.value,X=b.left._zod.run({value:Q,issues:[]},W),G=b.right._zod.run({value:Q,issues:[]},W);if(X instanceof Promise||G instanceof Promise)return Promise.all([X,G]).then(([Y,H])=>{return kQ($,Y,H)});return kQ($,X,G)}});function T4(w,b){if(w===b)return{valid:!0,data:w};if(w instanceof Date&&b instanceof Date&&+w===+b)return{valid:!0,data:w};if(M1(w)&&M1(b)){let $=Object.keys(b),W=Object.keys(w).filter((X)=>$.indexOf(X)!==-1),Q={...w,...b};for(let X of W){let G=T4(w[X],b[X]);if(!G.valid)return{valid:!1,mergeErrorPath:[X,...G.mergeErrorPath]};Q[X]=G.data}return{valid:!0,data:Q}}if(Array.isArray(w)&&Array.isArray(b)){if(w.length!==b.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let W=0;W<w.length;W++){let Q=w[W],X=b[W],G=T4(Q,X);if(!G.valid)return{valid:!1,mergeErrorPath:[W,...G.mergeErrorPath]};$.push(G.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function kQ(w,b,$){if(b.issues.length)w.issues.push(...b.issues);if($.issues.length)w.issues.push(...$.issues);if(V1(w))return w;let W=T4(b.value,$.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return w.value=W.data,w}var M8=O("$ZodRecord",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{let Q=$.value;if(!M1(Q))return $.issues.push({expected:"record",code:"invalid_type",input:Q,inst:w}),$;let X=[];if(b.keyType._zod.values){let G=b.keyType._zod.values;$.value={};for(let Y of G)if(typeof Y==="string"||typeof Y==="number"||typeof Y==="symbol"){let H=b.valueType._zod.run({value:Q[Y],issues:[]},W);if(H instanceof Promise)X.push(H.then((z)=>{if(z.issues.length)$.issues.push(...X1(Y,z.issues));$.value[Y]=z.value}));else{if(H.issues.length)$.issues.push(...X1(Y,H.issues));$.value[Y]=H.value}}let J;for(let Y in Q)if(!G.has(Y))J=J??[],J.push(Y);if(J&&J.length>0)$.issues.push({code:"unrecognized_keys",input:Q,inst:w,keys:J})}else{$.value={};for(let G of Reflect.ownKeys(Q)){if(G==="__proto__")continue;let J=b.keyType._zod.run({value:G,issues:[]},W);if(J instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(J.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:J.issues.map((H)=>cw(H,W,kw())),input:G,path:[G],inst:w}),$.value[J.value]=J.value;continue}let Y=b.valueType._zod.run({value:Q[G],issues:[]},W);if(Y instanceof Promise)X.push(Y.then((H)=>{if(H.issues.length)$.issues.push(...X1(G,H.issues));$.value[J.value]=H.value}));else{if(Y.issues.length)$.issues.push(...X1(G,Y.issues));$.value[J.value]=Y.value}}}if(X.length)return Promise.all(X).then(()=>$);return $}});var V8=O("$ZodEnum",(w,b)=>{ww.init(w,b);let $=U4(b.entries),W=new Set($);w._zod.values=W,w._zod.pattern=new RegExp(`^(${$.filter((Q)=>Z4.has(typeof Q)).map((Q)=>typeof Q==="string"?Q1(Q):Q.toString()).join("|")})$`),w._zod.parse=(Q,X)=>{let G=Q.value;if(W.has(G))return Q;return Q.issues.push({code:"invalid_value",values:$,input:G,inst:w}),Q}}),j8=O("$ZodLiteral",(w,b)=>{if(ww.init(w,b),b.values.length===0)throw Error("Cannot create literal schema with no valid values");w._zod.values=new Set(b.values),w._zod.pattern=new RegExp(`^(${b.values.map(($)=>typeof $==="string"?Q1($):$?Q1($.toString()):String($)).join("|")})$`),w._zod.parse=($,W)=>{let Q=$.value;if(w._zod.values.has(Q))return $;return $.issues.push({code:"invalid_value",values:b.values,input:Q,inst:w}),$}});var q8=O("$ZodTransform",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{if(W.direction==="backward")throw new V0(w.constructor.name);let Q=b.transform($.value,$);if(W.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((G)=>{return $.value=G,$});if(Q instanceof Promise)throw new W1;return $.value=Q,$}});function _Q(w,b){if(w.issues.length&&b===void 0)return{issues:[],value:void 0};return w}var P8=O("$ZodOptional",(w,b)=>{ww.init(w,b),w._zod.optin="optional",w._zod.optout="optional",s(w._zod,"values",()=>{return b.innerType._zod.values?new Set([...b.innerType._zod.values,void 0]):void 0}),s(w._zod,"pattern",()=>{let $=b.innerType._zod.pattern;return $?new RegExp(`^(${P0($.source)})?$`):void 0}),w._zod.parse=($,W)=>{if(b.innerType._zod.optin==="optional"){let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>_Q(X,$.value));return _Q(Q,$.value)}if($.value===void 0)return $;return b.innerType._zod.run($,W)}}),I8=O("$ZodNullable",(w,b)=>{ww.init(w,b),s(w._zod,"optin",()=>b.innerType._zod.optin),s(w._zod,"optout",()=>b.innerType._zod.optout),s(w._zod,"pattern",()=>{let $=b.innerType._zod.pattern;return $?new RegExp(`^(${P0($.source)}|null)$`):void 0}),s(w._zod,"values",()=>{return b.innerType._zod.values?new Set([...b.innerType._zod.values,null]):void 0}),w._zod.parse=($,W)=>{if($.value===null)return $;return b.innerType._zod.run($,W)}}),N8=O("$ZodDefault",(w,b)=>{ww.init(w,b),w._zod.optin="optional",s(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,W)=>{if(W.direction==="backward")return b.innerType._zod.run($,W);if($.value===void 0)return $.value=b.defaultValue,$;let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>xQ(X,b));return xQ(Q,b)}});function xQ(w,b){if(w.value===void 0)w.value=b.defaultValue;return w}var E8=O("$ZodPrefault",(w,b)=>{ww.init(w,b),w._zod.optin="optional",s(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,W)=>{if(W.direction==="backward")return b.innerType._zod.run($,W);if($.value===void 0)$.value=b.defaultValue;return b.innerType._zod.run($,W)}}),T8=O("$ZodNonOptional",(w,b)=>{ww.init(w,b),s(w._zod,"values",()=>{let $=b.innerType._zod.values;return $?new Set([...$].filter((W)=>W!==void 0)):void 0}),w._zod.parse=($,W)=>{let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>hQ(X,w));return hQ(Q,w)}});function hQ(w,b){if(!w.issues.length&&w.value===void 0)w.issues.push({code:"invalid_type",expected:"nonoptional",input:w.value,inst:b});return w}var R8=O("$ZodCatch",(w,b)=>{ww.init(w,b),s(w._zod,"optin",()=>b.innerType._zod.optin),s(w._zod,"optout",()=>b.innerType._zod.optout),s(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,W)=>{if(W.direction==="backward")return b.innerType._zod.run($,W);let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>{if($.value=X.value,X.issues.length)$.value=b.catchValue({...$,error:{issues:X.issues.map((G)=>cw(G,W,kw()))},input:$.value}),$.issues=[];return $});if($.value=Q.value,Q.issues.length)$.value=b.catchValue({...$,error:{issues:Q.issues.map((X)=>cw(X,W,kw()))},input:$.value}),$.issues=[];return $}});var S8=O("$ZodPipe",(w,b)=>{ww.init(w,b),s(w._zod,"values",()=>b.in._zod.values),s(w._zod,"optin",()=>b.in._zod.optin),s(w._zod,"optout",()=>b.out._zod.optout),s(w._zod,"propValues",()=>b.in._zod.propValues),w._zod.parse=($,W)=>{if(W.direction==="backward"){let X=b.out._zod.run($,W);if(X instanceof Promise)return X.then((G)=>hb(G,b.in,W));return hb(X,b.in,W)}let Q=b.in._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>hb(X,b.out,W));return hb(Q,b.out,W)}});function hb(w,b,$){if(w.issues.length)return w.aborted=!0,w;return b._zod.run({value:w.value,issues:w.issues},$)}var v8=O("$ZodReadonly",(w,b)=>{ww.init(w,b),s(w._zod,"propValues",()=>b.innerType._zod.propValues),s(w._zod,"values",()=>b.innerType._zod.values),s(w._zod,"optin",()=>b.innerType._zod.optin),s(w._zod,"optout",()=>b.innerType._zod.optout),w._zod.parse=($,W)=>{if(W.direction==="backward")return b.innerType._zod.run($,W);let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then(yQ);return yQ(Q)}});function yQ(w){return w.value=Object.freeze(w.value),w}var C8=O("$ZodCustom",(w,b)=>{Fw.init(w,b),ww.init(w,b),w._zod.parse=($,W)=>{return $},w._zod.check=($)=>{let W=$.value,Q=b.fn(W);if(Q instanceof Promise)return Q.then((X)=>uQ(X,$,W,w));uQ(Q,$,W,w);return}});function uQ(w,b,$,W){if(!w){let Q={code:"custom",input:$,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)Q.params=W._zod.def.params;b.issues.push(p1(Q))}}var vz=(w)=>{let b=typeof w;switch(b){case"number":return Number.isNaN(w)?"NaN":"number";case"object":{if(Array.isArray(w))return"array";if(w===null)return"null";if(Object.getPrototypeOf(w)!==Object.prototype&&w.constructor)return w.constructor.name}}return b},Cz=()=>{let w={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function b(W){return w[W]??null}let $={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${vz(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${Sb(W.values[0])}`;return`Invalid option: expected one of ${Eb(W.values,"|")}`;case"too_big":{let Q=W.inclusive?"<=":"<",X=b(W.origin);if(X)return`Too big: expected ${W.origin??"value"} to have ${Q}${W.maximum.toString()} ${X.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${Q}${W.maximum.toString()}`}case"too_small":{let Q=W.inclusive?">=":">",X=b(W.origin);if(X)return`Too small: expected ${W.origin} to have ${Q}${W.minimum.toString()} ${X.unit}`;return`Too small: expected ${W.origin} to be ${Q}${W.minimum.toString()}`}case"invalid_format":{let Q=W;if(Q.format==="starts_with")return`Invalid string: must start with "${Q.prefix}"`;if(Q.format==="ends_with")return`Invalid string: must end with "${Q.suffix}"`;if(Q.format==="includes")return`Invalid string: must include "${Q.includes}"`;if(Q.format==="regex")return`Invalid string: must match pattern ${Q.pattern}`;return`Invalid ${$[Q.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${Eb(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function v4(){return{localeError:Cz()}}var $q=Symbol("ZodOutput"),Wq=Symbol("ZodInput");class k8{constructor(){this._map=new WeakMap,this._idmap=new Map}add(w,...b){let $=b[0];if(this._map.set(w,$),$&&typeof $==="object"&&"id"in $){if(this._idmap.has($.id))throw Error(`ID ${$.id} already exists in the registry`);this._idmap.set($.id,w)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(w){let b=this._map.get(w);if(b&&typeof b==="object"&&"id"in b)this._idmap.delete(b.id);return this._map.delete(w),this}get(w){let b=w._zod.parent;if(b){let $={...this.get(b)??{}};delete $.id;let W={...$,...this._map.get(w)};return Object.keys(W).length?W:void 0}return this._map.get(w)}has(w){return this._map.has(w)}}function kz(){return new k8}var S0=kz();function _8(w,b){return new w({type:"string",...v(b)})}function x8(w,b){return new w({type:"string",format:"email",check:"string_format",abort:!1,...v(b)})}function C4(w,b){return new w({type:"string",format:"guid",check:"string_format",abort:!1,...v(b)})}function h8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,...v(b)})}function y8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(b)})}function u8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(b)})}function f8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(b)})}function c8(w,b){return new w({type:"string",format:"url",check:"string_format",abort:!1,...v(b)})}function m8(w,b){return new w({type:"string",format:"emoji",check:"string_format",abort:!1,...v(b)})}function l8(w,b){return new w({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(b)})}function g8(w,b){return new w({type:"string",format:"cuid",check:"string_format",abort:!1,...v(b)})}function i8(w,b){return new w({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(b)})}function n8(w,b){return new w({type:"string",format:"ulid",check:"string_format",abort:!1,...v(b)})}function p8(w,b){return new w({type:"string",format:"xid",check:"string_format",abort:!1,...v(b)})}function d8(w,b){return new w({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(b)})}function o8(w,b){return new w({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(b)})}function t8(w,b){return new w({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(b)})}function r8(w,b){return new w({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(b)})}function s8(w,b){return new w({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(b)})}function e8(w,b){return new w({type:"string",format:"base64",check:"string_format",abort:!1,...v(b)})}function a8(w,b){return new w({type:"string",format:"base64url",check:"string_format",abort:!1,...v(b)})}function wX(w,b){return new w({type:"string",format:"e164",check:"string_format",abort:!1,...v(b)})}function bX(w,b){return new w({type:"string",format:"jwt",check:"string_format",abort:!1,...v(b)})}function $X(w,b){return new w({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(b)})}function WX(w,b){return new w({type:"string",format:"date",check:"string_format",...v(b)})}function QX(w,b){return new w({type:"string",format:"time",check:"string_format",precision:null,...v(b)})}function XX(w,b){return new w({type:"string",format:"duration",check:"string_format",...v(b)})}function GX(w,b){return new w({type:"number",checks:[],...v(b)})}function JX(w,b){return new w({type:"number",check:"number_format",abort:!1,format:"safeint",...v(b)})}function YX(w,b){return new w({type:"boolean",...v(b)})}function HX(w,b){return new w({type:"null",...v(b)})}function zX(w){return new w({type:"unknown"})}function DX(w,b){return new w({type:"never",...v(b)})}function fb(w,b){return new I4({check:"less_than",...v(b),value:w,inclusive:!1})}function v0(w,b){return new I4({check:"less_than",...v(b),value:w,inclusive:!0})}function cb(w,b){return new N4({check:"greater_than",...v(b),value:w,inclusive:!1})}function C0(w,b){return new N4({check:"greater_than",...v(b),value:w,inclusive:!0})}function mb(w,b){return new KQ({check:"multiple_of",...v(b),value:w})}function lb(w,b){return new ZQ({check:"max_length",...v(b),maximum:w})}function d1(w,b){return new MQ({check:"min_length",...v(b),minimum:w})}function gb(w,b){return new VQ({check:"length_equals",...v(b),length:w})}function k4(w,b){return new jQ({check:"string_format",format:"regex",...v(b),pattern:w})}function _4(w){return new qQ({check:"string_format",format:"lowercase",...v(w)})}function x4(w){return new PQ({check:"string_format",format:"uppercase",...v(w)})}function h4(w,b){return new IQ({check:"string_format",format:"includes",...v(b),includes:w})}function y4(w,b){return new NQ({check:"string_format",format:"starts_with",...v(b),prefix:w})}function u4(w,b){return new EQ({check:"string_format",format:"ends_with",...v(b),suffix:w})}function x1(w){return new TQ({check:"overwrite",tx:w})}function f4(w){return x1((b)=>b.normalize(w))}function c4(){return x1((w)=>w.trim())}function m4(){return x1((w)=>w.toLowerCase())}function l4(){return x1((w)=>w.toUpperCase())}function BX(w,b,$){return new w({type:"array",element:b,...v($)})}function AX(w,b,$){let W=v($);return W.abort??(W.abort=!0),new w({type:"custom",check:"custom",fn:b,...W})}function FX(w,b,$){return new w({type:"custom",check:"custom",fn:b,...v($)})}function LX(w){let b=_z(($)=>{return $.addIssue=(W)=>{if(typeof W==="string")$.issues.push(p1(W,$.value,b._zod.def));else{let Q=W;if(Q.fatal)Q.continue=!1;Q.code??(Q.code="custom"),Q.input??(Q.input=$.value),Q.inst??(Q.inst=b),Q.continue??(Q.continue=!b._zod.def.abort),$.issues.push(p1(Q))}},w($.value,$)});return b}function _z(w,b){let $=new Fw({check:"custom",...v(b)});return $._zod.check=w,$}function o1(w){return!!w._zod}function j1(w,b){if(o1(w))return E0(w,b);return w.safeParse(b)}function ib(w){if(!w)return;let b;if(o1(w))b=w._zod?.def?.shape;else b=w.shape;if(!b)return;if(typeof b==="function")try{return b()}catch{return}return b}function UX(w){if(o1(w)){let X=w._zod?.def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}}let $=w._def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}let W=w.value;if(W!==void 0)return W;return}var _0={};BW(_0,{time:()=>n4,duration:()=>p4,datetime:()=>g4,date:()=>i4,ZodISOTime:()=>ZX,ZodISODuration:()=>MX,ZodISODateTime:()=>KX,ZodISODate:()=>OX});var KX=O("ZodISODateTime",(w,b)=>{rQ.init(w,b),Ww.init(w,b)});function g4(w){return $X(KX,w)}var OX=O("ZodISODate",(w,b)=>{sQ.init(w,b),Ww.init(w,b)});function i4(w){return WX(OX,w)}var ZX=O("ZodISOTime",(w,b)=>{eQ.init(w,b),Ww.init(w,b)});function n4(w){return QX(ZX,w)}var MX=O("ZodISODuration",(w,b)=>{aQ.init(w,b),Ww.init(w,b)});function p4(w){return XX(MX,w)}var VX=(w,b)=>{vb.init(w,b),w.name="ZodError",Object.defineProperties(w,{format:{value:($)=>CW(w,$)},flatten:{value:($)=>vW(w,$)},addIssue:{value:($)=>{w.issues.push($),w.message=JSON.stringify(w.issues,i1,2)}},addIssues:{value:($)=>{w.issues.push(...$),w.message=JSON.stringify(w.issues,i1,2)}},isEmpty:{get(){return w.issues.length===0}}})},lq=O("ZodError",VX),Sw=O("ZodError",VX,{Parent:Error});var jX=Cb(Sw),qX=kb(Sw),PX=N0(Sw),IX=T0(Sw),NX=kW(Sw),EX=_W(Sw),TX=xW(Sw),RX=hW(Sw),SX=yW(Sw),vX=uW(Sw),CX=fW(Sw),kX=cW(Sw);var Jw=O("ZodType",(w,b)=>{return ww.init(w,b),w.def=b,w.type=b.type,Object.defineProperty(w,"_def",{value:b}),w.check=(...$)=>{return w.clone(d.mergeDefs(b,{checks:[...b.checks??[],...$.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},w.clone=($,W)=>fw(w,$,W),w.brand=()=>w,w.register=($,W)=>{return $.add(w,W),w},w.parse=($,W)=>jX(w,$,W,{callee:w.parse}),w.safeParse=($,W)=>PX(w,$,W),w.parseAsync=async($,W)=>qX(w,$,W,{callee:w.parseAsync}),w.safeParseAsync=async($,W)=>IX(w,$,W),w.spa=w.safeParseAsync,w.encode=($,W)=>NX(w,$,W),w.decode=($,W)=>EX(w,$,W),w.encodeAsync=async($,W)=>TX(w,$,W),w.decodeAsync=async($,W)=>RX(w,$,W),w.safeEncode=($,W)=>SX(w,$,W),w.safeDecode=($,W)=>vX(w,$,W),w.safeEncodeAsync=async($,W)=>CX(w,$,W),w.safeDecodeAsync=async($,W)=>kX(w,$,W),w.refine=($,W)=>w.check(SD($,W)),w.superRefine=($)=>w.check(vD($)),w.overwrite=($)=>w.check(x1($)),w.optional=()=>Gw(w),w.nullable=()=>hX(w),w.nullish=()=>Gw(hX(w)),w.nonoptional=($)=>PD(w,$),w.array=()=>l(w),w.or=($)=>a([w,$]),w.and=($)=>pb(w,$),w.transform=($)=>o4(w,mX($)),w.default=($)=>VD(w,$),w.prefault=($)=>qD(w,$),w.catch=($)=>ND(w,$),w.pipe=($)=>o4(w,$),w.readonly=()=>RD(w),w.describe=($)=>{let W=w.clone();return S0.add(W,{description:$}),W},Object.defineProperty(w,"description",{get(){return S0.get(w)?.description},configurable:!0}),w.meta=(...$)=>{if($.length===0)return S0.get(w);let W=w.clone();return S0.add(W,$[0]),W},w.isOptional=()=>w.safeParse(void 0).success,w.isNullable=()=>w.safeParse(null).success,w}),yX=O("_ZodString",(w,b)=>{ub.init(w,b),Jw.init(w,b);let $=w._zod.bag;w.format=$.format??null,w.minLength=$.minimum??null,w.maxLength=$.maximum??null,w.regex=(...W)=>w.check(k4(...W)),w.includes=(...W)=>w.check(h4(...W)),w.startsWith=(...W)=>w.check(y4(...W)),w.endsWith=(...W)=>w.check(u4(...W)),w.min=(...W)=>w.check(d1(...W)),w.max=(...W)=>w.check(lb(...W)),w.length=(...W)=>w.check(gb(...W)),w.nonempty=(...W)=>w.check(d1(1,...W)),w.lowercase=(W)=>w.check(_4(W)),w.uppercase=(W)=>w.check(x4(W)),w.trim=()=>w.check(c4()),w.normalize=(...W)=>w.check(f4(...W)),w.toLowerCase=()=>w.check(m4()),w.toUpperCase=()=>w.check(l4())}),gz=O("ZodString",(w,b)=>{ub.init(w,b),yX.init(w,b),w.email=($)=>w.check(x8(iz,$)),w.url=($)=>w.check(c8(nz,$)),w.jwt=($)=>w.check(bX(GD,$)),w.emoji=($)=>w.check(m8(pz,$)),w.guid=($)=>w.check(C4(_X,$)),w.uuid=($)=>w.check(h8(nb,$)),w.uuidv4=($)=>w.check(y8(nb,$)),w.uuidv6=($)=>w.check(u8(nb,$)),w.uuidv7=($)=>w.check(f8(nb,$)),w.nanoid=($)=>w.check(l8(dz,$)),w.guid=($)=>w.check(C4(_X,$)),w.cuid=($)=>w.check(g8(oz,$)),w.cuid2=($)=>w.check(i8(tz,$)),w.ulid=($)=>w.check(n8(rz,$)),w.base64=($)=>w.check(e8(WD,$)),w.base64url=($)=>w.check(a8(QD,$)),w.xid=($)=>w.check(p8(sz,$)),w.ksuid=($)=>w.check(d8(ez,$)),w.ipv4=($)=>w.check(o8(az,$)),w.ipv6=($)=>w.check(t8(wD,$)),w.cidrv4=($)=>w.check(r8(bD,$)),w.cidrv6=($)=>w.check(s8($D,$)),w.e164=($)=>w.check(wX(XD,$)),w.datetime=($)=>w.check(g4($)),w.date=($)=>w.check(i4($)),w.time=($)=>w.check(n4($)),w.duration=($)=>w.check(p4($))});function K(w){return _8(gz,w)}var Ww=O("ZodStringFormat",(w,b)=>{bw.init(w,b),yX.init(w,b)}),iz=O("ZodEmail",(w,b)=>{mQ.init(w,b),Ww.init(w,b)});var _X=O("ZodGUID",(w,b)=>{fQ.init(w,b),Ww.init(w,b)});var nb=O("ZodUUID",(w,b)=>{cQ.init(w,b),Ww.init(w,b)});var nz=O("ZodURL",(w,b)=>{lQ.init(w,b),Ww.init(w,b)});var pz=O("ZodEmoji",(w,b)=>{gQ.init(w,b),Ww.init(w,b)});var dz=O("ZodNanoID",(w,b)=>{iQ.init(w,b),Ww.init(w,b)});var oz=O("ZodCUID",(w,b)=>{nQ.init(w,b),Ww.init(w,b)});var tz=O("ZodCUID2",(w,b)=>{pQ.init(w,b),Ww.init(w,b)});var rz=O("ZodULID",(w,b)=>{dQ.init(w,b),Ww.init(w,b)});var sz=O("ZodXID",(w,b)=>{oQ.init(w,b),Ww.init(w,b)});var ez=O("ZodKSUID",(w,b)=>{tQ.init(w,b),Ww.init(w,b)});var az=O("ZodIPv4",(w,b)=>{w8.init(w,b),Ww.init(w,b)});var wD=O("ZodIPv6",(w,b)=>{b8.init(w,b),Ww.init(w,b)});var bD=O("ZodCIDRv4",(w,b)=>{$8.init(w,b),Ww.init(w,b)});var $D=O("ZodCIDRv6",(w,b)=>{W8.init(w,b),Ww.init(w,b)});var WD=O("ZodBase64",(w,b)=>{X8.init(w,b),Ww.init(w,b)});var QD=O("ZodBase64URL",(w,b)=>{G8.init(w,b),Ww.init(w,b)});var XD=O("ZodE164",(w,b)=>{J8.init(w,b),Ww.init(w,b)});var GD=O("ZodJWT",(w,b)=>{Y8.init(w,b),Ww.init(w,b)});var uX=O("ZodNumber",(w,b)=>{R4.init(w,b),Jw.init(w,b),w.gt=(W,Q)=>w.check(cb(W,Q)),w.gte=(W,Q)=>w.check(C0(W,Q)),w.min=(W,Q)=>w.check(C0(W,Q)),w.lt=(W,Q)=>w.check(fb(W,Q)),w.lte=(W,Q)=>w.check(v0(W,Q)),w.max=(W,Q)=>w.check(v0(W,Q)),w.int=(W)=>w.check(xX(W)),w.safe=(W)=>w.check(xX(W)),w.positive=(W)=>w.check(cb(0,W)),w.nonnegative=(W)=>w.check(C0(0,W)),w.negative=(W)=>w.check(fb(0,W)),w.nonpositive=(W)=>w.check(v0(0,W)),w.multipleOf=(W,Q)=>w.check(mb(W,Q)),w.step=(W,Q)=>w.check(mb(W,Q)),w.finite=()=>w;let $=w._zod.bag;w.minValue=Math.max($.minimum??Number.NEGATIVE_INFINITY,$.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,w.maxValue=Math.min($.maximum??Number.POSITIVE_INFINITY,$.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,w.isInt=($.format??"").includes("int")||Number.isSafeInteger($.multipleOf??0.5),w.isFinite=!0,w.format=$.format??null});function r(w){return GX(uX,w)}var JD=O("ZodNumberFormat",(w,b)=>{H8.init(w,b),uX.init(w,b)});function xX(w){return JX(JD,w)}var YD=O("ZodBoolean",(w,b)=>{z8.init(w,b),Jw.init(w,b)});function Aw(w){return YX(YD,w)}var HD=O("ZodNull",(w,b)=>{D8.init(w,b),Jw.init(w,b)});function t4(w){return HX(HD,w)}var zD=O("ZodUnknown",(w,b)=>{B8.init(w,b),Jw.init(w,b)});function Qw(){return zX(zD)}var DD=O("ZodNever",(w,b)=>{A8.init(w,b),Jw.init(w,b)});function BD(w){return DX(DD,w)}var AD=O("ZodArray",(w,b)=>{F8.init(w,b),Jw.init(w,b),w.element=b.element,w.min=($,W)=>w.check(d1($,W)),w.nonempty=($)=>w.check(d1(1,$)),w.max=($,W)=>w.check(lb($,W)),w.length=($,W)=>w.check(gb($,W)),w.unwrap=()=>w.element});function l(w,b){return BX(AD,w,b)}var fX=O("ZodObject",(w,b)=>{K8.init(w,b),Jw.init(w,b),d.defineLazy(w,"shape",()=>{return b.shape}),w.keyof=()=>Pw(Object.keys(w._zod.def.shape)),w.catchall=($)=>w.clone({...w._zod.def,catchall:$}),w.passthrough=()=>w.clone({...w._zod.def,catchall:Qw()}),w.loose=()=>w.clone({...w._zod.def,catchall:Qw()}),w.strict=()=>w.clone({...w._zod.def,catchall:BD()}),w.strip=()=>w.clone({...w._zod.def,catchall:void 0}),w.extend=($)=>{return d.extend(w,$)},w.safeExtend=($)=>{return d.safeExtend(w,$)},w.merge=($)=>d.merge(w,$),w.pick=($)=>d.pick(w,$),w.omit=($)=>d.omit(w,$),w.partial=(...$)=>d.partial(lX,w,$[0]),w.required=(...$)=>d.required(gX,w,$[0])});function N(w,b){let $={type:"object",shape:w??{},...d.normalizeParams(b)};return new fX($)}function Vw(w,b){return new fX({type:"object",shape:w,catchall:Qw(),...d.normalizeParams(b)})}var cX=O("ZodUnion",(w,b)=>{S4.init(w,b),Jw.init(w,b),w.options=b.options});function a(w,b){return new cX({type:"union",options:w,...d.normalizeParams(b)})}var FD=O("ZodDiscriminatedUnion",(w,b)=>{cX.init(w,b),O8.init(w,b)});function r4(w,b,$){return new FD({type:"union",options:b,discriminator:w,...d.normalizeParams($)})}var LD=O("ZodIntersection",(w,b)=>{Z8.init(w,b),Jw.init(w,b)});function pb(w,b){return new LD({type:"intersection",left:w,right:b})}var UD=O("ZodRecord",(w,b)=>{M8.init(w,b),Jw.init(w,b),w.keyType=b.keyType,w.valueType=b.valueType});function Xw(w,b,$){return new UD({type:"record",keyType:w,valueType:b,...d.normalizeParams($)})}var d4=O("ZodEnum",(w,b)=>{V8.init(w,b),Jw.init(w,b),w.enum=b.entries,w.options=Object.values(b.entries);let $=new Set(Object.keys(b.entries));w.extract=(W,Q)=>{let X={};for(let G of W)if($.has(G))X[G]=b.entries[G];else throw Error(`Key ${G} not found in enum`);return new d4({...b,checks:[],...d.normalizeParams(Q),entries:X})},w.exclude=(W,Q)=>{let X={...b.entries};for(let G of W)if($.has(G))delete X[G];else throw Error(`Key ${G} not found in enum`);return new d4({...b,checks:[],...d.normalizeParams(Q),entries:X})}});function Pw(w,b){let $=Array.isArray(w)?Object.fromEntries(w.map((W)=>[W,W])):w;return new d4({type:"enum",entries:$,...d.normalizeParams(b)})}var KD=O("ZodLiteral",(w,b)=>{j8.init(w,b),Jw.init(w,b),w.values=new Set(b.values),Object.defineProperty(w,"value",{get(){if(b.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return b.values[0]}})});function T(w,b){return new KD({type:"literal",values:Array.isArray(w)?w:[w],...d.normalizeParams(b)})}var OD=O("ZodTransform",(w,b)=>{q8.init(w,b),Jw.init(w,b),w._zod.parse=($,W)=>{if(W.direction==="backward")throw new V0(w.constructor.name);$.addIssue=(X)=>{if(typeof X==="string")$.issues.push(d.issue(X,$.value,b));else{let G=X;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=$.value),G.inst??(G.inst=w),$.issues.push(d.issue(G))}};let Q=b.transform($.value,$);if(Q instanceof Promise)return Q.then((X)=>{return $.value=X,$});return $.value=Q,$}});function mX(w){return new OD({type:"transform",transform:w})}var lX=O("ZodOptional",(w,b)=>{P8.init(w,b),Jw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function Gw(w){return new lX({type:"optional",innerType:w})}var ZD=O("ZodNullable",(w,b)=>{I8.init(w,b),Jw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function hX(w){return new ZD({type:"nullable",innerType:w})}var MD=O("ZodDefault",(w,b)=>{N8.init(w,b),Jw.init(w,b),w.unwrap=()=>w._zod.def.innerType,w.removeDefault=w.unwrap});function VD(w,b){return new MD({type:"default",innerType:w,get defaultValue(){return typeof b==="function"?b():d.shallowClone(b)}})}var jD=O("ZodPrefault",(w,b)=>{E8.init(w,b),Jw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function qD(w,b){return new jD({type:"prefault",innerType:w,get defaultValue(){return typeof b==="function"?b():d.shallowClone(b)}})}var gX=O("ZodNonOptional",(w,b)=>{T8.init(w,b),Jw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function PD(w,b){return new gX({type:"nonoptional",innerType:w,...d.normalizeParams(b)})}var ID=O("ZodCatch",(w,b)=>{R8.init(w,b),Jw.init(w,b),w.unwrap=()=>w._zod.def.innerType,w.removeCatch=w.unwrap});function ND(w,b){return new ID({type:"catch",innerType:w,catchValue:typeof b==="function"?b:()=>b})}var ED=O("ZodPipe",(w,b)=>{S8.init(w,b),Jw.init(w,b),w.in=b.in,w.out=b.out});function o4(w,b){return new ED({type:"pipe",in:w,out:b})}var TD=O("ZodReadonly",(w,b)=>{v8.init(w,b),Jw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function RD(w){return new TD({type:"readonly",innerType:w})}var iX=O("ZodCustom",(w,b)=>{C8.init(w,b),Jw.init(w,b)});function nX(w,b){return AX(iX,w??(()=>!0),b)}function SD(w,b={}){return FX(iX,w,b)}function vD(w){return LX(w)}function s4(w,b){return o4(mX(w),b)}kw(v4());var e4="2025-11-25";var pX=[e4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],q1="io.modelcontextprotocol/related-task",ob="2.0",Lw=nX((w)=>w!==null&&(typeof w==="object"||typeof w==="function")),dX=a([K(),r().int()]),oX=K(),yP=Vw({ttl:a([r(),t4()]).optional(),pollInterval:r().optional()}),CD=N({ttl:r().optional()}),kD=N({taskId:K()}),a4=Vw({progressToken:dX.optional(),[q1]:kD.optional()}),vw=N({_meta:a4.optional()}),x0=vw.extend({task:CD.optional()}),tX=(w)=>x0.safeParse(w).success,Uw=N({method:K(),params:vw.loose().optional()}),_w=N({_meta:a4.optional()}),xw=N({method:K(),params:_w.loose().optional()}),Kw=Vw({_meta:a4.optional()}),tb=a([K(),r().int()]),rX=N({jsonrpc:T(ob),id:tb,...Uw.shape}).strict(),w$=(w)=>rX.safeParse(w).success,sX=N({jsonrpc:T(ob),...xw.shape}).strict(),eX=(w)=>sX.safeParse(w).success,b$=N({jsonrpc:T(ob),id:tb,result:Kw}).strict(),h0=(w)=>b$.safeParse(w).success;var g;(function(w){w[w.ConnectionClosed=-32000]="ConnectionClosed",w[w.RequestTimeout=-32001]="RequestTimeout",w[w.ParseError=-32700]="ParseError",w[w.InvalidRequest=-32600]="InvalidRequest",w[w.MethodNotFound=-32601]="MethodNotFound",w[w.InvalidParams=-32602]="InvalidParams",w[w.InternalError=-32603]="InternalError",w[w.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(g||(g={}));var $$=N({jsonrpc:T(ob),id:tb.optional(),error:N({code:r().int(),message:K(),data:Qw().optional()})}).strict();var aX=(w)=>$$.safeParse(w).success;var wG=a([rX,sX,b$,$$]),uP=a([b$,$$]),rb=Kw.strict(),_D=_w.extend({requestId:tb.optional(),reason:K().optional()}),sb=xw.extend({method:T("notifications/cancelled"),params:_D}),xD=N({src:K(),mimeType:K().optional(),sizes:l(K()).optional(),theme:Pw(["light","dark"]).optional()}),y0=N({icons:l(xD).optional()}),t1=N({name:K(),title:K().optional()}),bG=t1.extend({...t1.shape,...y0.shape,version:K(),websiteUrl:K().optional(),description:K().optional()}),hD=pb(N({applyDefaults:Aw().optional()}),Xw(K(),Qw())),yD=s4((w)=>{if(w&&typeof w==="object"&&!Array.isArray(w)){if(Object.keys(w).length===0)return{form:{}}}return w},pb(N({form:hD.optional(),url:Lw.optional()}),Xw(K(),Qw()).optional())),uD=Vw({list:Lw.optional(),cancel:Lw.optional(),requests:Vw({sampling:Vw({createMessage:Lw.optional()}).optional(),elicitation:Vw({create:Lw.optional()}).optional()}).optional()}),fD=Vw({list:Lw.optional(),cancel:Lw.optional(),requests:Vw({tools:Vw({call:Lw.optional()}).optional()}).optional()}),cD=N({experimental:Xw(K(),Lw).optional(),sampling:N({context:Lw.optional(),tools:Lw.optional()}).optional(),elicitation:yD.optional(),roots:N({listChanged:Aw().optional()}).optional(),tasks:uD.optional()}),mD=vw.extend({protocolVersion:K(),capabilities:cD,clientInfo:bG}),W$=Uw.extend({method:T("initialize"),params:mD});var lD=N({experimental:Xw(K(),Lw).optional(),logging:Lw.optional(),completions:Lw.optional(),prompts:N({listChanged:Aw().optional()}).optional(),resources:N({subscribe:Aw().optional(),listChanged:Aw().optional()}).optional(),tools:N({listChanged:Aw().optional()}).optional(),tasks:fD.optional()}),gD=Kw.extend({protocolVersion:K(),capabilities:lD,serverInfo:bG,instructions:K().optional()}),Q$=xw.extend({method:T("notifications/initialized"),params:_w.optional()});var eb=Uw.extend({method:T("ping"),params:vw.optional()}),iD=N({progress:r(),total:Gw(r()),message:Gw(K())}),nD=N({..._w.shape,...iD.shape,progressToken:dX}),ab=xw.extend({method:T("notifications/progress"),params:nD}),pD=vw.extend({cursor:oX.optional()}),u0=Uw.extend({params:pD.optional()}),f0=Kw.extend({nextCursor:oX.optional()}),dD=Pw(["working","input_required","completed","failed","cancelled"]),c0=N({taskId:K(),status:dD,ttl:a([r(),t4()]),createdAt:K(),lastUpdatedAt:K(),pollInterval:Gw(r()),statusMessage:Gw(K())}),r1=Kw.extend({task:c0}),oD=_w.merge(c0),m0=xw.extend({method:T("notifications/tasks/status"),params:oD}),w6=Uw.extend({method:T("tasks/get"),params:vw.extend({taskId:K()})}),b6=Kw.merge(c0),$6=Uw.extend({method:T("tasks/result"),params:vw.extend({taskId:K()})}),fP=Kw.loose(),W6=u0.extend({method:T("tasks/list")}),Q6=f0.extend({tasks:l(c0)}),X6=Uw.extend({method:T("tasks/cancel"),params:vw.extend({taskId:K()})}),$G=Kw.merge(c0),WG=N({uri:K(),mimeType:Gw(K()),_meta:Xw(K(),Qw()).optional()}),QG=WG.extend({text:K()}),X$=K().refine((w)=>{try{return atob(w),!0}catch{return!1}},{message:"Invalid Base64 string"}),XG=WG.extend({blob:X$}),l0=Pw(["user","assistant"]),s1=N({audience:l(l0).optional(),priority:r().min(0).max(1).optional(),lastModified:_0.datetime({offset:!0}).optional()}),GG=N({...t1.shape,...y0.shape,uri:K(),description:Gw(K()),mimeType:Gw(K()),annotations:s1.optional(),_meta:Gw(Vw({}))}),tD=N({...t1.shape,...y0.shape,uriTemplate:K(),description:Gw(K()),mimeType:Gw(K()),annotations:s1.optional(),_meta:Gw(Vw({}))}),G$=u0.extend({method:T("resources/list")}),rD=f0.extend({resources:l(GG)}),sD=u0.extend({method:T("resources/templates/list")}),eD=f0.extend({resourceTemplates:l(tD)}),J$=vw.extend({uri:K()}),aD=J$,Y$=Uw.extend({method:T("resources/read"),params:aD}),wB=Kw.extend({contents:l(a([QG,XG]))}),bB=xw.extend({method:T("notifications/resources/list_changed"),params:_w.optional()}),$B=J$,WB=Uw.extend({method:T("resources/subscribe"),params:$B}),QB=J$,XB=Uw.extend({method:T("resources/unsubscribe"),params:QB}),GB=_w.extend({uri:K()}),JB=xw.extend({method:T("notifications/resources/updated"),params:GB}),YB=N({name:K(),description:Gw(K()),required:Gw(Aw())}),HB=N({...t1.shape,...y0.shape,description:Gw(K()),arguments:Gw(l(YB)),_meta:Gw(Vw({}))}),zB=u0.extend({method:T("prompts/list")}),DB=f0.extend({prompts:l(HB)}),BB=vw.extend({name:K(),arguments:Xw(K(),K()).optional()}),AB=Uw.extend({method:T("prompts/get"),params:BB}),H$=N({type:T("text"),text:K(),annotations:s1.optional(),_meta:Xw(K(),Qw()).optional()}),z$=N({type:T("image"),data:X$,mimeType:K(),annotations:s1.optional(),_meta:Xw(K(),Qw()).optional()}),D$=N({type:T("audio"),data:X$,mimeType:K(),annotations:s1.optional(),_meta:Xw(K(),Qw()).optional()}),FB=N({type:T("tool_use"),name:K(),id:K(),input:Xw(K(),Qw()),_meta:Xw(K(),Qw()).optional()}),LB=N({type:T("resource"),resource:a([QG,XG]),annotations:s1.optional(),_meta:Xw(K(),Qw()).optional()}),UB=GG.extend({type:T("resource_link")}),B$=a([H$,z$,D$,UB,LB]),KB=N({role:l0,content:B$}),OB=Kw.extend({description:K().optional(),messages:l(KB)}),ZB=xw.extend({method:T("notifications/prompts/list_changed"),params:_w.optional()}),MB=N({title:K().optional(),readOnlyHint:Aw().optional(),destructiveHint:Aw().optional(),idempotentHint:Aw().optional(),openWorldHint:Aw().optional()}),VB=N({taskSupport:Pw(["required","optional","forbidden"]).optional()}),JG=N({...t1.shape,...y0.shape,description:K().optional(),inputSchema:N({type:T("object"),properties:Xw(K(),Lw).optional(),required:l(K()).optional()}).catchall(Qw()),outputSchema:N({type:T("object"),properties:Xw(K(),Lw).optional(),required:l(K()).optional()}).catchall(Qw()).optional(),annotations:MB.optional(),execution:VB.optional(),_meta:Xw(K(),Qw()).optional()}),A$=u0.extend({method:T("tools/list")}),jB=f0.extend({tools:l(JG)}),G6=Kw.extend({content:l(B$).default([]),structuredContent:Xw(K(),Qw()).optional(),isError:Aw().optional()}),cP=G6.or(Kw.extend({toolResult:Qw()})),qB=x0.extend({name:K(),arguments:Xw(K(),Qw()).optional()}),g0=Uw.extend({method:T("tools/call"),params:qB}),PB=xw.extend({method:T("notifications/tools/list_changed"),params:_w.optional()}),mP=N({autoRefresh:Aw().default(!0),debounceMs:r().int().nonnegative().default(300)}),i0=Pw(["debug","info","notice","warning","error","critical","alert","emergency"]),IB=vw.extend({level:i0}),F$=Uw.extend({method:T("logging/setLevel"),params:IB}),NB=_w.extend({level:i0,logger:K().optional(),data:Qw()}),EB=xw.extend({method:T("notifications/message"),params:NB}),TB=N({name:K().optional()}),RB=N({hints:l(TB).optional(),costPriority:r().min(0).max(1).optional(),speedPriority:r().min(0).max(1).optional(),intelligencePriority:r().min(0).max(1).optional()}),SB=N({mode:Pw(["auto","required","none"]).optional()}),vB=N({type:T("tool_result"),toolUseId:K().describe("The unique identifier for the corresponding tool call."),content:l(B$).default([]),structuredContent:N({}).loose().optional(),isError:Aw().optional(),_meta:Xw(K(),Qw()).optional()}),CB=r4("type",[H$,z$,D$]),db=r4("type",[H$,z$,D$,FB,vB]),kB=N({role:l0,content:a([db,l(db)]),_meta:Xw(K(),Qw()).optional()}),_B=x0.extend({messages:l(kB),modelPreferences:RB.optional(),systemPrompt:K().optional(),includeContext:Pw(["none","thisServer","allServers"]).optional(),temperature:r().optional(),maxTokens:r().int(),stopSequences:l(K()).optional(),metadata:Lw.optional(),tools:l(JG).optional(),toolChoice:SB.optional()}),xB=Uw.extend({method:T("sampling/createMessage"),params:_B}),L$=Kw.extend({model:K(),stopReason:Gw(Pw(["endTurn","stopSequence","maxTokens"]).or(K())),role:l0,content:CB}),U$=Kw.extend({model:K(),stopReason:Gw(Pw(["endTurn","stopSequence","maxTokens","toolUse"]).or(K())),role:l0,content:a([db,l(db)])}),hB=N({type:T("boolean"),title:K().optional(),description:K().optional(),default:Aw().optional()}),yB=N({type:T("string"),title:K().optional(),description:K().optional(),minLength:r().optional(),maxLength:r().optional(),format:Pw(["email","uri","date","date-time"]).optional(),default:K().optional()}),uB=N({type:Pw(["number","integer"]),title:K().optional(),description:K().optional(),minimum:r().optional(),maximum:r().optional(),default:r().optional()}),fB=N({type:T("string"),title:K().optional(),description:K().optional(),enum:l(K()),default:K().optional()}),cB=N({type:T("string"),title:K().optional(),description:K().optional(),oneOf:l(N({const:K(),title:K()})),default:K().optional()}),mB=N({type:T("string"),title:K().optional(),description:K().optional(),enum:l(K()),enumNames:l(K()).optional(),default:K().optional()}),lB=a([fB,cB]),gB=N({type:T("array"),title:K().optional(),description:K().optional(),minItems:r().optional(),maxItems:r().optional(),items:N({type:T("string"),enum:l(K())}),default:l(K()).optional()}),iB=N({type:T("array"),title:K().optional(),description:K().optional(),minItems:r().optional(),maxItems:r().optional(),items:N({anyOf:l(N({const:K(),title:K()}))}),default:l(K()).optional()}),nB=a([gB,iB]),pB=a([mB,lB,nB]),dB=a([pB,hB,yB,uB]),oB=x0.extend({mode:T("form").optional(),message:K(),requestedSchema:N({type:T("object"),properties:Xw(K(),dB),required:l(K()).optional()})}),tB=x0.extend({mode:T("url"),message:K(),elicitationId:K(),url:K().url()}),rB=a([oB,tB]),sB=Uw.extend({method:T("elicitation/create"),params:rB}),eB=_w.extend({elicitationId:K()}),aB=xw.extend({method:T("notifications/elicitation/complete"),params:eB}),J6=Kw.extend({action:Pw(["accept","decline","cancel"]),content:s4((w)=>w===null?void 0:w,Xw(K(),a([K(),r(),Aw(),l(K())])).optional())}),wA=N({type:T("ref/resource"),uri:K()});var bA=N({type:T("ref/prompt"),name:K()}),$A=vw.extend({ref:a([bA,wA]),argument:N({name:K(),value:K()}),context:N({arguments:Xw(K(),K()).optional()}).optional()}),WA=Uw.extend({method:T("completion/complete"),params:$A});var QA=Kw.extend({completion:Vw({values:l(K()).max(100),total:Gw(r().int()),hasMore:Gw(Aw())})}),XA=N({uri:K().startsWith("file://"),name:K().optional(),_meta:Xw(K(),Qw()).optional()}),GA=Uw.extend({method:T("roots/list"),params:vw.optional()}),K$=Kw.extend({roots:l(XA)}),JA=xw.extend({method:T("notifications/roots/list_changed"),params:_w.optional()}),lP=a([eb,W$,WA,F$,AB,zB,G$,sD,Y$,WB,XB,g0,A$,w6,$6,W6,X6]),gP=a([sb,ab,Q$,JA,m0]),iP=a([rb,L$,U$,J6,K$,b6,Q6,r1]),nP=a([eb,xB,sB,GA,w6,$6,W6,X6]),pP=a([sb,ab,EB,JB,bB,PB,ZB,m0,aB]),dP=a([rb,gD,QA,OB,DB,rD,eD,wB,G6,jB,b6,Q6,r1]);class u extends Error{constructor(w,b,$){super(`MCP error ${w}: ${b}`);this.code=w,this.data=$,this.name="McpError"}static fromError(w,b,$){if(w===g.UrlElicitationRequired&&$){let W=$;if(W.elicitations)return new YG(W.elicitations,b)}return new u(w,b,$)}}class YG extends u{constructor(w,b=`URL elicitation${w.length>1?"s":""} required`){super(g.UrlElicitationRequired,b,{elicitations:w})}get elicitations(){return this.data?.elicitations??[]}}function P1(w){return w==="completed"||w==="failed"||w==="cancelled"}var YA=Symbol("Let zodToJsonSchema decide on which parser to use");var NI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function O$(w){let $=ib(w)?.method;if(!$)throw Error("Schema is missing a method literal");let W=UX($);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function Z$(w,b){let $=j1(w,b);if(!$.success)throw $.error;return $.data}var FA=60000;class M${constructor(w){if(this._options=w,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(sb,(b)=>{this._oncancel(b)}),this.setNotificationHandler(ab,(b)=>{this._onprogress(b)}),this.setRequestHandler(eb,(b)=>({})),this._taskStore=w?.taskStore,this._taskMessageQueue=w?.taskMessageQueue,this._taskStore)this.setRequestHandler(w6,async(b,$)=>{let W=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!W)throw new u(g.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler($6,async(b,$)=>{let W=async()=>{let Q=b.params.taskId;if(this._taskMessageQueue){let G;while(G=await this._taskMessageQueue.dequeue(Q,$.sessionId)){if(G.type==="response"||G.type==="error"){let J=G.message,Y=J.id,H=this._requestResolvers.get(Y);if(H)if(this._requestResolvers.delete(Y),G.type==="response")H(J);else{let z=J,B=new u(z.error.code,z.error.message,z.error.data);H(B)}else{let z=G.type==="response"?"Response":"Error";this._onerror(Error(`${z} handler missing for request ${Y}`))}continue}await this._transport?.send(G.message,{relatedRequestId:$.requestId})}}let X=await this._taskStore.getTask(Q,$.sessionId);if(!X)throw new u(g.InvalidParams,`Task not found: ${Q}`);if(!P1(X.status))return await this._waitForTaskUpdate(Q,$.signal),await W();if(P1(X.status)){let G=await this._taskStore.getTaskResult(Q,$.sessionId);return this._clearTaskQueue(Q),{...G,_meta:{...G._meta,[q1]:{taskId:Q}}}}return await W()};return await W()}),this.setRequestHandler(W6,async(b,$)=>{try{let{tasks:W,nextCursor:Q}=await this._taskStore.listTasks(b.params?.cursor,$.sessionId);return{tasks:W,nextCursor:Q,_meta:{}}}catch(W){throw new u(g.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(X6,async(b,$)=>{try{let W=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!W)throw new u(g.InvalidParams,`Task not found: ${b.params.taskId}`);if(P1(W.status))throw new u(g.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(b.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(b.params.taskId);let Q=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!Q)throw new u(g.InvalidParams,`Task not found after cancellation: ${b.params.taskId}`);return{_meta:{},...Q}}catch(W){if(W instanceof u)throw W;throw new u(g.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(w){if(!w.params.requestId)return;this._requestHandlerAbortControllers.get(w.params.requestId)?.abort(w.params.reason)}_setupTimeout(w,b,$,W,Q=!1){this._timeoutInfo.set(w,{timeoutId:setTimeout(W,b),startTime:Date.now(),timeout:b,maxTotalTimeout:$,resetTimeoutOnProgress:Q,onTimeout:W})}_resetTimeout(w){let b=this._timeoutInfo.get(w);if(!b)return!1;let $=Date.now()-b.startTime;if(b.maxTotalTimeout&&$>=b.maxTotalTimeout)throw this._timeoutInfo.delete(w),u.fromError(g.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:b.maxTotalTimeout,totalElapsed:$});return clearTimeout(b.timeoutId),b.timeoutId=setTimeout(b.onTimeout,b.timeout),!0}_cleanupTimeout(w){let b=this._timeoutInfo.get(w);if(b)clearTimeout(b.timeoutId),this._timeoutInfo.delete(w)}async connect(w){this._transport=w;let b=this.transport?.onclose;this._transport.onclose=()=>{b?.(),this._onclose()};let $=this.transport?.onerror;this._transport.onerror=(Q)=>{$?.(Q),this._onerror(Q)};let W=this._transport?.onmessage;this._transport.onmessage=(Q,X)=>{if(W?.(Q,X),h0(Q)||aX(Q))this._onresponse(Q);else if(w$(Q))this._onrequest(Q,X);else if(eX(Q))this._onnotification(Q);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Q)}`))},await this._transport.start()}_onclose(){let w=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let b=u.fromError(g.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let $ of w.values())$(b)}_onerror(w){this.onerror?.(w)}_onnotification(w){let b=this._notificationHandlers.get(w.method)??this.fallbackNotificationHandler;if(b===void 0)return;Promise.resolve().then(()=>b(w)).catch(($)=>this._onerror(Error(`Uncaught error in notification handler: ${$}`)))}_onrequest(w,b){let $=this._requestHandlers.get(w.method)??this.fallbackRequestHandler,W=this._transport,Q=w.params?._meta?.[q1]?.taskId;if($===void 0){let H={jsonrpc:"2.0",id:w.id,error:{code:g.MethodNotFound,message:"Method not found"}};if(Q&&this._taskMessageQueue)this._enqueueTaskMessage(Q,{type:"error",message:H,timestamp:Date.now()},W?.sessionId).catch((z)=>this._onerror(Error(`Failed to enqueue error response: ${z}`)));else W?.send(H).catch((z)=>this._onerror(Error(`Failed to send an error response: ${z}`)));return}let X=new AbortController;this._requestHandlerAbortControllers.set(w.id,X);let G=tX(w.params)?w.params.task:void 0,J=this._taskStore?this.requestTaskStore(w,W?.sessionId):void 0,Y={signal:X.signal,sessionId:W?.sessionId,_meta:w.params?._meta,sendNotification:async(H)=>{let z={relatedRequestId:w.id};if(Q)z.relatedTask={taskId:Q};await this.notification(H,z)},sendRequest:async(H,z,B)=>{let A={...B,relatedRequestId:w.id};if(Q&&!A.relatedTask)A.relatedTask={taskId:Q};let F=A.relatedTask?.taskId??Q;if(F&&J)await J.updateTaskStatus(F,"input_required");return await this.request(H,z,A)},authInfo:b?.authInfo,requestId:w.id,requestInfo:b?.requestInfo,taskId:Q,taskStore:J,taskRequestedTtl:G?.ttl,closeSSEStream:b?.closeSSEStream,closeStandaloneSSEStream:b?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(G)this.assertTaskHandlerCapability(w.method)}).then(()=>$(w,Y)).then(async(H)=>{if(X.signal.aborted)return;let z={result:H,jsonrpc:"2.0",id:w.id};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"response",message:z,timestamp:Date.now()},W?.sessionId);else await W?.send(z)},async(H)=>{if(X.signal.aborted)return;let z={jsonrpc:"2.0",id:w.id,error:{code:Number.isSafeInteger(H.code)?H.code:g.InternalError,message:H.message??"Internal error",...H.data!==void 0&&{data:H.data}}};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"error",message:z,timestamp:Date.now()},W?.sessionId);else await W?.send(z)}).catch((H)=>this._onerror(Error(`Failed to send response: ${H}`))).finally(()=>{this._requestHandlerAbortControllers.delete(w.id)})}_onprogress(w){let{progressToken:b,...$}=w.params,W=Number(b),Q=this._progressHandlers.get(W);if(!Q){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(w)}`));return}let X=this._responseHandlers.get(W),G=this._timeoutInfo.get(W);if(G&&X&&G.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(J){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),X(J);return}Q($)}_onresponse(w){let b=Number(w.id),$=this._requestResolvers.get(b);if($){if(this._requestResolvers.delete(b),h0(w))$(w);else{let X=new u(w.error.code,w.error.message,w.error.data);$(X)}return}let W=this._responseHandlers.get(b);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(w)}`));return}this._responseHandlers.delete(b),this._cleanupTimeout(b);let Q=!1;if(h0(w)&&w.result&&typeof w.result==="object"){let X=w.result;if(X.task&&typeof X.task==="object"){let G=X.task;if(typeof G.taskId==="string")Q=!0,this._taskProgressTokens.set(G.taskId,b)}}if(!Q)this._progressHandlers.delete(b);if(h0(w))W(w);else{let X=u.fromError(w.error.code,w.error.message,w.error.data);W(X)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(w,b,$){let{task:W}=$??{};if(!W){try{yield{type:"result",result:await this.request(w,b,$)}}catch(X){yield{type:"error",error:X instanceof u?X:new u(g.InternalError,String(X))}}return}let Q;try{let X=await this.request(w,r1,$);if(X.task)Q=X.task.taskId,yield{type:"taskCreated",task:X.task};else throw new u(g.InternalError,"Task creation did not return a task");while(!0){let G=await this.getTask({taskId:Q},$);if(yield{type:"taskStatus",task:G},P1(G.status)){if(G.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Q},b,$)};else if(G.status==="failed")yield{type:"error",error:new u(g.InternalError,`Task ${Q} failed`)};else if(G.status==="cancelled")yield{type:"error",error:new u(g.InternalError,`Task ${Q} was cancelled`)};return}if(G.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Q},b,$)};return}let J=G.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((Y)=>setTimeout(Y,J)),$?.signal?.throwIfAborted()}}catch(X){yield{type:"error",error:X instanceof u?X:new u(g.InternalError,String(X))}}}request(w,b,$){let{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:X,task:G,relatedTask:J}=$??{};return new Promise((Y,H)=>{let z=(P)=>{H(P)};if(!this._transport){z(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(w.method),G)this.assertTaskCapability(w.method)}catch(P){z(P);return}$?.signal?.throwIfAborted();let B=this._requestMessageId++,A={...w,jsonrpc:"2.0",id:B};if($?.onprogress)this._progressHandlers.set(B,$.onprogress),A.params={...w.params,_meta:{...w.params?._meta||{},progressToken:B}};if(G)A.params={...A.params,task:G};if(J)A.params={...A.params,_meta:{...A.params?._meta||{},[q1]:J}};let F=(P)=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:B,reason:String(P)}},{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:X}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let k=P instanceof u?P:new u(g.RequestTimeout,String(P));H(k)};this._responseHandlers.set(B,(P)=>{if($?.signal?.aborted)return;if(P instanceof Error)return H(P);try{let k=j1(b,P.result);if(!k.success)H(k.error);else Y(k.data)}catch(k){H(k)}}),$?.signal?.addEventListener("abort",()=>{F($?.signal?.reason)});let U=$?.timeout??FA,V=()=>F(u.fromError(g.RequestTimeout,"Request timed out",{timeout:U}));this._setupTimeout(B,U,$?.maxTotalTimeout,V,$?.resetTimeoutOnProgress??!1);let q=J?.taskId;if(q){let P=(k)=>{let S=this._responseHandlers.get(B);if(S)S(k);else this._onerror(Error(`Response handler missing for side-channeled request ${B}`))};this._requestResolvers.set(B,P),this._enqueueTaskMessage(q,{type:"request",message:A,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(B),H(k)})}else this._transport.send(A,{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:X}).catch((P)=>{this._cleanupTimeout(B),H(P)})})}async getTask(w,b){return this.request({method:"tasks/get",params:w},b6,b)}async getTaskResult(w,b,$){return this.request({method:"tasks/result",params:w},b,$)}async listTasks(w,b){return this.request({method:"tasks/list",params:w},Q6,b)}async cancelTask(w,b){return this.request({method:"tasks/cancel",params:w},$G,b)}async notification(w,b){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(w.method);let $=b?.relatedTask?.taskId;if($){let G={...w,jsonrpc:"2.0",params:{...w.params,_meta:{...w.params?._meta||{},[q1]:b.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:G,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(w.method)&&!w.params&&!b?.relatedRequestId&&!b?.relatedTask){if(this._pendingDebouncedNotifications.has(w.method))return;this._pendingDebouncedNotifications.add(w.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(w.method),!this._transport)return;let G={...w,jsonrpc:"2.0"};if(b?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[q1]:b.relatedTask}}};this._transport?.send(G,b).catch((J)=>this._onerror(J))});return}let X={...w,jsonrpc:"2.0"};if(b?.relatedTask)X={...X,params:{...X.params,_meta:{...X.params?._meta||{},[q1]:b.relatedTask}}};await this._transport.send(X,b)}setRequestHandler(w,b){let $=O$(w);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(W,Q)=>{let X=Z$(w,W);return Promise.resolve(b(X,Q))})}removeRequestHandler(w){this._requestHandlers.delete(w)}assertCanSetRequestHandler(w){if(this._requestHandlers.has(w))throw Error(`A request handler for ${w} already exists, which would be overridden`)}setNotificationHandler(w,b){let $=O$(w);this._notificationHandlers.set($,(W)=>{let Q=Z$(w,W);return Promise.resolve(b(Q))})}removeNotificationHandler(w){this._notificationHandlers.delete(w)}_cleanupTaskProgressHandler(w){let b=this._taskProgressTokens.get(w);if(b!==void 0)this._progressHandlers.delete(b),this._taskProgressTokens.delete(w)}async _enqueueTaskMessage(w,b,$){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(w,b,$,W)}async _clearTaskQueue(w,b){if(this._taskMessageQueue){let $=await this._taskMessageQueue.dequeueAll(w,b);for(let W of $)if(W.type==="request"&&w$(W.message)){let Q=W.message.id,X=this._requestResolvers.get(Q);if(X)X(new u(g.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(Q);else this._onerror(Error(`Resolver missing for request ${Q} during task ${w} cleanup`))}}}async _waitForTaskUpdate(w,b){let $=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(w);if(W?.pollInterval)$=W.pollInterval}catch{}return new Promise((W,Q)=>{if(b.aborted){Q(new u(g.InvalidRequest,"Request cancelled"));return}let X=setTimeout(W,$);b.addEventListener("abort",()=>{clearTimeout(X),Q(new u(g.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(w,b){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(W)=>{if(!w)throw Error("No request provided");return await $.createTask(W,w.id,{method:w.method,params:w.params},b)},getTask:async(W)=>{let Q=await $.getTask(W,b);if(!Q)throw new u(g.InvalidParams,"Failed to retrieve task: Task not found");return Q},storeTaskResult:async(W,Q,X)=>{await $.storeTaskResult(W,Q,X,b);let G=await $.getTask(W,b);if(G){let J=m0.parse({method:"notifications/tasks/status",params:G});if(await this.notification(J),P1(G.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return $.getTaskResult(W,b)},updateTaskStatus:async(W,Q,X)=>{let G=await $.getTask(W,b);if(!G)throw new u(g.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(P1(G.status))throw new u(g.InvalidParams,`Cannot update task "${W}" from terminal status "${G.status}" to "${Q}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(W,Q,X,b);let J=await $.getTask(W,b);if(J){let Y=m0.parse({method:"notifications/tasks/status",params:J});if(await this.notification(Y),P1(J.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return $.listTasks(W,b)}}}}function HG(w){return w!==null&&typeof w==="object"&&!Array.isArray(w)}function zG(w,b){let $={...w};for(let W in b){let Q=W,X=b[Q];if(X===void 0)continue;let G=$[Q];if(HG(G)&&HG(X))$[Q]={...G,...X};else $[Q]=X}return $}var mH=DW(F9(),1),lH=DW(cH(),1);function qV(){let w=new mH.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return lH.default(w),w}class P9{constructor(w){this._ajv=w??qV()}getValidator(w){let b="$id"in w&&typeof w.$id==="string"?this._ajv.getSchema(w.$id)??this._ajv.compile(w):this._ajv.compile(w);return($)=>{if(b($))return{valid:!0,data:$,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(b.errors)}}}}class I9{constructor(w){this._server=w}requestStream(w,b,$){return this._server.requestStream(w,b,$)}async getTask(w,b){return this._server.getTask({taskId:w},b)}async getTaskResult(w,b,$){return this._server.getTaskResult({taskId:w},b,$)}async listTasks(w,b){return this._server.listTasks(w?{cursor:w}:void 0,b)}async cancelTask(w,b){return this._server.cancelTask({taskId:w},b)}}function gH(w,b,$){if(!w)throw Error(`${$} does not support task creation (required for ${b})`);switch(b){case"tools/call":if(!w.tools?.call)throw Error(`${$} does not support task creation for tools/call (required for ${b})`);break;default:break}}function iH(w,b,$){if(!w)throw Error(`${$} does not support task creation (required for ${b})`);switch(b){case"sampling/createMessage":if(!w.sampling?.createMessage)throw Error(`${$} does not support task creation for sampling/createMessage (required for ${b})`);break;case"elicitation/create":if(!w.elicitation?.create)throw Error(`${$} does not support task creation for elicitation/create (required for ${b})`);break;default:break}}class N9 extends M${constructor(w,b){super(b);if(this._serverInfo=w,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(i0.options.map(($,W)=>[$,W])),this.isMessageIgnored=($,W)=>{let Q=this._loggingLevels.get(W);return Q?this.LOG_LEVEL_SEVERITY.get($)<this.LOG_LEVEL_SEVERITY.get(Q):!1},this._capabilities=b?.capabilities??{},this._instructions=b?.instructions,this._jsonSchemaValidator=b?.jsonSchemaValidator??new P9,this.setRequestHandler(W$,($)=>this._oninitialize($)),this.setNotificationHandler(Q$,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(F$,async($,W)=>{let Q=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:X}=$.params,G=i0.safeParse(X);if(G.success)this._loggingLevels.set(Q,G.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new I9(this)};return this._experimental}registerCapabilities(w){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=zG(this._capabilities,w)}setRequestHandler(w,b){let W=ib(w)?.method;if(!W)throw Error("Schema is missing a method literal");let Q;if(o1(W)){let G=W;Q=G._zod?.def?.value??G.value}else{let G=W;Q=G._def?.value??G.value}if(typeof Q!=="string")throw Error("Schema method literal must be a string");if(Q==="tools/call"){let G=async(J,Y)=>{let H=j1(g0,J);if(!H.success){let F=H.error instanceof Error?H.error.message:String(H.error);throw new u(g.InvalidParams,`Invalid tools/call request: ${F}`)}let{params:z}=H.data,B=await Promise.resolve(b(J,Y));if(z.task){let F=j1(r1,B);if(!F.success){let U=F.error instanceof Error?F.error.message:String(F.error);throw new u(g.InvalidParams,`Invalid task creation result: ${U}`)}return F.data}let A=j1(G6,B);if(!A.success){let F=A.error instanceof Error?A.error.message:String(A.error);throw new u(g.InvalidParams,`Invalid tools/call result: ${F}`)}return A.data};return super.setRequestHandler(w,G)}return super.setRequestHandler(w,b)}assertCapabilityForMethod(w){switch(w){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${w})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${w})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${w})`);break;case"ping":break}}assertNotificationCapability(w){switch(w){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${w})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${w})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${w})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${w})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${w})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(w){if(!this._capabilities)return;switch(w){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${w})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${w})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${w})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${w})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${w})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${w})`);break;case"ping":case"initialize":break}}assertTaskCapability(w){iH(this._clientCapabilities?.tasks?.requests,w,"Client")}assertTaskHandlerCapability(w){if(!this._capabilities)return;gH(this._capabilities.tasks?.requests,w,"Server")}async _oninitialize(w){let b=w.params.protocolVersion;return this._clientCapabilities=w.params.capabilities,this._clientVersion=w.params.clientInfo,{protocolVersion:pX.includes(b)?b:e4,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"},rb)}async createMessage(w,b){if(w.tools||w.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(w.messages.length>0){let $=w.messages[w.messages.length-1],W=Array.isArray($.content)?$.content:[$.content],Q=W.some((Y)=>Y.type==="tool_result"),X=w.messages.length>1?w.messages[w.messages.length-2]:void 0,G=X?Array.isArray(X.content)?X.content:[X.content]:[],J=G.some((Y)=>Y.type==="tool_use");if(Q){if(W.some((Y)=>Y.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!J)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(J){let Y=new Set(G.filter((z)=>z.type==="tool_use").map((z)=>z.id)),H=new Set(W.filter((z)=>z.type==="tool_result").map((z)=>z.toolUseId));if(Y.size!==H.size||![...Y].every((z)=>H.has(z)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(w.tools)return this.request({method:"sampling/createMessage",params:w},U$,b);return this.request({method:"sampling/createMessage",params:w},L$,b)}async elicitInput(w,b){switch(w.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=w;return this.request({method:"elicitation/create",params:W},J6,b)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=w.mode==="form"?w:{...w,mode:"form"},Q=await this.request({method:"elicitation/create",params:W},J6,b);if(Q.action==="accept"&&Q.content&&W.requestedSchema)try{let G=this._jsonSchemaValidator.getValidator(W.requestedSchema)(Q.content);if(!G.valid)throw new u(g.InvalidParams,`Elicitation response content does not match requested schema: ${G.errorMessage}`)}catch(X){if(X instanceof u)throw X;throw new u(g.InternalError,`Error validating elicitation response: ${X instanceof Error?X.message:String(X)}`)}return Q}}}createElicitationCompletionNotifier(w,b){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:w}},b)}async listRoots(w,b){return this.request({method:"roots/list",params:w},K$,b)}async sendLoggingMessage(w,b){if(this._capabilities.logging){if(!this.isMessageIgnored(w.level,b))return this.notification({method:"notifications/message",params:w})}}async sendResourceUpdated(w){return this.notification({method:"notifications/resources/updated",params:w})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var nH={name:"@sequenzy/mcp",version:"0.0.140",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"bunx --bun tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^7.0.2"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var E9=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],pH={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function IV(w){let $=(w??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return $.length>0?$:"https://sequenzy.com"}function dw(w){let b=w?.trim();return b?b:void 0}function w1(w){return encodeURIComponent(w)}function zw(w,b){return`${w}${b}`}function Dw(w,b=""){return`/dashboard/company/${w1(w)}${b}`}function dH(w,b,$){return zw(w,`${Dw(b,"/settings")}?tab=${encodeURIComponent($)}`)}function NV(w,b){let $=E9.map((W)=>[W,b?dH(w,b,W):""]);return Object.fromEntries($)}function B1(w={},b){let $=IV(b),W=dw(w.companyId),Q={},X=NV($,W);if(!W)return{appUrl:$,routeTemplates:pH,settingsTabValues:E9,urls:Q,settingsUrls:X};Q.dashboard=zw($,Dw(W)),Q.campaigns=zw($,Dw(W,"/campaign")),Q.landingPages=zw($,Dw(W,"/landing-pages")),Q.sequences=zw($,Dw(W,"/sequences")),Q.settings=zw($,Dw(W,"/settings")),Q.emails=zw($,Dw(W,"/emails")),Q.subscribers=zw($,Dw(W,"/subscribers")),Q.sentEmails=zw($,Dw(W,"/sent-emails")),Q.segments=zw($,Dw(W,"/segments")),Q.metrics=zw($,Dw(W,"/metrics")),Q.transactional=zw($,Dw(W,"/transactional"));let G=dw(w.campaignId);if(G)Q.campaign=zw($,Dw(W,`/campaign/${w1(G)}`)),Q.campaignPreview=`${Q.campaign}?step=review`;let J=dw(w.landingPageId);if(J)Q.landingPage=zw($,Dw(W,`/landing-pages/${w1(J)}`));let Y=dw(w.sequenceId);if(Y)Q.sequence=zw($,Dw(W,`/sequences/${w1(Y)}`));let H=dw(w.emailId)??dw(w.templateId);if(H)Q.email=zw($,Dw(W,`/emails/${w1(H)}`)),Q.template=Q.email;let z=dw(w.transactionalId);if(z)Q.transactionalEmail=zw($,Dw(W,`/transactional/${w1(z)}`));let B=dw(w.emailSendId);if(B)Q.emailSend=zw($,Dw(W,`/sent-emails/${w1(B)}`));let A=dw(w.domainId);if(A)Q.domain=zw($,Dw(W,`/settings/domain/${w1(A)}`)),Q.domainVerify=`${Q.domain}/verify`;let F=dw(w.status);if(F)Q.campaignList=zw($,Dw(W,`/campaign/list/${w1(F)}`)),Q.sequenceList=zw($,Dw(W,`/sequences/list/${w1(F)}`));let U=dw(w.settingsTab);if(U)Q.settingsTab=dH($,W,U);return{appUrl:$,routeTemplates:pH,settingsTabValues:E9,urls:Q,settingsUrls:X}}var oH=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function tH(w){try{let b;switch(w){case"sequenzy://dashboard":b=await D("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await D("GET","/api/v1/account"),W=K1()??$.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");b=await D("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":b=await D("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":b=await D("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":b=await D("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":b=await D("GET","/api/v1/sequences");break;case"sequenzy://templates":b=await D("GET","/api/v1/templates");break;case"sequenzy://segments":b=await D("GET","/api/v1/segments");break;case"sequenzy://tags":b=await D("GET","/api/v1/tags");break;case"sequenzy://health":b=await D("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":b=B1();break;default:throw Error(`Unknown resource: ${w}`)}return{contents:[{uri:w,mimeType:"application/json",text:JSON.stringify(b,null,2)}]}}catch(b){return{contents:[{uri:w,mimeType:"text/plain",text:U1(b)}]}}}function C(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}function L(w,b){let $=w[b];if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function Z(w,b,$){let W=L(b,$);if(W===void 0)throw Error(`\`${$}\` is required when calling \`${w}\`.`);return W}var p6=' Minimal valid core examples: {"type":"heading","content":"Title","level":1}; {"type":"text","content":"<p>Paragraph with <strong>bold</strong></p>","variant":"paragraph"}; {"type":"button","text":"Click Me","url":"https://example.com","variant":"primary"}; {"type":"image","src":"https://...","alt":"Description","width":100,"widthType":"percent","height":240,"objectFit":"cover","href":"https://example.com","align":"center"}. Heading and text use `content`; button uses `text` but also accepts `content` as an alias and defaults `variant` to `primary`. Image `widthType` accepts `percent` or `px`.';var T9=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "commerceCollection", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',R9=' Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). `accentColor` recolors every appearance, including "brutal". `optionRadius` sets answer-button corners in px (0 is square) independently of `styles.borderRadius`, while `questionColor` recolors only the question. `fontFamily` applies to the poll; `optionFontSize`, `optionFontWeight`, `optionLetterSpacing`, and `optionTextTransform` style answers, and the matching `questionFontSize`, `questionFontWeight`, `questionLetterSpacing`, and `questionTextTransform` fields style the question. Sizes and spacing are px, weights are 100-900, and transforms are "none" or "uppercase". Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page.',S9=' For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',Yw="Raw HTML is stored as one opaque block. Sequenzy preserves that markup but does not add a company logo, branded native sections, or theme-driven block design. Use blocks for editor-native design, or a drafting prompt when you want Sequenzy to compose a new branded email.",d6=' The code is minted per subscriber at run time and reaches every later email in the same sequence as {{discount.code}}. Also available: {{discount.value}} (pre-formatted, e.g. "20% off" or "$10 off"), {{discount.percentOff}}, {{discount.amountOff}}, {{discount.currency}}, and {{date.discount.expiresAt}} (locale-formatted expiry). Present the code with a { "type": "discount-code", "code": "{{discount.code}}", "label": "Your discount code" } block, or inline {{discount.code}} in any text block. These tags resolve only in emails downstream of the discount step; render_email substitutes a clearly fake sample code so the email can be previewed before anyone is enrolled, and lists anything it could not resolve under unresolvedMergeTags.',C1='For exact historical Poll/NPS respondents, use field `pollResponse`, operator `is`, and a JSON value shaped like {"v":1,"campaignId":"camp_123","blockId":"poll_1","match":{"kind":"answer","value":"loved"}}. For NPS buckets, use match {"kind":"npsBucket","bucket":"promoters"}; bucket may be `promoters`, `passives`, or `detractors`.',v9=" `styles` applies to the block's own container, not to an inner rendered element. On a button block, `styles.backgroundColor` colors the band behind the button and `styles.textColor` does not reach the label - set the top-level `buttonColor` and `buttonTextColor` fields instead, or leave them unset to inherit the email theme's primary color.",l1=" Unsupported fields are discarded and reported in the response `warnings` array rather than rejected.",A1=`Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the \`html\` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.${T9}${v9}${l1}${R9}${S9}${p6}`,o6=" Replacing a step's blocks keeps that step's existing Style > Format rather than the company default: a step that already had a logo or footer gets them back even if you omit them, and every block added that way is listed in the response `warnings`. Pass `emailPreset` to change the format. A step whose stored content is a single raw HTML block has no format, so replacing it with another single raw HTML block is stored exactly as sent; replacing it with native blocks converts the step and does add a footer.",EV=` For action_email:${o6}`,F1=`Replacement Sequenzy email blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`.${T9}${v9}${l1}${R9}${S9}${p6}`,H0=`Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer \`html\`; Sequenzy stores it as one raw HTML block and does not recreate it as native blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Blocks can include repeat blocks over array variables such as items.${T9}${v9}${l1}${R9}${S9}${p6}`,Lb="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",rH="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",C9=500,k9=500,uw={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},Ub=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay","transport_failure"],Kb=Ub.join(", "),t6={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},TV={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},z0={type:"object",description:"Wait until a date from the trigger event before this step. Use this for renewal reminders, appointment follow-ups, trial-expiry nudges, and other subscriber-specific dates. The field value must be an ISO date string or Unix timestamp.",properties:{field:{type:"string",description:"Dot-path into the trigger event properties, e.g. renews_at or booking.startsAt."},untilDateField:{type:"string",description:"Alias for field."},offset:TV,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},D0={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date"],description:"Use duration for a fixed wait, or until_date to resolve a date from the trigger event."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},_9={type:"object",description:`Type-aware patch for the existing node. Start from get_sequence.sequence.nodes[].config. For logic_delay, set exactly one of delay ({ days, hours, minutes }), delayMs, or waitUntil; optional label is also accepted. For action_email, use name/label, subject, previewText, html/htmlContent or blocks, emailPreset, isTransactional, attachments ([{ filename, path }] URL-backed files fetched at send time; path may use {{event.*}} from the enrollment event; [] removes them), and sender/reply identity fields. For action_sms, use text, blocks, imageUrls, label, or ineligibleAction. Other node types accept their editable config keys. Managed IDs, nodeType conversion, and branch path IDs/count are not editable here; use edit_sequence_graph for topology. Webhook header patches are merged, and redacted values from get_sequence must be omitted or replaced with a real new value.${EV}`,properties:{emailPreset:{type:"string",enum:["branded","minimal"],description:"For an action_email node with native Sequenzy blocks, set the linked email's per-email Style > Format. Native block emails may include supported custom HTML blocks. Use minimal for a direct text-forward note without the company logo and with the simple footer, or branded to restore branded chrome. This does not change the company-wide default. A standalone raw HTML email does not support this field, and emailPreset must not be combined with html/htmlContent."}},additionalProperties:!0},r6={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:_9,expectedUpdatedAt:{type:"string",description:"Required optimistic-concurrency value from get_sequence.sequence.nodes[].updatedAt. The update is rejected if that node or its linked email content changed after it was read."}},required:["nodeId","changes","expectedUpdatedAt"],additionalProperties:!1},B0=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],A0=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.failed","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.created","subscriber.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","sequence.finished","sequence.failed","poll.answered"];var RV=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_api_keys","list_websites","list_integrations","get_integration","get_integration_pixel","list_integration_capabilities","list_integration_activity","list_sender_profiles","get_notification_preferences","get_tracking_settings","check_website","get_integration_guide","get_subscriber","get_subscriber_import","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_campaign_audience","render_email","list_email_sends","get_email_send","list_forms","get_form_embed","get_recipient_suppression","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_sequence_enrollments","list_sequence_goals","get_sequence_inbound_webhook","list_transactional_emails","get_transactional_email","get_stats","get_transactional_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_subject_lines","generate_sms","get_sms_settings"]),SV=new Set(["select_company","create_company","update_company","update_notification_preferences","update_sender_profile","update_tracking_settings","update_sync_rules","update_shopify_automation_settings","connect_integration","set_integration_sync_enabled","sync_integration","activate_integration_pixel","create_api_key","update_api_key","revoke_api_key","delete_api_key","add_sending_domain","add_website","verify_sending_domain","add_subscriber","create_subscriber_import","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","trigger_subscriber_event","trigger_subscriber_events","bulk_add_subscriber_tags","bulk_remove_subscriber_tags","upsert_products","delete_product","attach_product_file","remove_product_file","upload_image_asset","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","set_template_localization","sync_template_localizations","delete_template","restart_ab_test","update_ab_test_variant","update_ab_test","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","unschedule_campaign","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_form","update_form","create_landing_page","update_landing_page","duplicate_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","generate_sequence","send_sequence_test_email","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","duplicate_sequence","archive_sequence","unarchive_sequence","create_sequence_goal","update_sequence_goal","delete_sequence_goal","configure_sequence_inbound_webhook","rotate_sequence_inbound_webhook_secret","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","delete_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback","remove_recipient_suppression"]),vV=new Set(["send_test_email","send_test_sms","send_sequence_test_email","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","add_sending_domain","add_website","verify_sending_domain","connect_integration","sync_integration","get_integration_pixel","activate_integration_pixel","enable_sequence","unarchive_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery","remove_recipient_suppression"]),CV=new Set(["revoke_api_key","delete_api_key","remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","bulk_remove_subscriber_tags","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","set_integration_sync_enabled","disable_sequence","archive_sequence","delete_sequence_goal","rotate_sequence_inbound_webhook_secret","edit_sequence_graph","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook","delete_transactional_email","remove_recipient_suppression"]);function kV(w){let b=RV.has(w),$=SV.has(w);if(b===$)throw Error(`MCP tool "${w}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:b,destructiveHint:b?!1:CV.has(w),openWorldHint:vV.has(w)}}function sH(w){return{...w,annotations:{...w.annotations,...kV(w.name)}}}var x9={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains","is","is_not"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],pollResponse:["is"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"],commerceCollection:["is","is_not","at_least","less_than_count"]},_V=Object.entries(x9).map(([w,b])=>`${w}: ${b.join(", ")}`).join("; "),h9={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","pollResponse","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct","commerceCollection"],description:`Filter field. Use \`email\` with is/is_not for exact, case-insensitive address matching (allowlists and exclusions) and with contains/not_contains for domain or substring matching. Use \`phone\` with is_not_empty/is_empty to check whether a subscriber has a phone number, and \`smsStatus\` (is/is_not one of \`subscribed\`, \`unsubscribed\`, \`not_subscribed\`) for SMS marketing consent. Use \`event\` for custom subscriber events, \`segment\` for saved segment membership, \`stripeProduct\`/\`stripeCurrentProduct\`/\`stripeTrialProduct\` for Stripe product-based segments, and \`commerceProduct\` for products purchased through commerce orders - the value is \`provider:productId\` (provider one of \`shopify\`, \`woocommerce\`, \`api\`; product ids are provider-scoped), optionally with an order-count threshold (\`provider:productId:count\`) for at_least/less_than_count; a bare product id matches the id on any provider. Use \`commerceCollection\` to segment on anyone who bought ANY product in a store collection - the value is the collection id or handle (e.g. \`skincare\`), optionally provider-prefixed and/or with an order-count threshold (\`shopify:skincare:2\`); collection membership is resolved from the synced catalog as it stands now, and only Shopify collections and WooCommerce categories are synced. Engagement fields (\`emailSent\`, \`emailDelivered\`, \`emailOpened\`, \`emailClicked\`, \`emailBounced\`, \`emailComplained\`) accept a time range as the value, a specific campaign via \`campaign:<campaign_id>\`, or \`count:timeRange\` (e.g. \`10:30d\`, \`10:all\`) with at_least/less_than_count to segment by number of opens/clicks. ${C1}`},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${_V}.`},value:{type:"string",description:`Filter value. For custom attribute empty checks, use \`attributeName:\` such as \`last_logged_in:\`. Event examples: \`saas.purchase:30d\`, \`saas.purchase:all\`, or \`saas.purchase:5:30d\` for thresholds. Segment values are segment IDs. Stripe product examples: \`prod_123\` for bought/didn't buy/current/trialing, \`prod_123:3\` for payment thresholds, \`prod_123:is_canceled\` for products set to cancel, \`prod_123:cancels_at:2026-05-26\`, \`prod_123:end_at:2026-05-26\`, or \`prod_123:start_at:7 days ago\` for product-scoped dates. Engagement examples: \`7d\`, \`30d\`, \`90d\`, \`180d\`, \`all\` for rolling time windows, \`campaign:<campaign_id>\` to scope to a specific sent campaign (use \`list_campaigns\` to find IDs), or \`count:timeRange\` like \`10:30d\` / \`10:all\` with at_least/less_than_count operators (e.g. emailClicked at_least \`10:all\` = clicked 10 or more times ever). ${C1}`}},required:["field","operator","value"],additionalProperties:!1},y9={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function s6(w){if(!Array.isArray(w))return w;return w.map((b)=>{if(typeof b!=="object"||b===null)return b;let $=b;if(typeof $.id==="string"&&$.id.trim()!=="")return $;return{...$,id:crypto.randomUUID()}})}function e6(w){if(typeof w!=="object"||w===null)return w;let b=w;if(b.kind==="filter"||"field"in b||"operator"in b||"value"in b){let $=s6([b]);return Array.isArray($)?$[0]:b}if(b.kind!=="group")return w;return{...b,id:typeof b.id==="string"&&b.id.trim()!==""?b.id:crypto.randomUUID(),children:Array.isArray(b.children)?b.children.map(e6):[]}}function xV(w){let b=w.indexOf(":");return b!==-1&&w.substring(0,b).trim().length>0}function hV(w){let b=w.indexOf(":");return b!==-1&&w.substring(b+1).trim().length>0}function eH(w){if(w==="all")return!0;let b=w.match(/^(\d+)d$/);if(!b?.[1])return!1;let $=Number.parseInt(b[1],10);return Number.isInteger($)&&$>0}function yV(w,b){let $=b.split(":");if(w==="at_least"||w==="less_than_count"){if($.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let X=$.slice(0,-2).join(":").trim(),G=$.at(-2),J=$.at(-1),Y=G===void 0?Number.NaN:Number.parseInt(G,10);return X&&Number.isInteger(Y)&&Y>0&&J!==void 0&&eH(J)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if($.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=$.slice(0,-1).join(":").trim(),Q=$.at(-1);return W&&Q!==void 0&&eH(Q)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function uV(w){let b=w.indexOf(":");if(b===-1)return{productId:w,subfilter:null,rawValue:null};let $=w.substring(0,b),W=w.substring(b+1),Q=W.indexOf(":");if(Q===-1)return{productId:$,subfilter:W,rawValue:null};return{productId:$,subfilter:W.substring(0,Q),rawValue:W.substring(Q+1)}}function fV(w){return w.trim().toLowerCase().replace(/[-\s]+/g,"_")}function cV(w){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(w)}function mV(w,b){if(b==="cancels_at"||b==="cancel_at"||b==="cancellation_at")return!0;if(w==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(b);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(b)}function lV(w){return["is","is_not","gte","lte","gt","lt"].includes(w)}function gV(w,b,$){if(w==="stripeProduct"){if(b!=="at_least"&&b!=="less_than_count")return null;let J=$.indexOf(":");if(J===-1)return null;let Y=$.substring(0,J).trim(),H=Number.parseInt($.substring(J+1).trim(),10);return Y&&Number.isInteger(H)&&H>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(w!=="stripeCurrentProduct"&&w!=="stripeTrialProduct")return null;let{productId:W,subfilter:Q,rawValue:X}=uV($);if(!W.trim())return"Stripe product filters must include a product ID.";if(!Q)return b==="is"||b==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let G=fV(Q);if(cV(G))return b==="is"||b==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!mV(w,G))return`Unsupported Stripe product subfilter "${Q}".`;if(!lV(b))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return X?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var aH=new Set(["shopify","woocommerce","api"]);function iV(w,b){let $=b.trim(),W=$.indexOf(":");if(W!==-1&&aH.has($.substring(0,W).trim()))$=$.substring(W+1).trim();if(!$)return'Purchased Product filters must include a product ID, like "shopify:42".';if(w!=="at_least"&&w!=="less_than_count")return null;let Q=$.lastIndexOf(":");if(Q===-1)return null;let X=$.substring(0,Q).trim(),G=Number.parseInt($.substring(Q+1).trim(),10);return X&&Number.isInteger(G)&&G>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function nV(w,b){let $=b.trim(),W=$.indexOf(":");if(W!==-1&&aH.has($.substring(0,W).trim()))$=$.substring(W+1).trim();if(!$)return'Purchased Collection filters must include a collection, like "shopify:summer-sale".';if(w!=="at_least"&&w!=="less_than_count")return null;let Q=$.lastIndexOf(":");if(Q===-1)return null;let X=$.substring(0,Q).trim(),G=Number.parseInt($.substring(Q+1).trim(),10);return X&&Number.isInteger(G)&&G>=1?null:'Purchased Collection threshold filters must use "provider:collection:count" with a count of at least 1.'}function pV(w){let b;try{b=JSON.parse(w)}catch{return`Poll response filters must use valid JSON. ${C1}`}if(!C(b)||b.v!==1||typeof b.campaignId!=="string"||!b.campaignId.trim()||typeof b.blockId!=="string"||!b.blockId.trim()||!C(b.match))return`Poll response filter context is invalid. ${C1}`;let $=b.match;if($.kind==="answer"&&typeof $.value==="string"&&$.value.length>0)return null;if($.kind==="npsBucket"&&($.bucket==="promoters"||$.bucket==="passives"||$.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${C1}`}function a6(w){if(typeof w!=="object"||w===null)return"Segment filters must be objects.";let b=w,$=b.field,W=b.operator,Q=b.value;if(typeof $!=="string"||!($ in x9))return`Unsupported segment filter field "${String($)}".`;if(typeof W!=="string")return`Segment filter "${$}" must include an operator.`;let X=x9[$];if(!X.includes(W))return`Operator "${W}" is not supported for ${$} filters. Use one of: ${X.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof Q!=="string"||Q.trim().length===0))return`Segment filter "${$}" must include a value.`;if($==="attribute"&&typeof Q==="string"){if(!xV(Q))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!hV(Q))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof Q==="string"){let G=yV(W,Q);if(G)return G}if($==="pollResponse"&&typeof Q==="string"){let G=pV(Q);if(G)return G}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof Q==="string"){let G=gV($,W,Q);if(G)return G}if($==="commerceProduct"&&typeof Q==="string"){let G=iV(W,Q);if(G)return G}if($==="commerceCollection"&&typeof Q==="string"){let G=nV(W,Q);if(G)return G}if($==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof Q==="string"&&Q.split(",").map((J)=>J.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function w4(w){if(typeof w!=="object"||w===null)return[];let b=w;if(b.kind==="filter"||"field"in b||"operator"in b||"value"in b){let $=a6(b);return $?[$]:[]}if(Array.isArray(b.children))return b.children.flatMap(w4);return[]}function Cw(w,b,$){if(b.html!==void 0&&b.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${w}\`, not both.`);if(b.blocks!==void 0&&!Array.isArray(b.blocks))throw Error(`\`blocks\` must be an array when calling \`${w}\`.`);if($?.requireContent&&b.html===void 0&&b.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${w}\`.`)}function L1(w,b){if(b.labels===void 0)return;if(!Array.isArray(b.labels))throw Error(`\`labels\` must be an array when calling \`${w}\`.`);if(b.labels.some(($)=>typeof $!=="string"||$.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${w}\`.`)}function $5(w){let b=w.filters!==void 0,$=w.root!==void 0;if(b&&$)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!b&&!$)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(b){if(!Array.isArray(w.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(w.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if($&&(typeof w.root!=="object"||w.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=b?w.filters.flatMap((Q)=>{let X=a6(Q);return X?[X]:[]}):w4(w.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function W5(w){let b=w.filters!==void 0,$=w.root!==void 0;if(b&&$)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(w.name===void 0&&w.filterJoinOperator===void 0&&!b&&!$)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(b){if(!Array.isArray(w.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(w.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if($&&(typeof w.root!=="object"||w.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=b?w.filters.flatMap((Q)=>{let X=a6(Q);return X?[X]:[]}):$?w4(w.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var u9=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailTheme","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingEnabled","replyTrackingDomainMode","forwardReplies"];function f9(w,b,$){if(b[$]!==void 0&&!C(b[$]))throw Error(`\`${$}\` must be an object when calling \`${w}\`.`)}function w5(w,b,$){if(b[$]!==void 0&&!Array.isArray(b[$]))throw Error(`\`${$}\` must be an array when calling \`${w}\`.`)}function Q5(w){let b=new Set(["companyId",...u9]),$=Object.keys(w).filter((Q)=>!b.has(Q));if($.length>0)throw Error(`\`update_company\` accepts only editable company settings. Unsupported field${$.length===1?"":"s"}: ${$.map((Q)=>`\`${Q}\``).join(", ")}.`);let W={};for(let Q of u9)if(w[Q]!==void 0)W[Q]=w[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${u9.map((Q)=>`\`${Q}\``).join(", ")} when calling \`update_company\`.`);for(let Q of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingDomainMode"])if(w[Q]!==void 0&&typeof w[Q]!=="string")throw Error(`\`${Q}\` must be a string when calling \`update_company\`.`);if(f9("update_company",w,"brandColors"),f9("update_company",w,"socialLinks"),f9("update_company",w,"pricing"),w.emailTheme!==void 0&&w.emailTheme!==null&&!C(w.emailTheme))throw Error("`emailTheme` must be an object or null when calling `update_company`.");w5("update_company",w,"valueProps"),w5("update_company",w,"testimonials");for(let Q of["replyTrackingEnabled","forwardReplies"])if(w[Q]!==void 0&&typeof w[Q]!=="boolean")throw Error(`\`${Q}\` must be a boolean when calling \`update_company\`.`);if(w.replyTrackingDomainMode!==void 0&&w.replyTrackingDomainMode!=="sequenzy"&&w.replyTrackingDomainMode!=="custom")throw Error("`replyTrackingDomainMode` must be `sequenzy` or `custom` when calling `update_company`.");if(typeof w.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(w.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let Q of["fromEmail","replyTo"]){let X=w[Q];if(typeof X==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(X.trim()))throw Error(`\`${Q}\` must be a valid email address when calling \`update_company\`.`)}return W}var c9=["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","defaultAttributionWindowHours","doubleOptInEnabled","autoUtmEnabled","autoUtmSettings"],m9=["source","medium","campaign","content","term"];function X5(w){let b=new Set(["companyId",...c9]),$=Object.keys(w).filter((Q)=>!b.has(Q));if($.length>0)throw Error(`\`update_tracking_settings\` accepts only tracking settings. Unsupported field${$.length===1?"":"s"}: ${$.map((Q)=>`\`${Q}\``).join(", ")}. Reply tracking is set with \`update_company\`.`);let W={};for(let Q of c9)if(w[Q]!==void 0)W[Q]=w[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${c9.map((Q)=>`\`${Q}\``).join(", ")} when calling \`update_tracking_settings\`.`);for(let Q of["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","doubleOptInEnabled","autoUtmEnabled"])if(w[Q]!==void 0&&typeof w[Q]!=="boolean")throw Error(`\`${Q}\` must be a boolean when calling \`update_tracking_settings\`.`);if(w.defaultAttributionWindowHours!==void 0&&(typeof w.defaultAttributionWindowHours!=="number"||!Number.isInteger(w.defaultAttributionWindowHours)||w.defaultAttributionWindowHours<1||w.defaultAttributionWindowHours>720))throw Error("`defaultAttributionWindowHours` must be a whole number of hours between 1 and 720 when calling `update_tracking_settings`.");if(w.autoUtmSettings!==void 0&&w.autoUtmSettings!==null&&!C(w.autoUtmSettings))throw Error("`autoUtmSettings` must be an object or null when calling `update_tracking_settings`.");if(C(w.autoUtmSettings)){let Q=w.autoUtmSettings,X=Object.keys(Q).filter((G)=>!m9.includes(G));if(X.length>0)throw Error(`\`autoUtmSettings\` accepts only ${m9.map((G)=>`\`${G}\``).join(", ")}. Unsupported: ${X.map((G)=>`\`${G}\``).join(", ")}.`);for(let G of m9){let J=Q[G];if(J!==void 0&&J!==null&&typeof J!=="string")throw Error(`\`autoUtmSettings.${G}\` must be a string or null when calling \`update_tracking_settings\`.`)}}return W}var g9={profileKey:"senderProfileId",emailKey:"fromEmail",nameKey:"fromName",addressLabel:"From"},i9={profileKey:"replyProfileId",emailKey:"replyTo",nameKey:"replyToName",addressLabel:"Reply-To"};function n9(w){let{profileKey:b,emailKey:$,nameKey:W,addressLabel:Q}=w.pair,X=w.args[b]!==void 0,G=w.args[$]!==void 0,J=w.args[W]!==void 0,Y=w.location?`for ${w.location} when calling \`${w.toolName}\``:`when calling \`${w.toolName}\``,H=`\`${b}\` already sets both the ${Q} address and the display name, so send it without \`${$}\`${w.nameIsOverride?"":` and \`${W}\``}.`;if(X&&G){let[z,B]=w.profileFirst?[b,$]:[$,b];throw Error(`Provide either \`${z}\` or \`${B}\` ${Y}, not both. ${H}`)}if(X&&J&&!w.nameIsOverride)throw Error(`\`${W}\` cannot be combined with \`${b}\` ${Y}. ${H}`);if(J&&!G&&!w.nameIsOverride)throw Error(`\`${W}\` requires \`${$}\` ${Y}. Send \`${W}\` with the \`${$}\` it names, or send \`${b}\` on its own to use an existing profile's address and name.`)}function F0(w,b,$){let W=$?.replyFirst?[i9,g9]:[g9,i9];for(let Q of W)n9({toolName:w,args:b,pair:Q})}var G5=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function dV(w){return G5.some((b)=>w[b]!==void 0)}function oV(w){if(typeof w.nodeType==="string")return w.nodeType==="action_email";return w.type===void 0||w.type==="email"}function b4(w,b,$){for(let W of G5){let Q=$[W];if(Q!==void 0&&typeof Q!=="string")throw Error(`\`${W}\` must be a string for ${b} when calling \`${w}\`.`)}n9({toolName:w,args:$,pair:g9,location:b,profileFirst:!0,nameIsOverride:!0}),n9({toolName:w,args:$,pair:i9,location:b,profileFirst:!0})}function p9(w,b,$){if(dV($)&&!oV($))throw Error(`Sender identity fields are only supported for email steps at ${b} when calling \`${w}\`.`);b4(w,b,$)}function b5(w,b,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(C(W))b4(w,`${b}[${Q}]`,W)})}function l9(w,b,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(C(W))p9(w,`${b}[${Q}]`,W)})}function tV(w){if(b5("update_sequence","emails",w.emails),b5("update_sequence","steps",w.steps),C(w.insertSteps))l9("update_sequence","insertSteps.steps",w.insertSteps.steps);if(!C(w.branch))return;if(Array.isArray(w.branch.branches))w.branch.branches.forEach(($,W)=>{if(C($))l9("update_sequence",`branch.branches[${W}].steps`,$.steps)});l9("update_sequence","branch.elseSteps",w.branch.elseSteps)}function J5(w){L1("update_sequence",w);let b=["listId","tagName","segmentId","stopOnSegmentExit","eventName","propertyFilters","integrationSlug","integrationEventKey","customIntegration","inactiveDays","inactivityBaseline","minCount","timeWindowDays"];if(w.trigger===void 0&&b.some((W)=>w[W]!==void 0))throw Error("Provide `trigger` when replacing sequence trigger configuration with `update_sequence`.");if(F0("update_sequence",w),w.clearEnrollmentFieldPath===!0&&w.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(w.clearSendingWindow===!0&&w.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(w.clearBccEmails===!0&&w.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(w.branch!==void 0&&w.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");tV(w);let $={...w};if(delete $.clearEnrollmentFieldPath,delete $.clearSendingWindow,delete $.clearBccEmails,w.clearEnrollmentFieldPath===!0)$.enrollmentFieldPath=null;if(w.clearSendingWindow===!0)$.sendingWindow=null;if(w.clearBccEmails===!0)$.bccEmails=null;return $}function rV(w,b){if((b.triggerType??"event")==="event"){if(typeof b.triggerEventName!=="string"||b.triggerEventName.trim().length===0)throw Error(`\`triggerEventName\` is required when calling \`${w}\` with an event goal (the default \`triggerType\`).`);return}if(typeof b.attributePath!=="string"||b.attributePath.trim().length===0)throw Error(`\`attributePath\` is required when calling \`${w}\` with \`triggerType: "attribute_change"\`.`);let W=b.attributeCondition??"changed",Q=typeof b.attributeValue==="string"&&b.attributeValue.trim().length>0,X=typeof b.attributePreviousValue==="string"&&b.attributePreviousValue.trim().length>0;if((W==="changed_to"||W==="changed_from_to")&&!Q)throw Error(`\`attributeValue\` is required when calling \`${w}\` with \`attributeCondition\` \`changed_to\` or \`changed_from_to\`.`);if(W==="changed_from_to"&&!X)throw Error(`\`attributePreviousValue\` is required when calling \`${w}\` with \`attributeCondition: "changed_from_to"\`.`)}function Y5(w){rV("create_sequence_goal",w)}function H5(w){if(typeof w.triggerEventName==="string"&&w.triggerEventName.trim().length===0)throw Error("`triggerEventName` must be a non-empty string when provided to `update_sequence_goal`.");if(typeof w.attributePath==="string"&&w.attributePath.trim().length===0)throw Error("`attributePath` must be a non-empty string when provided to `update_sequence_goal`.")}function D5(w,b,$){let W=Z(w,b,"nodeId");if(!C(b.changes)||Object.keys(b.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${w}\`.`);let Q=Z(w,b,"expectedUpdatedAt");return{nodeId:W,changes:b.changes,expectedUpdatedAt:Q}}function B5(w){let b=D5("update_sequence_node",w,"the node update");return{...w.confirmLiveChange!==void 0&&{confirmLiveChange:w.confirmLiveChange},nodeUpdates:[b]}}function A5(w){if(!Array.isArray(w.updates)||w.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let b=new Set,$=w.updates.map((W,Q)=>{if(!C(W))throw Error(`\`updates[${Q}]\` must be an object when calling \`update_sequence_nodes\`.`);let X=D5("update_sequence_nodes",W,`updates[${Q}]`),G=String(X.nodeId);if(b.has(G))throw Error(`\`updates[${Q}]\` targets duplicate nodeId '${G}' when calling \`update_sequence_nodes\`.`);return b.add(G),X});return{...w.confirmLiveChange!==void 0&&{confirmLiveChange:w.confirmLiveChange},nodeUpdates:$}}function F5(w){let b=Z("edit_sequence_graph",w,"action"),$=Z("edit_sequence_graph",w,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(b))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let Q=L(w,"nodeId"),X=L(w,"afterNodeId"),G=L(w,"beforeNodeId"),J=w.edges;if(b!=="replace_edges"&&!Q)throw Error(`\`nodeId\` is required for ${b} when calling \`edit_sequence_graph\`.`);if(b==="replace_edges"&&Q)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let Y=b==="move_node"||b==="duplicate_node";if(Y&&(X?1:0)+(G?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${b} when calling \`edit_sequence_graph\`.`);if(!Y&&(X||G))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${b} when calling \`edit_sequence_graph\`.`);if((b==="replace_edges"||b==="delete_node"&&J!==void 0)&&(!Array.isArray(J)||J.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${b} when calling \`edit_sequence_graph\`.`);if((b==="move_node"||b==="duplicate_node")&&J!==void 0)throw Error(`\`edges\` is not used with ${b} when calling \`edit_sequence_graph\`.`);let H=Array.isArray(J)?J.map((z,B)=>{if(!C(z))throw Error(`\`edges\` item ${B+1} must be an object when calling \`edit_sequence_graph\`.`);let A=Z("edit_sequence_graph",z,"sourceNodeId"),F=Z("edit_sequence_graph",z,"targetNodeId");if(z.condition!==void 0&&z.condition!==null&&!C(z.condition))throw Error(`\`edges\` item ${B+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:A,targetNodeId:F,...C(z.condition)?{condition:z.condition}:{}}}):void 0;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},graphEdit:{action:b,expectedRevision:$,...Q?{nodeId:Q}:{},...X?{afterNodeId:X}:{},...G?{beforeNodeId:G}:{},...H?{edges:H}:{}}}}function L5(w){let b=L(w,"type")??"email";if(!new Set(["email","sms","delay","create_discount","update_subscriber","condition","add_tag","remove_tag","add_to_list","remove_from_list","webhook","logic_wait_for_event","logic_branch"]).has(b))throw Error("`type` is not a supported dashboard sequence step when calling `insert_sequence_step`.");if(b==="logic_wait_for_event"){let G=Z("insert_sequence_step",w,"eventName"),J=w.timeoutDays,Y=J===void 0?7:J;if(typeof Y!=="number"||!Number.isInteger(Y)||Y<1||Y>365)throw Error("`timeoutDays` must be a whole number from 1 to 365 when inserting `logic_wait_for_event` with `insert_sequence_step`.");let H=L(w,"timeoutAction")??"continue";if(H!=="continue"&&H!=="exit")throw Error("`timeoutAction` must be `continue` or `exit` when inserting `logic_wait_for_event` with `insert_sequence_step`.");let z={steps:[{nodeType:"logic_wait_for_event",config:{label:L(w,"label")??`Wait for ${G}`,eventName:G,timeoutDays:Y,timeoutAction:H}}]},B=L(w,"afterNodeId");if(B)z.afterNodeId=B;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:z}}if(b==="logic_branch"){let G=Z("insert_sequence_step",w,"afterNodeId");if(!Array.isArray(w.branches)||w.branches.length===0)throw Error("`branches` must contain at least one typed condition when inserting `logic_branch` with `insert_sequence_step`.");let J=new Set(["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"]),Y=["id","label","conditionType","tagName","tagId","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue","targetNodeId","steps"],H=w.allowEmptyPaths===!0,z=w.branches.map((F,U)=>{if(!C(F))throw Error(`\`branches[${U}]\` must be an object when calling \`insert_sequence_step\`.`);let V=Z("insert_sequence_step",F,"conditionType");if(!J.has(V))throw Error(`\`branches[${U}].conditionType\` is not supported when calling \`insert_sequence_step\`.`);let q=`branches[${U}]`;if((V==="has_tag"||V==="does_not_have_tag")&&!L(F,"tagId")&&!L(F,"tagName"))throw Error(`\`${q}\` must provide \`tagId\` or \`tagName\` for ${V} when calling \`insert_sequence_step\`.`);if(V==="in_list"&&!L(F,"listId"))throw Error(`\`${q}.listId\` is required for in_list when calling \`insert_sequence_step\`.`);if(V==="in_segment"&&!L(F,"segmentId"))throw Error(`\`${q}.segmentId\` is required for in_segment when calling \`insert_sequence_step\`.`);if(V==="event_received"&&!L(F,"eventName"))throw Error(`\`${q}.eventName\` is required for event_received when calling \`insert_sequence_step\`.`);if(V.startsWith("field_")&&(!L(F,"fieldName")||!L(F,"fieldValue")))throw Error(`\`${q}\` must provide \`fieldName\` and \`fieldValue\` for ${V} when calling \`insert_sequence_step\`.`);if(F.steps!==void 0&&!Array.isArray(F.steps))throw Error(`\`branches[${U}].steps\` must be an array when calling \`insert_sequence_step\`.`);let P=L(F,"targetNodeId"),k=Array.isArray(F.steps)&&F.steps.length>0;if(!P&&!k&&!H)throw Error(`\`branches[${U}]\` must provide \`targetNodeId\` or non-empty \`steps\` when inserting \`logic_branch\` with \`insert_sequence_step\`.`);return Object.fromEntries(Y.flatMap((S)=>F[S]===void 0?[]:[[S,F[S]]]))});if(w.elseSteps!==void 0&&!Array.isArray(w.elseSteps))throw Error("`elseSteps` must be an array when calling `insert_sequence_step`.");let B=L(w,"elseTargetNodeId"),A=Array.isArray(w.elseSteps)&&w.elseSteps.length>0;if(!B&&!A&&!H)throw Error("Provide `elseTargetNodeId` or non-empty `elseSteps` when inserting `logic_branch` with `insert_sequence_step`.");return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},branch:{afterNodeId:G,...L(w,"label")?{label:L(w,"label")}:{},branches:z,...Array.isArray(w.elseSteps)?{elseSteps:w.elseSteps}:{},...B?{elseTargetNodeId:B}:{},...H?{allowEmptyPaths:!0}:{}}}}if(b==="delay"||b==="create_discount"||b==="update_subscriber"||b==="condition"||b==="add_tag"||b==="remove_tag"||b==="add_to_list"||b==="remove_from_list"||b==="webhook"){let G;if(b==="delay"){G={type:"delay"};for(let H of["delay","delayMs","waitUntil"])if(w[H]!==void 0)G[H]=w[H];if(G.delay===void 0&&G.delayMs===void 0&&G.waitUntil===void 0)throw Error("Provide `delay`, `delayMs`, or `waitUntil` when inserting a delay step.")}else if(b==="create_discount"){G={type:"create_discount"};for(let H of["discount","label","provider","discountType","percentOff","amountOff","currency","duration","durationInMonths","appliesToAllPlans","planIds","codePrefix","maxRedemptions","lockToSubscriber","expiresAt","expiresInHours"])if(w[H]!==void 0)G[H]=w[H]}else if(b==="update_subscriber"){if(!C(w.config))throw Error("`config` is required when inserting an update_subscriber step.");G={type:"update_subscriber",nodeType:"action_update_attributes",config:w.config}}else if(b==="webhook"){let H=L(w,"method")??"POST";if(!["POST","GET","PUT","PATCH","DELETE"].includes(H))throw Error("`method` must be one of POST, GET, PUT, PATCH, or DELETE when inserting a webhook step.");if(w.headers!==void 0&&(!C(w.headers)||Object.values(w.headers).some((F)=>typeof F!=="string")))throw Error("`headers` must be an object with string values when inserting a webhook step.");let z=L(w,"onError");if(z&&!["continue","exit","fail"].includes(z))throw Error("`onError` must be `continue`, `exit`, or `fail` when inserting a webhook step.");if(w.body!==void 0&&typeof w.body!=="string")throw Error("`body` must be a JSON string when inserting a webhook step.");if(w.resultKey!==void 0&&typeof w.resultKey!=="string")throw Error("`resultKey` must be a string when inserting a webhook step.");let B=L(w,"body"),A=L(w,"resultKey");G={type:"webhook",nodeType:"action_webhook",config:{label:L(w,"label")??"Webhook",url:Z("insert_sequence_step",w,"url"),method:H,...w.headers!==void 0?{headers:w.headers}:{},...B?{body:B}:{},...A?{resultKey:A}:{},...z?{onError:z}:{}}}}else if(b==="condition"){let H=Z("insert_sequence_step",w,"conditionType");if(!new Set(["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"]).has(H))throw Error("`conditionType` is not supported for condition steps.");if((H==="has_tag"||H==="does_not_have_tag")&&!L(w,"tagId")&&!L(w,"tagName"))throw Error("Provide `tagId` or `tagName` for this condition step.");if(H==="in_list"&&!L(w,"listId"))throw Error("`listId` is required for an in_list condition.");if(H==="in_segment"&&!L(w,"segmentId"))throw Error("`segmentId` is required for an in_segment condition.");if(H==="event_received"&&!L(w,"eventName"))throw Error("`eventName` is required for an event_received condition.");if(H.startsWith("field_")&&(!L(w,"fieldName")||!L(w,"fieldValue")))throw Error("`fieldName` and `fieldValue` are required for field conditions.");let B={label:L(w,"label")??"Condition",conditionType:H};for(let A of["tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"])if(w[A]!==void 0)B[A]=w[A];G={type:"condition",nodeType:"logic_condition",config:B}}else{let H=b==="add_tag"||b==="remove_tag",z=b==="add_tag"?"action_add_tag":b==="remove_tag"?"action_remove_tag":b==="add_to_list"?"action_add_to_list":"action_remove_from_list",B={label:L(w,"label")??(b==="add_tag"?"Add Tag":b==="remove_tag"?"Remove Tag":b==="add_to_list"?"Add to List":"Remove from List")};if(H){let A=L(w,"tagId"),F=L(w,"tagName");if(!A&&!F)throw Error("Provide `tagId` or `tagName` when inserting a tag action.");if(A)B.tagId=A;if(F)B.tagName=F}else{B.listId=Z("insert_sequence_step",w,"listId");let A=L(w,"listName");if(A)B.listName=A}G={nodeType:z,config:B}}for(let H of["delay","delayMs","waitUntil"])if(b!=="delay"&&w[H]!==void 0)G[H]=w[H];let J={steps:[G]},Y=L(w,"afterNodeId");if(Y)J.afterNodeId=Y;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:J}}let W=b==="sms",Q;if(W){p9("insert_sequence_step","SMS step",w);let G=L(w,"text"),J=Array.isArray(w.blocks)&&w.blocks.length>0;if(G===void 0&&!J)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");Q={type:"sms"};for(let Y of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(w[Y]!==void 0)Q[Y]=w[Y]}else{Cw("insert_sequence_step",w,{requireContent:!0}),b4("insert_sequence_step","email step",w),Q={subject:Z("insert_sequence_step",w,"subject")};for(let G of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","isTransactional","ccEmails","bccEmails","attachments"])if(w[G]!==void 0)Q[G]=w[G]}let X={steps:[Q]};if(w.afterNodeId!==void 0)X.afterNodeId=w.afterNodeId;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:X}}function z5(w,b){let $=w[b];if($===void 0)return[];if(!Array.isArray($))throw Error(`\`${b}\` must be an array when calling \`cancel_sequence_enrollments\`.`);let W=$.map((Q)=>typeof Q==="string"?Q.trim():"").filter((Q)=>Q.length>0);if($.some((Q)=>typeof Q!=="string")||W.length===0)throw Error(`\`${b}\` must contain at least one non-empty string when calling \`cancel_sequence_enrollments\`.`);return W}function U5(w){let b=L(w,"subscriberId"),$=z5(w,"subscriberIds"),W=z5(w,"fieldValues");if(w.cancelAll!==void 0&&typeof w.cancelAll!=="boolean")throw Error("`cancelAll` must be a boolean when calling `cancel_sequence_enrollments`.");let Q=w.cancelAll===!0;if((b!==void 0?1:0)+($.length>0?1:0)+(W.length>0?1:0)+(Q?1:0)!==1)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `cancelAll`, `subscriberId`, `subscriberIds`, or `fieldValues`.");let G=L(w,"fieldPath"),J=L(w,"reason");return{...Q&&{cancelAll:!0},...b!==void 0&&{subscriberId:b},...$.length>0&&{subscriberIds:$},...G!==void 0&&{fieldPath:G},...W.length>0&&{fieldValues:W},...typeof w.dryRun==="boolean"&&{dryRun:w.dryRun},...J!==void 0&&{reason:J}}}function K5(w){Cw("create_campaign",w),L1("create_campaign",w);let b=L(w,"prompt")!==void 0,$=w.html!==void 0,W=w.blocks!==void 0,Q=w.templateId!==void 0;if(w.prompt!==void 0&&!b)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(b&&($||W||Q))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!b&&(w.style!==void 0||w.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!b&&L(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function O5(w){Cw("create_template",w),L1("create_template",w);let b=L(w,"prompt")!==void 0,$=[b,w.html!==void 0,w.blocks!==void 0].filter(Boolean).length;if(w.prompt!==void 0&&!b)throw Error("`prompt` cannot be empty when calling `create_template`.");if($!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!b&&(w.style!==void 0||w.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!b&&L(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function Z5(w){if(L(w,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(w.targetLists!==void 0&&!C(w.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(w.sendTimeOptimization!==void 0){if(typeof w.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(w.spreadOverHours!==void 0){if(typeof w.spreadOverHours!=="number"||!Number.isInteger(w.spreadOverHours)||w.spreadOverHours<1||w.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(w.recurringInterval!==void 0&&w.recurringInterval!=="weekly"&&w.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function $4(w,b,$){let W=new Set(["companyId","landingPageId","name","slug","content"]),Q=Object.keys(b).filter((X)=>!W.has(X));if(Q.length>0)throw Error(`\`${w}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${Q.length===1?"":"s"}: ${Q.map((X)=>`\`${X}\``).join(", ")}.`);if($.requireUpdate&&b.name===void 0&&b.slug===void 0&&b.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${w}\`.`);return{...b.name!==void 0&&{name:b.name},...b.slug!==void 0&&{slug:b.slug},...b.content!==void 0&&{content:b.content}}}function M5(w){let b=new Set(["companyId","domain","verify"]),$=Object.keys(w).filter((W)=>!b.has(W));if($.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}.`);if(w.domain===void 0&&w.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...w.domain!==void 0&&{domain:w.domain},...typeof w.verify==="boolean"&&{verify:w.verify}}}function V5(w){Cw("create_transactional_email",w);let b=L(w,"prompt")!==void 0,$=w.html!==void 0,W=w.blocks!==void 0;if(w.prompt!==void 0&&!b)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(b&&($||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!b&&(w.style!==void 0||w.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!b&&!$&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!b&&L(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var L0={type:"object",description:"Update Subscriber config. firstName, lastName, and customAttributeUpdates values may use trigger-event merge tags such as {{event.plan}}. Number and boolean values must be a literal or one standalone merge tag and are coerced after resolution.",properties:{label:{type:"string"},firstName:{type:["string","null"],description:"First name literal or merge tag; null clears the field."},lastName:{type:["string","null"],description:"Last name literal or merge tag; null clears the field."},status:{type:"string",enum:["active","unsubscribed","bounced"]},customAttributeUpdates:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:["string","number","boolean","null"],description:"Literal scalar, null to delete, or a standalone merge tag such as {{event.plan}}, {{event.amount}}, or {{event.active}}."},valueType:{type:"string",enum:["text","number","boolean"]}},required:["name","value"]}}},additionalProperties:!0},sV={type:"object",description:"Config for advanced nodeType steps. Required fields depend on nodeType: action_add_tag and action_remove_tag need tagId or tagName; action_add_to_list and action_remove_from_list need listId; action_update_attributes uses the Update Subscriber fields (firstName, lastName, status, customAttributeUpdates) and may use trigger-event merge tags; logic_wait_for_event needs eventName plus optional timeoutDays and timeoutAction; logic_condition needs conditionType plus that condition's resource field; action_webhook needs an HTTPS url plus optional method, headers, body, resultKey, and onError; logic_delay uses delayDays/delayHours/delayMinutes. Fields that do not apply to the node type are dropped.",properties:{...L0.properties,tagId:{type:"string",description:"action_add_tag / action_remove_tag: tag ID. Pass a name in tagName instead, because tag actions resolve tagId by ID only. has_tag / does_not_have_tag also accept a tag name here. Missing tag definitions are created automatically."},tagName:{type:"string",description:"action_add_tag / action_remove_tag / has_tag / does_not_have_tag: tag name. Use instead of tagId when you only know the name."},listId:{type:"string",description:"action_add_to_list / action_remove_from_list / in_list: list ID. It must match an existing list in this company; listName is filled in for you."},listName:{type:"string",description:"Optional cached list display name for list actions."},eventName:{type:"string",description:"logic_wait_for_event and event_received conditions: event to wait for or check, for example email.replied."},timeoutDays:{type:"number",description:"logic_wait_for_event: maximum wait in whole days from 1 to 365. Defaults to 7."},timeoutAction:{type:"string",enum:["continue","exit"],description:"logic_wait_for_event: continue to the next node or exit the sequence when the timeout is reached. Defaults to continue."},conditionType:{type:"string",enum:["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"logic_condition: condition evaluated before continuing. has_phone and sms_subscribed need no resource fields."},segmentId:{type:"string",description:"logic_condition: segment ID for in_segment."},segmentName:{type:"string",description:"Optional cached segment display name."},linkUrl:{type:"string",description:"logic_condition: optional URL substring for link_clicked. Omit to match any tracked click."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"logic_condition: scope for event_received and link_clicked. Use this_sequence to restrict activity to the current enrollment."},fieldName:{type:"string",description:"logic_condition: subscriber attribute name/path for field comparisons."},fieldValue:{type:"string",description:"logic_condition: comparison value for field comparisons."},url:{type:"string",description:"action_webhook: destination HTTPS URL called when a subscriber reaches this step. Supports merge tags like {{email}} and {{event.order_id}} resolved at execution time."},method:{type:"string",enum:["POST","GET","PUT","PATCH","DELETE"],description:"action_webhook: HTTP method. Defaults to POST."},headers:{type:"object",description:"action_webhook: optional string-valued request headers. Values support merge tags. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},body:{type:"string",description:'action_webhook: optional JSON body template for POST/PUT/PATCH. Must be valid JSON as written, with merge tags inside quoted string values ({"email": "{{email}}"}); a tag in a bare value position is rejected. Tags are resolved at execution time; when omitted, the default payload with subscriber and sequence context is sent.'},resultKey:{type:"string",description:"action_webhook: when set, the HTTP response is saved and later email steps can reference it via {{webhooks.KEY.data.field}} merge tags. Must start with a letter; letters, numbers, underscores; max 64 chars."},onError:{type:"string",enum:["continue","exit","fail"],description:"action_webhook: behavior when the request fails. continue proceeds to the next step, exit ends the sequence for the subscriber, fail marks the enrollment failed (default)."},delayDays:{type:"number",description:"logic_delay: whole days to wait."},delayHours:{type:"number",description:"logic_delay: hours to wait."},delayMinutes:{type:"number",description:"logic_delay: minutes to wait."}},additionalProperties:!0},Ob={senderProfileId:{type:"string",description:"Sender profile for this step's From identity. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"From address for this step. Its domain must be configured and verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this step. Alone it only changes the visible name; with fromEmail it also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this step's Reply-To. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Reply-To address for this step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."}},Zb={type:"object",description:"A typed step to create inside a sequence path, including email, SMS, delay, discount, subscriber actions, conditions, waits, and webhooks.",properties:{type:{type:"string",enum:["email","sms","delay","create_discount","discount","update_subscriber","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for fixed/date waits or update_subscriber for action_update_attributes. For an event gate, use nodeType:'logic_wait_for_event' with an explicit config object."},nodeType:{type:"string",enum:["logic_delay","action_email","action_sms","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","logic_condition","action_webhook"],description:"Advanced sequence path node type. Prefer type unless creating a non-email action. Tag, list, subscriber-update, wait, condition, and webhook node types carry their fields in config, for example nodeType:'action_add_tag' with config:{ tagName:'newsletter-confirmed' }. SMS steps still use the step-level text/imageUrls/ineligibleAction, discount steps the step-level discount fields, and delays the step-level delay/delayMs/waitUntil."},config:sV,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:H0,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},isTransactional:{type:"boolean",description:"Email only: omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses CC'd on this step."},bccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses BCC'd on this step in addition to sequence BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"Email only: URL-backed file attachments (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time."},text:{type:"string",description:"SMS only: plain-text message body."},imageUrls:{type:"array",items:{type:"string"},description:"SMS only: up to two public MMS image URLs."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS only: behavior when the contact cannot receive SMS."},delay:D0,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:z0,name:{type:"string",description:"Email template name for email steps."},senderProfileId:{type:"string",description:"Sender profile for this email step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"From address for this email step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this email step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this email step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},replyTo:{type:"string",description:"Reply-To address for this email step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},discount:{type:"object",description:`Discount configuration for create_discount steps. Same shape as create_sequence steps.${d6}`,additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use stripe to dynamically create a Stripe coupon plus promotion code, or shopify to dynamically create a Shopify Admin discount code."},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1},d9={type:"object",properties:{id:{type:"string",description:"Optional stable path ID. Defaults to branch-0, branch-1, and so on. The value 'else' is reserved."},label:{type:"string",description:"Display label, for example 'Replied in this sequence'."},conditionType:{type:"string",enum:["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"Condition for this path. has_phone and sms_subscribed need no resource fields."},tagName:{type:"string",description:"Tag name for has_tag and does_not_have_tag. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag and does_not_have_tag."},listId:{type:"string",description:"List ID for in_list."},segmentId:{type:"string",description:"Segment ID for in_segment."},segmentName:{type:"string",description:"Optional display name for in_segment."},eventName:{type:"string",description:"Event name for event_received, for example email.replied."},linkUrl:{type:"string",description:"Optional URL substring for link_clicked. Omit to match any tracked click."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"Scope for event_received and link_clicked. Use this_sequence to restrict activity to the current enrollment."},fieldName:{type:"string",description:"Subscriber attribute name/path for field conditions."},fieldValue:{type:"string",description:"Comparison value for field conditions."},targetNodeId:{type:"string",description:"Optional existing node to route this branch path to. Use a node ID from get_sequence, including the sequence completion node when this path should stop. If steps are also provided, they run before this target."},steps:{type:"array",description:"Optional new steps for this path. When targetNodeId is also set, the last new step connects to that existing node.",items:Zb}},required:["conditionType"],additionalProperties:!1};function j5(w){if(!w||typeof w!=="object")return null;let b=w;if(b.success!==!1)return null;if(typeof b.error==="string")return Error(b.error);if(b.error&&typeof b.error==="object"&&typeof b.error.message==="string")return Error(b.error.message);if(typeof b.message==="string")return Error(b.message);return Error("The tool returned an unsuccessful response.")}var q5=1000,eV=1000;function o9(w){return w.trim().toLowerCase().replace(/\s+/g,"-")}function aV(w){let b=new URLSearchParams;if(typeof w.query==="string"&&w.query.trim()!=="")b.set("query",w.query.trim());if(Array.isArray(w.tags)&&w.tags.length>0)b.set("tags",w.tags.filter(($)=>typeof $==="string"&&$.trim()!=="").join(","));if(typeof w.list==="string"&&w.list.trim()!=="")b.set("list",w.list.trim());if(typeof w.listId==="string"&&w.listId.trim()!=="")b.set("listId",w.listId.trim());if(typeof w.listName==="string"&&w.listName.trim()!=="")b.set("listName",w.listName.trim());if(typeof w.segmentId==="string"&&w.segmentId.trim()!=="")b.set("segmentId",w.segmentId);if(typeof w.status==="string"&&w.status.trim()!=="")b.set("status",w.status.trim());if(w.cursor)b.set("cursor",w.cursor);else b.set("page",String(w.page));if(b.set("limit",String(w.pageSize)),w.includeTotal===!1)b.set("includeTotal","false");return b}async function I5(w,b){let $=typeof w.limit==="number"&&Number.isFinite(w.limit)?Math.max(1,Math.trunc(w.limit)):void 0,W=Math.min(q5,Math.max(1,$??q5)),Q=[],X=1,G,J=0,Y=0,H=0;while(!0){let B=aV({query:w.query,tags:w.tags,list:w.list,listId:w.listId,listName:w.listName,segmentId:w.segmentId,status:w.status,page:X,pageSize:W,cursor:G}),A=await D("GET",`/api/v1/subscribers?${B.toString()}`,void 0,b);if(H===0)J=A.pagination?.total??A.subscribers.length,Y=A.pagination?.totalPages??1;H+=1,Q.push(...A.subscribers??[]);let F=(A.subscribers??[]).length,U=A.pagination?.nextCursor??void 0,V=$!==void 0&&Q.length>=$,q;if(U)q=!1;else if(A.pagination?.hasMore!==void 0)q=!A.pagination.hasMore;else if(A.pagination?.totalPages!==void 0&&A.pagination.totalPages!==null)q=X>=A.pagination.totalPages;else q=F<W;if(V||q||F===0||H>=eV)break;if(U)G=U;else X+=1}if(J===0&&Q.length>0)J=Q.length;let z=$!==void 0?Q.slice(0,$):Q;return{success:!0,subscribers:z,pagination:{page:1,limit:W,total:J,totalPages:Y,fetchedPages:H},returned:z.length,truncated:$!==void 0&&J>0&&z.length<J}}function t9(w){let b=typeof w.email==="string"&&w.email.trim()!==""?w.email.trim():void 0,$=typeof w.externalId==="string"&&w.externalId.trim()!==""?w.externalId.trim():void 0;return{...b?{email:b}:{},...$?{externalId:$}:{}}}function ow(w,b){let $=t9(b);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${w}\`.`);return $}function W4(w,b){let $=new URLSearchParams;if(b?.includeMachineEngagement)$.set("includeMachineEngagement","true");let W=$.toString(),Q=W?`?${W}`:"";if(w.email)return`/api/v1/subscribers/${encodeURIComponent(w.email)}${Q}`;return $.set("externalId",String(w.externalId)),`/api/v1/subscribers/external?${$.toString()}`}function r9(w){if(w.email)return`/api/v1/subscribers/${encodeURIComponent(w.email)}/notes`;let b=new URLSearchParams;return b.set("externalId",String(w.externalId)),`/api/v1/subscribers/external/notes?${b.toString()}`}async function Mb(w,b,$){return D("GET",W4(w,$),void 0,b)}function n(w,b,$,W){let Q=L(b,$);if(Q===void 0)return;if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${w}\`.`);return Q}function Vb(w,b,$,W){let Q=Z(w,b,$);if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${w}\`.`);return Q}function Bw(w,b,$,W,Q){let X=b[$];if(X===void 0)return;if(typeof X!=="number"||!Number.isInteger(X)||X<W||X>Q)throw Error(`\`${$}\` must be an integer between ${W} and ${Q} when calling \`${w}\`.`);return X}function wj(w,b){let $=[],W=n(w,b,"eventType",Ub);if(W)$.push(W);if(b.eventTypes!==void 0){if(!Array.isArray(b.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${w}\`.`);b.eventTypes.forEach((Q,X)=>{if(typeof Q!=="string")throw Error(`\`eventTypes\` item ${X+1} must be a string when calling \`${w}\`.`);let G=Q.trim();if(!Ub.includes(G))throw Error(`\`eventTypes\` item ${X+1} must be one of ${Ub.join(", ")} when calling \`${w}\`.`);$.push(G)})}return[...new Set($)]}function s9(w,b){let $=new URLSearchParams,W=wj(w,b);if(W.length>0)$.set("eventTypes",W.join(","));let Q=n(w,b,"period",["1h","24h","7d","30d","90d"]);if(Q)$.set("period",Q);let X=L(b,"start");if(X)$.set("start",X);let G=L(b,"end");if(G)$.set("end",G);let J=Bw(w,b,"page",1,1e6);if(J!==void 0)$.set("page",String(J));let Y=Bw(w,b,"limit",1,500);if(Y!==void 0)$.set("limit",String(Y));if(b.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function e9(w,b){if(b.events===void 0)return;if(!Array.isArray(b.events))throw Error(`\`events\` must be an array when calling \`${w}\`.`);let $=b.events.map((W,Q)=>{if(typeof W!=="string"||!A0.includes(W))throw Error(`\`events\` item ${Q+1} must be one of ${A0.join(", ")} when calling \`${w}\`.`);return W});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${w}\`.`);return $}function a9(w,b){if(!Array.isArray(b.emails))throw Error(`\`emails\` must be an array when calling \`${w}\`.`);let $=[];if(b.emails.forEach((W,Q)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${Q+1} must be a string when calling \`${w}\`.`);let X=W.trim();if(X.length>0)$.push(X)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${w}\`.`);if($.length>C9)throw Error(`\`emails\` must include no more than ${C9} email addresses when calling \`${w}\`. Split larger batches into multiple calls.`);return $}function P5(w,b,$,W){let Q=b[$];if(Q===void 0)return;if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array when calling \`${w}\`.`);let X=[];if(Q.forEach((G,J)=>{if(typeof G!=="string")throw Error(`\`${$}\` item ${J+1} must be a string when calling \`${w}\`.`);let Y=G.trim();if(Y.length>0)X.push(Y)}),X.length===0)throw Error(`\`${$}\` must include at least one ${W} when calling \`${w}\`.`);return X}function N5(w){let $=P5("enroll_subscribers_in_sequence",w,"emails","email address"),W=P5("enroll_subscribers_in_sequence",w,"subscriberIds","subscriber ID"),Q=($?.length??0)+(W?.length??0);if(Q===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(Q>k9)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${k9} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let X=L(w,"targetNodeId");return{...$!==void 0&&{emails:$},...W!==void 0&&{subscriberIds:W},...X!==void 0&&{targetNodeId:X}}}import{readFileSync as bj,statSync as $j}from"node:fs";import{basename as Wj}from"node:path";var Qj={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function Xj(w){let b=w.split(".").pop()?.toLowerCase()??"";return Qj[b]??null}var Gj=104857600;async function E5(w,b){if(!Pb())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let $=Xj(w);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=$j(w).size;if(W>Gj)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let Q=bj(w),X=await D("POST","/api/v1/products/delivery/upload-url",{filename:Wj(w),contentType:$,fileSizeBytes:W},b),G=await fetch(X.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:Q});if(!G.ok)throw Error(`File upload failed (${G.status})`);return{url:X.publicUrl,fileName:X.fileName,fileSizeBytes:W,mimeType:$}}async function Q4(w){let b=L(w,"companyId");if(b)return b;let $=K1();if($)return $;try{return(await D("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function jb(w,b){let $=await Q4(b);if(!$)throw Error(`A company is required when calling \`${w}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function K0(w,b){if(!C(w)||!b)return w;return{...w,url:b}}function T5(w,b){if(!C(w))return w;return{...w,...b.campaign!==void 0&&{url:b.campaign},...b.campaignPreview!==void 0&&{previewUrl:b.campaignPreview}}}function U0(w,b,$){if(!Array.isArray(w)||!b)return w;return w.map((W)=>{if(!C(W))return W;let Q=L(W,"id");if(!Q)return W;let X=B1({companyId:b,...$==="campaign"&&{campaignId:Q},...$==="landingPage"&&{landingPageId:Q},...$==="sequence"&&{sequenceId:Q},...$==="template"&&{emailId:Q},...$==="transactional"&&{transactionalId:Q},...$==="emailSend"&&{emailSendId:Q}});if($==="campaign")return T5(W,X.urls);let G=$==="sequence"?X.urls.sequence:$==="landingPage"?X.urls.landingPage:$==="template"?X.urls.email:$==="transactional"?X.urls.transactionalEmail:X.urls.emailSend;return K0(W,G)})}function Jj(w){if(!Array.isArray(w))return w;return w.map((b)=>{if(!C(b))return b;let $=L(b,"id");if(!$)return b;let W=B1({companyId:$});return{...b,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var wW=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","list_email_sends","create_campaign","update_campaign","schedule_campaign","unschedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","duplicate_landing_page","delete_landing_page","list_sequences","get_sequence","send_sequence_test_email","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","update_ab_test","list_templates","get_template","create_template","update_template","set_template_localization","sync_template_localizations","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function R5(w,b,$){if(!C($)||!wW.has(w))return $;let W=C($.company)?$.company:void 0,X=L($,"selectedCompanyId")??L($,"currentCompanyId")??L($,"companyId")??(W?L(W,"id"):void 0)??(W?L(W,"companyId"):void 0)??await Q4(b);if(!X)return $;let G=C($.campaign)?$.campaign:void 0,J=C($.sequence)?$.sequence:void 0,Y=C($.landingPage)?$.landingPage:void 0,H=C($.template)?$.template:void 0,z=C($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,B={companyId:X,campaignId:L(b,"campaignId")??L($,"campaignId")??(G?L(G,"id"):void 0),landingPageId:L(b,"landingPageId")??L($,"landingPageId")??(Y?L(Y,"id"):void 0),sequenceId:L(b,"sequenceId")??L($,"sequenceId")??(J?L(J,"id"):void 0),emailId:L($,"templateId")??(H?L(H,"id"):void 0)??(z?L(z,"emailId"):void 0)??L(b,"templateId"),transactionalId:L(b,"transactionalId")??(z?L(z,"id"):void 0)??L(b,"idOrSlug"),emailSendId:L(b,"emailSendId")??L($,"emailSendId")??(C($.emailSend)?L($.emailSend,"id"):void 0),status:L(b,"status")},A=B1(B),F=W?B1({companyId:X}):void 0;return{...$,...Array.isArray($.companies)&&{companies:Jj($.companies)},...Array.isArray($.campaigns)&&{campaigns:U0($.campaigns,X,"campaign")},...Array.isArray($.landingPages)&&{landingPages:U0($.landingPages,X,"landingPage")},...Array.isArray($.sequences)&&{sequences:U0($.sequences,X,"sequence")},...Array.isArray($.templates)&&{templates:U0($.templates,X,"template")},...Array.isArray($.transactional)&&{transactional:U0($.transactional,X,"transactional")},...Array.isArray($.emailSends)&&{emailSends:U0($.emailSends,X,"emailSend")},...W&&F!==void 0&&{company:{...W,url:F.urls.dashboard,settingsUrl:F.urls.settings}},...G&&A.urls.campaign!==void 0&&{campaign:T5(G,A.urls)},...J&&A.urls.sequence!==void 0&&{sequence:K0(J,A.urls.sequence)},...Y&&A.urls.landingPage!==void 0&&{landingPage:K0(Y,A.urls.landingPage)},...H&&A.urls.email!==void 0&&{template:K0(H,A.urls.email)},...z&&A.urls.transactionalEmail!==void 0&&{transactional:K0(z,A.urls.transactionalEmail)},...C($.emailSend)&&A.urls.emailSend!==void 0&&{emailSend:K0($.emailSend,A.urls.emailSend)},appUrls:A.urls}}import{readFileSync as Yj,statSync as Hj}from"node:fs";import{basename as zj,extname as v5}from"node:path";var $W=5242880,Dj=Math.ceil($W/3)*4,Bj=Math.ceil(Dj*1.05)+256,C5={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},Aj=new Set(Object.values(C5));function bW(w){return w?.split(";")[0]?.trim().toLowerCase()||void 0}function Fj(w){return C5[v5(w).toLowerCase()]}function Lj(w){let b=v5(w);return(b?w.slice(0,-b.length):w).replace(/[-_]+/g," ").trim()||"Image"}function Uj(w){if(w.length>Bj)throw Error("Image assets must be 5MB or smaller.")}function Kj(w){let b=0,$=0;for(let Q=0;Q<w.length;Q+=1){let X=w.charCodeAt(Q);if(X===9||X===10||X===11||X===12||X===13||X===32)continue;b+=1,$=X===61?$+1:0}if(Math.floor(b*3/4)-Math.min($,2)>$W)throw Error("Image assets must be 5MB or smaller.")}function Oj(w){Uj(w);let b=w.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(b),W=$?.[2]??b;Kj(W);let Q=W.replace(/\s+/g,"");if(Q.length===0||Q.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(Q))throw Error("`imageBase64` must contain valid base64 image bytes.");return{bytes:Buffer.from(Q,"base64"),...$?.[1]?{dataUrlContentType:bW($[1])}:{}}}function S5(w){if(w<=0)throw Error("The image file is empty.");if(w>$W)throw Error("Image assets must be 5MB or smaller.")}function Zj(w){let b=Fj(w.filename)??bW(w.explicitContentType)??bW(w.dataUrlContentType);if(!b||!Aj.has(b))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return b}function Mj(w){let b,$,W;if(w.filePath!==void 0){if(!Pb())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. For a remote MCP connection, pass `imageBase64` and `filename` instead.");let X=Hj(w.filePath).size;S5(X),b=Yj(w.filePath),$=w.filename??zj(w.filePath)}else{if(!w.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!w.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let X=Oj(w.imageBase64);b=X.bytes,W=X.dataUrlContentType,$=w.filename,S5(b.byteLength)}let Q=Zj({filename:$,explicitContentType:w.contentType,dataUrlContentType:W});return{bytes:b,filename:$,contentType:Q,altText:w.altText??Lj($)}}async function k5(w){let b=Mj(w),$=b.bytes.byteLength,W=await D("POST","/api/v1/media/upload-url",{filename:b.filename,contentType:b.contentType,fileSizeBytes:$},w.companyId);return await VW(W.uploadUrl,b.bytes,b.contentType,w.companyId),(await D("POST","/api/v1/media/complete-upload",{key:W.key,filename:W.fileName,contentType:b.contentType,fileSizeBytes:$,...w.sourceWidth!==void 0&&{width:w.sourceWidth},...w.sourceHeight!==void 0&&{height:w.sourceHeight},altText:b.altText},w.companyId)).asset}var Vj={type:"boolean",description:"Whether the Sequenzy operation succeeded."},O0={type:"string",description:"Human-readable status, confirmation, or next-step message."},x5={type:"string",description:"Additional context about the result."};function E(w){return{type:"object",description:w,additionalProperties:!0}}function k1(w){return{type:"array",description:w,items:E("One item in the returned collection.")}}function M(w){return{type:"string",description:w}}function qb(w){return{type:["object","null"],description:w,additionalProperties:!0}}function b1(w){return{type:["string","null"],description:w}}function c(w){return{type:"number",description:w}}function t(w){return{type:"boolean",description:w}}function j(w){return E(`The ${w} record returned by Sequenzy.`)}function h(w){return k1(`List of ${w} records returned by Sequenzy.`)}var X4="`opened` and `clicked` are unique counts deduplicated by email send (one recipient opening five times counts once), not total open events. Every count is attributed to the sends made inside the requested window, including engagement that arrives after the window ends, so `opened <= delivered <= sent` always holds. Rates use `rateDenominator` (`delivered`, or `sent` when no delivery events were recorded, reported as `rateDenominatorBasis`); `deliveryRate` and `bounceRate` divide by `sent`.",h5="Run state: branch on effectiveStatus (draft, live, enrollment_paused, paused, or archived) rather than on status, which reads `active` even when new enrollments are paused. acceptsNewEnrollments and processesExistingEnrollments answer the two questions behind it, and effectiveStatusSummary is a plain-language sentence. The legacy triggerConfig.active flag is not read by the runtime; it is reported as a mirror of acceptsNewEnrollments.",g1=E(`The sequence record returned by Sequenzy. ${h5}`),jj=k1(`List of sequence records returned by Sequenzy. ${h5}`),G4={effectiveStatus:{type:"string",enum:["draft","live","enrollment_paused","paused","archived"],description:"Resolved run state. The one field to branch on: `status` still reads `active` while new enrollments are paused."},acceptsNewEnrollments:t("Whether new subscribers can enter the sequence right now."),processesExistingEnrollments:t("Whether subscribers already inside the sequence keep advancing and receiving steps."),effectiveStatusSummary:M("One plain-language sentence describing the run state, safe to show a user verbatim.")},_5={...g1,properties:{migratedRecipientCount:c("Recipients moved immediately from deleted steps to their surviving successor."),completedRecipientCount:c("Recipients completed because a deleted step had no surviving successor.")}},qj={appUrls:E("Dashboard URLs for relevant Sequenzy resources."),url:M("Primary dashboard URL for this result."),settingsUrl:M("Company settings URL when available.")},Pj={success:Vj,message:O0,note:x5,warnings:{type:"array",description:"Non-fatal cautions about content, permissions, or follow-up actions.",items:M("One warning.")},items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:E("One returned item.")},value:E("Fallback object wrapper used only when a tool returns a non-object value.")},Ij={get_account:{account:j("account"),companies:h("company"),apiKeyPermissions:E("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:M("Company ID selected by the authenticated API key, when available."),selectedCompanyId:M("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:M("Selected company ID."),companyName:M("Selected company name.")},get_app_urls:{dashboard:M("Company dashboard URL."),settings:M("Company settings URL."),campaign:M("Campaign editor URL."),landingPage:M("Landing page editor URL."),sequence:M("Sequence editor URL."),email:M("Email editor URL."),transactionalEmail:M("Transactional email URL."),emailSend:M("Sent email detail URL."),domain:M("Sending domain settings URL."),urls:E("All generated URLs keyed by resource type.")},create_company:{company:j("company"),autoSelected:t("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:j("company")},get_company:{company:j("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:E("One sync rule.")},isDefault:t("Whether the company uses the inherited SaaS/ecommerce platform preset.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:E("One sync rule.")},isDefault:t("Whether the company now uses the inherited SaaS/ecommerce platform preset.")},get_shopify_automation_settings:{browseAbandonment:E("Effective browse-abandonment settings (defaults applied)."),cartAbandonment:E("Effective cart-abandonment settings (defaults applied)."),priceDrop:E("Effective price-drop settings (defaults applied)."),shopDomain:M("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:E("Effective browse-abandonment settings after the update."),cartAbandonment:E("Effective cart-abandonment settings after the update."),priceDrop:E("Effective price-drop settings after the update."),shopDomain:M("Connected Shopify store domain.")},create_api_key:{apiKey:E("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:M("Newly created API key if the API response uses the short key field.")},list_api_keys:{apiKeys:h("non-secret API key metadata, including ID, name, prefix, permissions, timestamps, and active-credential status")},update_api_key:{apiKey:j("updated non-secret API key metadata, including the `scopes` now in effect (null when the key has full access)")},revoke_api_key:{apiKey:j("revoked non-secret API key metadata")},delete_api_key:{apiKey:j("deleted non-secret API key metadata")},list_websites:{websites:h("sending domain, including DNS verification and readyToSend home-transport readiness")},list_integrations:{integrations:h("connected integration, including provider, provider account ID, active and sync status, last sync time, last sync error, allowlisted non-secret details, and lastSyncSkipped (records the last sync could not import normally: suppressed profiles that cannot receive email, plus any that were not imported). Credentials are never included")},get_integration:{integration:E("The connected integration: provider, display name, category, provider account ID, active and sync status, last sync time and error, and allowlisted non-secret details. Credentials are never included."),capabilities:qb("What this provider does: category, connect method, what it syncs, every event it emits with when it fires, attributes it writes, supported actions, availability, and caveats. Null for a provider with no catalog entry."),events:k1("Each event the provider emits, every matching tag rule and its conditions, listening sequences, and account-wide observation fields. Use activity for integration-specific delivery."),unusedEvents:{type:"array",description:"Events the provider emits that no sequence triggers on. These are the concrete automation gaps for this integration.",items:M("Event name with no listening sequence.")},accountNeverReceivedEvents:{type:"array",description:"Provider event names this account has never received from any source. This is not integration-specific delivery evidence.",items:M("Event name never seen account-wide.")},activity:E("Webhook and sync activity over the last 24 hours: totals by status, stalled count, last activity time, and recent failures."),pixel:qb("Shopify only: live storefront pixel state (installed, endpoint, endpointCurrent, configurationCurrent, healthy, error, dependentEvents). Null for providers without a pixel. When error is null and healthy is false, every dependentEvent is confirmed dark; an error means Shopify could not confirm the state."),recommendations:k1("Prioritized problems and suggestions, each with a code, severity (error, warning, info), message, and a concrete action."),availableActions:{type:"array",description:"Action ids callable on this integration right now, given its current state.",items:M("Available action id.")}},list_integration_capabilities:{providers:h("integration provider, including category, connect method, what it syncs, every event it emits with the moment that triggers it, the subscriber attributes it writes, supported actions, availability, and caveats")},list_integration_activity:{activity:h("integration activity row, including provider, action, status, event type, matched contact, message, and error. Payloads are sanitized, so no credentials appear"),windowHours:{type:"number",description:"Retention window in hours for integration activity."},note:x5},connect_integration:{integration:{type:"object",description:"The connected integration: id, provider, name, providerAccountId, sync state, and safe (non-credential) details."},webhookUrl:M("URL to configure in the provider's webhook settings with the same secret. Always relay this to the user - delivery does not start until it is configured."),revenueSyncQueued:t("Payment providers only: whether the initial revenue backfill was queued."),backfillQueued:t("Affonso only: whether the affiliate backfill was queued."),history:{type:"object",description:"PostHog only: outcome of the optional history import request ({ requested, queued, error }). The webhook connection succeeds even if queueing the import failed."}},set_integration_sync_enabled:{integrationId:M("The integration that was updated."),provider:M("Provider of the updated integration."),syncEnabled:t("Sync state after the update."),changed:t("False when the integration was already in the requested state."),message:O0},get_integration_pixel:{integrationId:M("The Shopify integration inspected."),provider:M("Always `shopify`."),shopDomain:M("Store the pixel was read from."),pixel:E("Live pixel state: installed, id, endpoint it posts to, endpointCurrent (including the supported compatibility route), configurationCurrent (endpoint plus signed connection settings), healthy, and error when Shopify could not confirm."),dependentEvents:{type:"array",description:"Event names that depend on this pixel. They are confirmed unable to arrive only when pixel.error is null and pixel.healthy is false.",items:M("Pixel-dependent event name.")},message:O0},activate_integration_pixel:{integrationId:M("The Shopify integration updated."),provider:M("Always `shopify`."),shopDomain:M("Store the pixel was installed on."),pixel:E("Pixel state after activation."),changed:t("False when the pixel was already installed and reporting to this account."),created:t("True when a new pixel was installed."),updated:t("True when an existing pixel was repointed at this account."),dependentEvents:{type:"array",description:"Event names this pixel enables.",items:M("Pixel-dependent event name.")},message:O0},sync_integration:{integrationId:M("The integration being synced."),provider:M("Provider of the synced integration."),jobId:b1("Background job id for the queued sync, when one was created."),syncStatus:M("Sync status after queueing. Poll get_integration to watch it progress."),message:O0},list_sender_profiles:{senderProfiles:h("sender (From) profile, including the sending domain behind it, its DNS verification status, and whether DNS plus the home transport allow the address to send"),replyProfiles:h("reply-to profile"),defaultSenderProfileId:b1("Company default sender profile ID. Null when no default is set."),defaultReplyProfileId:b1("Company default reply-to profile ID. Null when no default is set.")},update_sender_profile:{senderProfile:j("renamed sender (From) profile, present when type was sender"),replyProfile:j("renamed reply-to profile, present when type was reply"),renamed:t("False when the profile already carried that name, so nothing changed.")},get_notification_preferences:{notificationPreferences:k1("One entry per notification event with its current mode: off, instant, or daily. Every event is always present; an event the user has never configured reports the platform default."),supportedModes:E("Modes each event accepts, keyed by event. campaign_completed does not accept daily."),defaults:E("Mode each event uses when the user has never configured it.")},update_notification_preferences:{notificationPreferences:k1("Every notification event with its mode after the update, not only the events that were changed."),supportedModes:E("Modes each event accepts, keyed by event. campaign_completed does not accept daily."),defaults:E("Mode each event uses when the user has never configured it.")},get_tracking_settings:{tracking:E("Open, click, and unsubscribe tracking flags, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours."),consent:E("Signup consent settings: doubleOptInEnabled, and doubleOptInEmailId for the confirmation email sent to pending contacts (null when double opt-in has never been enabled)."),autoUtm:E("Automatic UTM tagging state and its configured parameters."),trackingDomain:qb("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:E("Inbound reply tracking configuration.")},update_tracking_settings:{message:O0,tracking:E("Open, click, and unsubscribe tracking flags, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours, after the update."),consent:E("Signup consent settings after the update: doubleOptInEnabled, and doubleOptInEmailId for the confirmation email, which is provisioned automatically the first time double opt-in is enabled."),autoUtm:E("Automatic UTM tagging state and its configured parameters, after the update."),trackingDomain:qb("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:E("Inbound reply tracking configuration. Unchanged by this tool; set it with update_company.")},add_website:{website:j("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},add_sending_domain:{website:j("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},check_website:{website:j("sending domain with separate DNS verification and readyToSend home-transport readiness"),ready:t("Whether the sender website is ready."),status:M("Current processing or verification status.")},verify_sending_domain:{website:j("Sending domain with current DNS verification, readyToSend home-transport readiness, SPF, DKIM, and MAIL FROM details."),verified:t("Whether the sending domain passed the fresh DNS verification check. This does not by itself mean SES or MTA is ready."),readyToSend:t("Whether DNS and the selected home transport are both ready for sending."),message:M("Verification result summary.")},get_integration_guide:{guide:j("integration guide"),code:M("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:E("One setup step.")}},add_subscriber:{subscriber:j("subscriber")},create_subscriber_import:{import:j("subscriber import")},get_subscriber_import:{import:j("subscriber import")},update_subscriber:{subscriber:j("subscriber")},remove_subscriber:{subscriber:j("subscriber"),hardDeleted:t("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:j("subscriber")},list_subscriber_notes:{notes:h("subscriber note")},add_subscriber_note:{note:j("subscriber note")},delete_subscriber_note:{id:M("Deleted subscriber note ID."),deleted:t("Whether the subscriber note was deleted.")},trigger_subscriber_event:{subscriber:j("subscriber"),event:j("recorded event with its name and whether the event definition was created"),sideEffectFailures:{type:"array",description:"Sync-rule or automation side effects that failed. The event itself is still recorded.",items:M("One failed side effect.")}},trigger_subscriber_events:{subscriber:j("subscriber"),events:h("recorded event")},bulk_add_subscriber_tags:{tags:{type:"array",description:"Normalized tag names applied to every matched subscriber.",items:M("One tag name.")},requested:c("Identifiers supplied in the request."),matched:c("Existing subscribers resolved."),updated:c("Subscribers whose tags actually changed."),unchanged:c("Subscribers that already carried every tag."),failed:c("Subscribers whose update failed."),notFound:E("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds. These subscribers were NOT created."),failures:h("per-subscriber failure (up to 50)"),triggeredAutomations:t("Whether tag_added sequences were allowed to enroll these contacts.")},bulk_remove_subscriber_tags:{tags:{type:"array",description:"Normalized tag names removed from every matched subscriber.",items:M("One tag name.")},requested:c("Identifiers supplied in the request."),matched:c("Existing subscribers resolved."),updated:c("Subscribers whose tags actually changed."),unchanged:c("Subscribers that did not carry any of the tags."),failed:c("Subscribers whose update failed."),notFound:E("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds."),failures:h("per-subscriber failure (up to 50)")},search_subscribers:{subscribers:h("subscriber"),pagination:E("Pagination metadata."),returned:c("Number of subscribers returned."),truncated:t("Whether the result was truncated by the requested limit.")},list_products:{products:h("product"),pagination:E("Pagination metadata: limit, offset, count (this page), total (whole catalog) and hasMore. Page with offset when hasMore is true.")},upsert_products:{products:h("product"),created:c("Number of products created."),updated:c("Number of products updated.")},delete_product:{productId:M("Deleted product ID.")},attach_product_file:{product:j("product"),delivery:j("digital delivery file")},remove_product_file:{product:j("product")},upload_image_asset:{asset:j("hosted image asset"),imageBlock:E("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:j("product sync job"),jobId:M("Queued product sync job ID.")},list_tags:{tags:h("tag")},create_tag:{tag:j("tag")},update_tag:{tag:j("tag")},delete_tag:{tagId:M("Deleted tag ID.")},list_lists:{lists:h("list")},create_list:{list:j("list")},update_list:{list:j("list")},delete_list:{listId:M("Deleted list ID.")},add_subscribers_to_list:{list:j("list"),added:c("Number of subscribers added to the list."),skipped:c("Number of subscribers skipped.")},remove_subscribers_from_list:{list:j("list"),removed:c("Number of subscribers removed from the list."),skipped:c("Number of subscribers skipped.")},list_segments:{segments:h("segment")},create_segment:{segment:j("segment")},update_segment:{segment:j("segment")},delete_segment:{segmentId:M("Deleted segment ID.")},get_segment_count:{count:c("Number of subscribers matching the segment."),segmentId:M("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:h("audience sync")},list_ad_accounts:{adAccounts:h("ad account")},create_audience_sync:{audienceSync:j("audience sync")},update_audience_sync:{audienceSync:j("audience sync")},delete_audience_sync:{audienceSyncId:M("Deleted audience sync ID.")},sync_audience_now:{audienceSync:j("audience sync"),job:j("audience sync job"),jobId:M("Queued audience sync job ID.")},list_templates:{templates:h("email template")},get_template:{template:j("email template")},create_template:{template:j("email template")},update_template:{template:j("email template")},set_template_localization:{templateId:M("Localized template ID."),localization:j("template localization")},sync_template_localizations:{templateId:M("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:M("One queued locale code.")},queuedVariantCount:c("Number of localized variants queued for translation.")},delete_template:{templateId:M("Deleted template ID.")},list_ab_tests:{abTests:h("A/B test")},get_ab_test:{abTest:j("A/B test")},get_ab_test_stats:{abTest:j("A/B test"),stats:j("A/B test statistics")},restart_ab_test:{abTest:j("A/B test")},update_ab_test_variant:{abTest:j("A/B test"),variant:j("A/B test variant")},update_ab_test:{abTest:j("A/B test")},create_ab_test:{abTest:j("A/B test")},add_ab_test_variant:{abTest:j("A/B test"),variant:j("A/B test variant")},delete_ab_test_variant:{abTest:j("A/B test"),variantId:M("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:M("Deleted A/B test ID.")},list_campaigns:{campaigns:h("campaign"),pagination:E("Campaign page window: `limit`, `offset`, `count` returned in this page, `total` matching the filters, and `hasMore`. Keep calling with an advanced `offset` while `hasMore` is true to enumerate every campaign.")},get_campaign:{campaign:j("campaign")},get_campaign_audience:{campaignId:M("Campaign the audience was resolved for."),campaignName:M("Campaign name."),status:M("Campaign status."),audience:E("Resolved targeting: `type`, a plain-language `summary`, `isUnset` (true when scheduling would fall back to every active subscriber), resolved `lists` and `segments` with names and a `missing` flag, `filters`, `include`/`exclude` rules, and individual subscriber adjustments."),recipientCount:c("Number of subscribers matching the effective targeting right now."),targetLists:qb("Raw stored targeting exactly as persisted on the campaign. Null when targeting has never been set.")},get_email_send:{emailSend:j("email send, including copied-recipient identity and primary email send ID when applicable"),events:h("email delivery event")},list_email_sends:{emailSends:h("email send"),pagination:j("email send pagination"),retentionDays:c("Number of days sent-email rows remain queryable in this collection.")},get_recipient_suppression:{suppression:j("recipient suppression status")},remove_recipient_suppression:{removed:t("Whether stale bounce suppression was removed."),removedLocalBounce:t("Whether the platform-local bounce block was removed."),removedSesRegions:{type:"array",description:"AWS SES regions where a bounce suppression was removed.",items:M("One AWS SES region.")},remainingSuppression:j("recipient suppression status after cleanup")},create_campaign:{campaign:j("campaign")},update_campaign:{campaign:j("campaign")},schedule_campaign:{campaign:j("campaign"),scheduledAt:M("Scheduled send timestamp.")},unschedule_campaign:{campaign:j("draft campaign")},send_test_email:{emailSendId:M("Durable test email delivery ID."),recipientEmail:M("Test email recipient.")},send_test_sms:{smsSendId:M("Created test SMS send ID."),toPhone:M("Normalized E.164 destination phone.")},cancel_campaign:{campaign:j("campaign")},pause_campaign:{campaign:j("campaign")},resume_campaign:{campaign:j("campaign")},delete_campaign:{campaignId:M("Deleted campaign ID.")},duplicate_campaign:{campaign:j("duplicated campaign")},resend_campaign_to_non_openers:{campaign:j("non-opener resend draft campaign"),estimatedNonOpenerCount:c("Estimated number of subscribers who haven't opened the original campaign.")},list_forms:{forms:h("saved form")},create_form:{form:j("saved form"),embed:E("Public action URL plus JavaScript, native form, and fetch snippets.")},update_form:{form:j("saved form"),embed:E("Public action URL plus JavaScript, native form, and fetch snippets (published forms only).")},get_form_embed:{form:j("saved form"),embed:E("Public action URL plus JavaScript, native form, and fetch snippets.")},list_landing_pages:{landingPages:h("landing page")},get_landing_page:{landingPage:j("landing page")},create_landing_page:{landingPage:j("landing page")},update_landing_page:{landingPage:j("landing page")},duplicate_landing_page:{landingPage:j("landing page")},delete_landing_page:{landingPageId:M("Deleted landing page ID.")},publish_landing_page:{landingPage:j("landing page")},unpublish_landing_page:{landingPage:j("landing page")},connect_landing_page_domain:{landingPage:j("landing page"),domain:M("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:j("landing page"),domain:M("Landing page domain.")},list_sequences:{sequences:jj,pagination:E("Sequence page window: `limit` (null when limit and offset were both omitted and every sequence was returned), `offset`, `count` returned in this page, `total` matching the filters, and `hasMore`.")},get_sequence:{sequence:g1},list_sequence_enrollments:{sequenceId:M("Sequence ID these enrollments belong to."),sequenceName:M("Sequence name."),statuses:{type:"array",description:"Enrollment statuses included in this response. Defaults to active and waiting.",items:{type:"string",description:"Enrollment status."}},enrollments:{type:"array",description:"Contact-level enrollments matching the filters, one row per enrollment token.",items:{type:"object",description:"One subscriber's enrollment in this sequence.",properties:{enrollmentId:M("Enrollment token ID. Stable identifier for this one run through the sequence."),sequenceId:M("Sequence ID."),subscriberId:M("Subscriber ID."),email:b1("Subscriber email address. Falls back to the address captured at enrollment when the subscriber record no longer exists, and is null when neither is known."),firstName:b1("Subscriber first name, or null when unset."),lastName:b1("Subscriber last name, or null when unset."),subscriberStatus:b1("Subscriber status (active, unsubscribed, bounced), or null when the subscriber record no longer exists."),status:M("Enrollment status: active, waiting, completed, failed, or cancelled."),currentNodeId:M("Sequence node this enrollment is currently sitting on."),currentNodeType:M("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:M("Current sequence node label or email subject when available."),currentNodeMissing:t("Whether the current node no longer exists in the sequence graph."),enrollmentKey:M("Key that distinguishes concurrent enrollments of the same subscriber in this sequence."),enrollmentStartedAt:M("ISO 8601 timestamp when this enrollment entered the sequence."),waitUntil:b1("ISO 8601 timestamp this enrollment is scheduled to resume, or null when nothing is scheduled."),lastUpdatedAt:M("ISO 8601 timestamp of the last change to this enrollment. For a waiting enrollment this is when it arrived at its current node; the platform does not separately track node entry time."),failedReason:b1("Why this enrollment stopped, for status `failed`. Null for every other status and for failures recorded before this field existed. A reason repeated across enrollments on the same currentNodeId points at that step's configuration or content rather than at the contacts.")},required:["enrollmentId","sequenceId","subscriberId","status","currentNodeId","currentNodeMissing","enrollmentStartedAt"]}},pagination:E("Pagination metadata.")},send_sequence_test_email:{sequenceId:M("Sequence ID."),nodeId:M("Tested sequence email-step node ID."),results:k1("Per-recipient test-send results containing recipientEmail, durable emailSendId, and legacy jobId.")},create_sequence:{sequence:g1,eventTrackingCode:M("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:E("Custom-event endpoint, payload contract, example payload, documentation URL, and get_integration_guide arguments."),requiredEvents:{type:"array",description:"Event names the application or an integration must send.",items:M("One required event name.")}},update_sequence:{sequence:_5},update_sequence_node:{sequence:j("sequence")},update_sequence_nodes:{sequence:j("sequence")},edit_sequence_graph:{sequence:_5},insert_sequence_step:{sequence:j("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for a linear inserted step, including any delay or wait-for-event node.",items:M("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:M("Inserted email template ID.")},insertedEmailCount:c("Number of email steps inserted."),addedBranchNodeId:M("New logic_branch node ID when the inserted step is a branch."),addedBranchPathNodeIds:E("Created path node IDs keyed by branch ID, plus else. Directly wired paths have empty arrays.")},enable_sequence:{sequenceId:M("Sequence ID."),status:M("Stored lifecycle status after the change."),enrollmentPaused:t("Whether new sequence enrollments are paused."),...G4},disable_sequence:{sequenceId:M("Sequence ID."),status:M("Stored lifecycle status after the change."),enrollmentPaused:t("Whether new sequence enrollments are paused."),...G4},duplicate_sequence:{sequence:g1,nodes:h("sequence node"),edges:h("sequence edge")},archive_sequence:{sequence:g1},unarchive_sequence:{sequence:g1},list_sequence_goals:{goals:h("sequence goal")},create_sequence_goal:{goal:j("sequence goal")},update_sequence_goal:{goal:j("sequence goal")},delete_sequence_goal:{goalId:M("Deleted sequence goal ID.")},get_sequence_inbound_webhook:{webhook:j("sequence inbound webhook")},configure_sequence_inbound_webhook:{webhook:j("sequence inbound webhook")},rotate_sequence_inbound_webhook_secret:{webhook:j("sequence inbound webhook")},pause_sequence_enrollments:{sequenceId:M("Sequence ID."),enrollmentPaused:t("Whether new sequence enrollments are paused."),...G4},resume_sequence_enrollments:{sequenceId:M("Sequence ID."),enrollmentPaused:t("Whether new sequence enrollments are paused."),...G4},enroll_subscribers_in_sequence:{sequence:j("sequence"),enrollments:h("sequence enrollment"),enrolled:c("Number of subscribers enrolled."),skipped:c("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequenceId:M("Sequence ID."),dryRun:t("Whether this call only reported matches instead of cancelling them."),target:E("Resolved cancellation target: mode all, subscriber, subscribers (with notFoundSubscriberIds), or field."),matchedCount:c("Active/waiting enrollments matching the target when the request started."),cancelledCount:c("Enrollments cancelled by this call."),remainingCount:c("Enrollments still matching after this call. Repeat the same request while this is above zero."),enrollments:h("sequence enrollment sample (up to 50)"),hasMore:t("Whether more enrollments matched than the returned sample.")},delete_sequence:{sequenceId:M("Deleted sequence ID.")},list_transactional_emails:{transactional:h("transactional email with subject, all-time delivery metrics, and dashboard URL")},get_transactional_email:{transactional:j("transactional email")},create_transactional_email:{transactional:j("transactional email")},update_transactional_email:{transactional:j("transactional email")},delete_transactional_email:{deleted:E("Deleted transactional email: id, slug, name, and emailId of the email content that was kept as a reusable template.")},send_email:{emailSendId:M("Durable email delivery ID."),emailType:{type:"string",enum:["marketing","transactional"],description:"Delivery policy accepted for the queued email."},transactional:j("transactional email")},get_stats:{stats:E(`Account-wide delivery funnel for the requested window. ${X4}`),emailType:M("Applied structural email type filter when one was requested."),commerceForecast:j("Optional background-computed commerce AOV, 12-month customer value, and 90-day revenue forecast. Omitted when no snapshot is available; insufficient_data is returned only after eligibility was evaluated successfully.")},get_campaign_stats:{campaign:j("campaign"),stats:E(`Delivery funnel for this campaign. ${X4}`),clickedLinks:{type:"array",description:"Per-link click breakdown, most clicked first (top 20). Each entry has url, clicks, and percentage (that link's share of every recorded link click). Present only when the campaign has tracked link clicks.",items:E("One clicked link with url/clicks/share.")},polls:{type:"array",description:`Poll and NPS summaries. Each subscriber counts once per campaign poll block using their latest answer to that block; NPS entries include score, average, and promoter/passive/detractor counts. To list the exact historical respondents behind a count, use the summary blockId and the get_campaign_stats campaignId with create_segment. ${C1} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response and may be overwritten by a later poll that reuses the key.`,items:E("One poll or NPS results summary.")},recommendations:E("Product recommendation funnel: impressions, recipients, clicks, clickers, orders, legacy revenueCents, currency-safe revenueByCurrency totals, and topProducts (per-product impressions/clicks). Orders count when a subscriber buys a recommended product within 7 days of clicking it. Present only when the campaign rendered product recommendation blocks.")},get_transactional_stats:{transactional:j("transactional email"),stats:E(`Delivery funnel for this transactional email. ${X4}`),complaints:j("complaint count and rate for the selected transactional email"),clickedLinks:h("clicked link with click count and percentage share"),bounceBreakdown:j("permanent, transient, and undetermined bounce counts plus subtype details"),engagementBreakdown:j("human and machine open and click counts")},get_sequence_stats:{sequence:g1,stats:E(`Delivery funnel across every email step in this sequence. ${X4}`),enrollmentCounts:{type:"object",description:"Live enrollment-token counts for this sequence. Includes only active and waiting enrollments and is always a current snapshot, independent of historical period/start/end filters.",properties:{active:c("Active enrollment count."),waiting:c("Waiting enrollment count."),total:c("Total active plus waiting enrollment count."),byCurrentNode:{type:"array",description:"Live active and waiting enrollment counts grouped by the token's current sequence node.",items:{type:"object",description:"Enrollment counts for one current sequence node.",properties:{currentNodeId:M("Current sequence node ID."),currentNodeType:M("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:M("Current sequence node label or email subject when available."),currentNodeMissing:t("Whether the current node no longer exists in the sequence graph."),active:c("Active enrollment count at this node."),waiting:c("Waiting enrollment count at this node."),total:c("Total active plus waiting enrollment count at this node.")},required:["currentNodeId","currentNodeMissing","active","waiting","total"],additionalProperties:!1}}},required:["active","waiting","total","byCurrentNode"],additionalProperties:!1},enrollmentSkipped:{type:"object",description:"Trigger matches where an unsubscribed or bounced contact could not be enrolled, including the total count and counts grouped by reason. Uses the requested period or start/end range; without an explicit range, this field defaults to the last 30 days.",properties:{count:c("Total skipped sequence enrollments."),byReason:{type:"object",description:"Skipped enrollment counts keyed by reason, such as unsubscribed or bounced.",additionalProperties:c("Skipped enrollment count for this reason.")}},required:["count","byReason"],additionalProperties:!1},recommendations:E("Product recommendation funnel aggregated across the sequence's email nodes: impressions, recipients, clicks, clickers, orders, legacy revenueCents, currency-safe revenueByCurrency totals, and topProducts. Present only when the sequence rendered product recommendation blocks.")},list_campaign_events:{events:h("campaign email event"),pagination:E("Pagination metadata.")},list_sequence_events:{events:h("sequence email event"),pagination:E("Pagination metadata.")},get_subscriber_activity:{activity:h("subscriber activity event"),subscribers:h("subscriber"),pagination:E("Pagination metadata.")},list_team_members:{members:h("team member"),invitations:h("team invitation")},invite_team_member:{invitation:j("team invitation")},cancel_team_invitation:{invitationId:M("Cancelled invitation ID.")},list_conversations:{conversations:h("inbox conversation"),pagination:E("Pagination metadata.")},get_conversation:{conversation:j("inbox conversation"),messages:h("conversation message")},reply_to_conversation:{conversation:j("inbox conversation"),message:j("conversation message")},update_conversation_status:{conversation:j("inbox conversation")},mark_conversation_read:{conversation:j("inbox conversation")},list_webhooks:{webhooks:h("outbound webhook")},create_webhook:{webhook:j("outbound webhook")},update_webhook:{webhook:j("outbound webhook")},delete_webhook:{webhookId:M("Deleted outbound webhook ID.")},test_webhook:{webhook:j("outbound webhook"),delivery:j("test webhook delivery")},list_webhook_deliveries:{deliveries:h("webhook delivery")},replay_webhook_delivery:{delivery:j("webhook delivery"),job:j("webhook replay job")},generate_email:{email:j("generated email"),html:M("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:E("One generated email block.")},subject:M("Generated subject line."),previewText:M("Generated inbox preview text.")},generate_sequence:{sequence:j("persisted AI-generated sequence draft"),deprecated:t("Always true for this deprecated alias."),deprecationMessage:M("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:M("One generated subject line.")},variants:h("generated subject line variant")},generate_sms:{prompt:M("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:E("One generated SMS message.")}},get_sms_settings:{sms:E("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{},render_email:{html:M("Email-safe HTML document, rendered exactly as it would be sent."),subject:M("Subject line with merge tags resolved."),previewText:b1("Inbox preview text with merge tags resolved, or null when unset."),locale:M("Localization locale the render resolved to."),personalized:t("Whether a real contact was supplied. False means a sample contact was used, so contact-specific merge tags resolve to empty values."),trackingApplied:t("Whether auto-UTM link decoration was applied."),unresolvedMergeTags:k1(`Merge tags that rendered as an empty string, as [{ tag, reason }]. reason "unknown" means nothing provides that name, so it stays empty for every recipient - usually a typo or a tag copied from another platform. reason "no_value" means the name is recognized, or could not be checked, but is blank for this contact. A name is only called unknown when the render had a source to check it against. Without the contact's attributes nothing is checkable, since a bare {{plan}} reads the same attribute map as {{subscriber.plan}}, so pass a stored subscriberId or an inline subscriber carrying customAttributes. Beyond that, {{event.*}} needs sample event properties in variables, since a real send fills those from the enrolling event; {{recommendedProducts.*}} needs a stored subscriberId the catalog has something to recommend for; and {{discount.*}} is only checkable on a sequence step whose incoming paths all run the same discount step, never on a standalone template. Rendering a transactional email is checkable only when variables is passed, because its tags come from the variables of each send call and carry no prefix marking them. Otherwise those tags land in no_value rather than in unknown. An optional attribute this contact never had set is kept out of unknown by checking the names other contacts in the account carry, which needs the subscribers:read scope; a key without it may report such a name as unknown. An empty array means every tag in the email resolved.`),entity:E("Which entity was rendered: type, id, and variantId.")}};function Nj(w){let b=Ij[w];if(b===void 0)throw Error(`MCP tool "${w}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${w}\` MCP tool.`,properties:{...Pj,...b,...wW.has(w)?qj:{}},additionalProperties:!0}}function y5(w){return{...w,outputSchema:Nj(w.name)}}function u5(w){if(C(w))return w;if(Array.isArray(w))return{items:w};return{value:w}}var f5=[{name:"list_ab_tests",description:"List A/B tests and their variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Optional sequence ID to filter automation A/B tests."}}}},{name:"get_ab_test",description:"Get A/B test details, variants, and per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"}},required:["abTestId"]}},{name:"get_ab_test_stats",description:"Get A/B test aggregate stats and per-variant stats. Supports period or custom start/end ranges.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},period:{type:"string",description:"Optional period: 1h, 24h, 7d, 30d, or 90d."},start:{type:"string",description:"Custom range start as ISO 8601. Requires end."},end:{type:"string",description:"Custom range end as ISO 8601. Requires start."},includeMachineEngagement:uw},required:["abTestId"]}},{name:"restart_ab_test",description:"Run another sequence A/B test after a winner is selected. By default the winner becomes the new control; pass sourceVariantId to use another variant as the control email.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to restart"},sourceVariantId:{type:"string",description:"Optional variant ID to use as the new control email. Defaults to the selected winner."},testType:{type:"string",description:"Optional test type: subject or content."},winnerThreshold:{type:"number",description:"Optional number of subscribers before selecting a winner. Must be from 10 to 1000."},variantCount:{type:"number",description:"Optional total variants including the control. Must be from 2 to 4."}},required:["abTestId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update an A/B test variant. Campaign variants are editable only in draft. Sequence variants can be edited after activity with confirmLiveChange, but earlier sends stay unchanged and combined results may no longer be accurate. Provide at least one of subject, previewText, html, or blocks. Use either html or blocks, not both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID"},subject:{type:"string",description:"Variant subject line"},previewText:{type:"string",description:"Variant preview text. Pass an empty string to clear it."},html:{type:"string",description:`Replacement HTML body. Mutually exclusive with blocks. ${Yw}`},blocks:{type:"array",description:`${F1}${l1} Mutually exclusive with html.`,items:{type:"object"}},confirmLiveChange:{type:"boolean",description:"Required as true when the sequence is active, the test is no longer a draft, or it has recorded activity. The edit affects future sends and can make combined results inaccurate."}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"update_ab_test",description:"Update A/B test settings. Campaign tests use testPercentage, testDurationMinutes, and winnerCriteria. Sequence tests use testType, winnerThreshold, and winnerCriteria; changing live or already-used sequence settings requires confirmLiveChange. Provide at least one setting.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Campaign-only percentage of the audience used for the test phase, from 5 to 50."},testDurationMinutes:{type:"number",description:"Campaign-only test duration in minutes, from 15 to 1440."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Applies to both campaign and sequence tests."},testType:{type:"string",enum:["subject","content"],description:"Sequence-only variant strategy. When winnerCriteria is omitted, subject defaults to open_rate and content defaults to click_rate."},winnerThreshold:{type:"number",description:"Sequence-only number of recipients before selecting a winner, from 10 to 1000."},confirmLiveChange:{type:"boolean",description:"Required as true when sequence settings affect an active test or a test with recorded activity."}},required:["abTestId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test or convert a sequence email node into a typed A/B test node. Provide exactly one of campaignId or automationNodeId. Control variant A is created automatically from the current email. Campaign tests may add variants later; automationNodeId conversions require at least one variants[] entry to compete with control variant A.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Draft campaign ID. Mutually exclusive with automationNodeId."},automationNodeId:{type:"string",description:"Sequence email-node ID to convert to action_ab_test. Mutually exclusive with campaignId."},confirmLiveChange:{type:"boolean",description:"Required as true when converting an email node in an active sequence."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Campaign-only percentage of the audience used for the test phase, from 5 to 50. Defaults to 20. Sequence tests use winnerThreshold instead."},testDurationMinutes:{type:"number",description:"Campaign-only test phase duration in minutes, from 15 to 1440. Defaults to 240. Sequence tests select after winnerThreshold recipients instead."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Campaign tests default to open_rate. For sequence tests, an explicit value overrides the testType default."},testType:{type:"string",enum:["subject","content"],description:"Sequence A/B test variant strategy. Subject defaults to open_rate and content defaults to click_rate unless winnerCriteria is explicit. Defaults to content."},winnerThreshold:{type:"number",description:"Sequence test sample size from 10 to 1000. Defaults to 100."},variants:{type:"array",maxItems:4,description:"Extra variants to create in addition to control variant A. Optional for campaign tests; automationNodeId conversions require at least one entry.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:`${F1}${l1}`,items:{type:"object"}}},required:["subject"]}}}}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign or sequence A/B test. Sequence variants receive their own editable email template. Variants cannot be added after the test has started. Sequence tests whose parent sequence is active require confirmLiveChange.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:`${F1}${l1}`,items:{type:"object"}},confirmLiveChange:{type:"boolean",description:"Required as true when the A/B test belongs to an active sequence, because new variants immediately enter the live rotation."}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign or sequence A/B test. This cannot be undone. Variant A is the control and cannot be deleted, and the test must keep at least the minimum number of variants. Variants cannot be removed after the test has started. Sequence tests whose parent sequence is active require confirmLiveChange.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID to delete."},confirmLiveChange:{type:"boolean",description:"Required as true when the A/B test belongs to an active sequence, because deletion immediately changes the live rotation."}},required:["abTestId","variantId"]}},{name:"delete_ab_test",description:"Permanently delete a campaign A/B test and all of its variants. This cannot be undone. Running tests (testing or winner_selected) cannot be deleted, and the linked campaign must be in draft or rejected status.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to delete."}},required:["abTestId"]}}];var c5=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. IMPORTANT: If you have access to multiple companies, you MUST either:
29
+ `)}F.write("payload.value = newResult;"),F.write("return payload;");let k=F.compile();return(S,l)=>k(A,S,l)},X,G=x1,J=!Eb.jitless,H=J&&O4.value,z=b.catchall,B;w._zod.parse=(A,F)=>{B??(B=W.value);let U=A.value;if(!G(U))return A.issues.push({expected:"object",code:"invalid_type",input:U,inst:w}),A;if(J&&H&&F?.async===!1&&F.jitless!==!0){if(!X)X=Q(b.shape);if(A=X(A,F),!z)return A;return K8([],U,A,F,B,w)}return $(A,F)}});function kQ(w,b,$,W){for(let X of w)if(X.issues.length===0)return b.value=X.value,b;let Q=w.filter((X)=>!j1(X));if(Q.length===1)return b.value=Q[0].value,Q[0];return b.issues.push({code:"invalid_union",input:b.value,inst:$,errors:w.map((X)=>X.issues.map((G)=>mw(G,W,xw())))}),b}var S4=O("$ZodUnion",(w,b)=>{ww.init(w,b),s(w._zod,"optin",()=>b.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),s(w._zod,"optout",()=>b.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),s(w._zod,"values",()=>{if(b.options.every((Q)=>Q._zod.values))return new Set(b.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),s(w._zod,"pattern",()=>{if(b.options.every((Q)=>Q._zod.pattern)){let Q=b.options.map((X)=>X._zod.pattern);return new RegExp(`^(${Q.map((X)=>I0(X.source)).join("|")})$`)}return});let $=b.options.length===1,W=b.options[0]._zod.run;w._zod.parse=(Q,X)=>{if($)return W(Q,X);let G=!1,J=[];for(let Y of b.options){let H=Y._zod.run({value:Q.value,issues:[]},X);if(H instanceof Promise)J.push(H),G=!0;else{if(H.issues.length===0)return H;J.push(H)}}if(!G)return kQ(J,Q,w,X);return Promise.all(J).then((Y)=>{return kQ(Y,Q,w,X)})}}),Z8=O("$ZodDiscriminatedUnion",(w,b)=>{S4.init(w,b);let $=w._zod.parse;s(w._zod,"propValues",()=>{let Q={};for(let X of b.options){let G=X._zod.propValues;if(!G||Object.keys(G).length===0)throw Error(`Invalid discriminated union option at index "${b.options.indexOf(X)}"`);for(let[J,Y]of Object.entries(G)){if(!Q[J])Q[J]=new Set;for(let H of Y)Q[J].add(H)}}return Q});let W=p1(()=>{let Q=b.options,X=new Map;for(let G of Q){let J=G._zod.propValues?.[b.discriminator];if(!J||J.size===0)throw Error(`Invalid discriminated union option at index "${b.options.indexOf(G)}"`);for(let Y of J){if(X.has(Y))throw Error(`Duplicate discriminator value "${String(Y)}"`);X.set(Y,G)}}return X});w._zod.parse=(Q,X)=>{let G=Q.value;if(!x1(G))return Q.issues.push({code:"invalid_type",expected:"object",input:G,inst:w}),Q;let J=W.value.get(G?.[b.discriminator]);if(J)return J._zod.run(Q,X);if(b.unionFallback)return $(Q,X);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:b.discriminator,input:G,path:[b.discriminator],inst:w}),Q}}),V8=O("$ZodIntersection",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{let Q=$.value,X=b.left._zod.run({value:Q,issues:[]},W),G=b.right._zod.run({value:Q,issues:[]},W);if(X instanceof Promise||G instanceof Promise)return Promise.all([X,G]).then(([Y,H])=>{return _Q($,Y,H)});return _Q($,X,G)}});function T4(w,b){if(w===b)return{valid:!0,data:w};if(w instanceof Date&&b instanceof Date&&+w===+b)return{valid:!0,data:w};if(M1(w)&&M1(b)){let $=Object.keys(b),W=Object.keys(w).filter((X)=>$.indexOf(X)!==-1),Q={...w,...b};for(let X of W){let G=T4(w[X],b[X]);if(!G.valid)return{valid:!1,mergeErrorPath:[X,...G.mergeErrorPath]};Q[X]=G.data}return{valid:!0,data:Q}}if(Array.isArray(w)&&Array.isArray(b)){if(w.length!==b.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let W=0;W<w.length;W++){let Q=w[W],X=b[W],G=T4(Q,X);if(!G.valid)return{valid:!1,mergeErrorPath:[W,...G.mergeErrorPath]};$.push(G.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function _Q(w,b,$){if(b.issues.length)w.issues.push(...b.issues);if($.issues.length)w.issues.push(...$.issues);if(j1(w))return w;let W=T4(b.value,$.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return w.value=W.data,w}var M8=O("$ZodRecord",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{let Q=$.value;if(!M1(Q))return $.issues.push({expected:"record",code:"invalid_type",input:Q,inst:w}),$;let X=[];if(b.keyType._zod.values){let G=b.keyType._zod.values;$.value={};for(let Y of G)if(typeof Y==="string"||typeof Y==="number"||typeof Y==="symbol"){let H=b.valueType._zod.run({value:Q[Y],issues:[]},W);if(H instanceof Promise)X.push(H.then((z)=>{if(z.issues.length)$.issues.push(...X1(Y,z.issues));$.value[Y]=z.value}));else{if(H.issues.length)$.issues.push(...X1(Y,H.issues));$.value[Y]=H.value}}let J;for(let Y in Q)if(!G.has(Y))J=J??[],J.push(Y);if(J&&J.length>0)$.issues.push({code:"unrecognized_keys",input:Q,inst:w,keys:J})}else{$.value={};for(let G of Reflect.ownKeys(Q)){if(G==="__proto__")continue;let J=b.keyType._zod.run({value:G,issues:[]},W);if(J instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(J.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:J.issues.map((H)=>mw(H,W,xw())),input:G,path:[G],inst:w}),$.value[J.value]=J.value;continue}let Y=b.valueType._zod.run({value:Q[G],issues:[]},W);if(Y instanceof Promise)X.push(Y.then((H)=>{if(H.issues.length)$.issues.push(...X1(G,H.issues));$.value[J.value]=H.value}));else{if(Y.issues.length)$.issues.push(...X1(G,Y.issues));$.value[J.value]=Y.value}}}if(X.length)return Promise.all(X).then(()=>$);return $}});var j8=O("$ZodEnum",(w,b)=>{ww.init(w,b);let $=U4(b.entries),W=new Set($);w._zod.values=W,w._zod.pattern=new RegExp(`^(${$.filter((Q)=>Z4.has(typeof Q)).map((Q)=>typeof Q==="string"?Q1(Q):Q.toString()).join("|")})$`),w._zod.parse=(Q,X)=>{let G=Q.value;if(W.has(G))return Q;return Q.issues.push({code:"invalid_value",values:$,input:G,inst:w}),Q}}),q8=O("$ZodLiteral",(w,b)=>{if(ww.init(w,b),b.values.length===0)throw Error("Cannot create literal schema with no valid values");w._zod.values=new Set(b.values),w._zod.pattern=new RegExp(`^(${b.values.map(($)=>typeof $==="string"?Q1($):$?Q1($.toString()):String($)).join("|")})$`),w._zod.parse=($,W)=>{let Q=$.value;if(w._zod.values.has(Q))return $;return $.issues.push({code:"invalid_value",values:b.values,input:Q,inst:w}),$}});var P8=O("$ZodTransform",(w,b)=>{ww.init(w,b),w._zod.parse=($,W)=>{if(W.direction==="backward")throw new j0(w.constructor.name);let Q=b.transform($.value,$);if(W.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((G)=>{return $.value=G,$});if(Q instanceof Promise)throw new W1;return $.value=Q,$}});function xQ(w,b){if(w.issues.length&&b===void 0)return{issues:[],value:void 0};return w}var I8=O("$ZodOptional",(w,b)=>{ww.init(w,b),w._zod.optin="optional",w._zod.optout="optional",s(w._zod,"values",()=>{return b.innerType._zod.values?new Set([...b.innerType._zod.values,void 0]):void 0}),s(w._zod,"pattern",()=>{let $=b.innerType._zod.pattern;return $?new RegExp(`^(${I0($.source)})?$`):void 0}),w._zod.parse=($,W)=>{if(b.innerType._zod.optin==="optional"){let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>xQ(X,$.value));return xQ(Q,$.value)}if($.value===void 0)return $;return b.innerType._zod.run($,W)}}),N8=O("$ZodNullable",(w,b)=>{ww.init(w,b),s(w._zod,"optin",()=>b.innerType._zod.optin),s(w._zod,"optout",()=>b.innerType._zod.optout),s(w._zod,"pattern",()=>{let $=b.innerType._zod.pattern;return $?new RegExp(`^(${I0($.source)}|null)$`):void 0}),s(w._zod,"values",()=>{return b.innerType._zod.values?new Set([...b.innerType._zod.values,null]):void 0}),w._zod.parse=($,W)=>{if($.value===null)return $;return b.innerType._zod.run($,W)}}),E8=O("$ZodDefault",(w,b)=>{ww.init(w,b),w._zod.optin="optional",s(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,W)=>{if(W.direction==="backward")return b.innerType._zod.run($,W);if($.value===void 0)return $.value=b.defaultValue,$;let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>hQ(X,b));return hQ(Q,b)}});function hQ(w,b){if(w.value===void 0)w.value=b.defaultValue;return w}var T8=O("$ZodPrefault",(w,b)=>{ww.init(w,b),w._zod.optin="optional",s(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,W)=>{if(W.direction==="backward")return b.innerType._zod.run($,W);if($.value===void 0)$.value=b.defaultValue;return b.innerType._zod.run($,W)}}),R8=O("$ZodNonOptional",(w,b)=>{ww.init(w,b),s(w._zod,"values",()=>{let $=b.innerType._zod.values;return $?new Set([...$].filter((W)=>W!==void 0)):void 0}),w._zod.parse=($,W)=>{let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>yQ(X,w));return yQ(Q,w)}});function yQ(w,b){if(!w.issues.length&&w.value===void 0)w.issues.push({code:"invalid_type",expected:"nonoptional",input:w.value,inst:b});return w}var S8=O("$ZodCatch",(w,b)=>{ww.init(w,b),s(w._zod,"optin",()=>b.innerType._zod.optin),s(w._zod,"optout",()=>b.innerType._zod.optout),s(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,W)=>{if(W.direction==="backward")return b.innerType._zod.run($,W);let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>{if($.value=X.value,X.issues.length)$.value=b.catchValue({...$,error:{issues:X.issues.map((G)=>mw(G,W,xw()))},input:$.value}),$.issues=[];return $});if($.value=Q.value,Q.issues.length)$.value=b.catchValue({...$,error:{issues:Q.issues.map((X)=>mw(X,W,xw()))},input:$.value}),$.issues=[];return $}});var v8=O("$ZodPipe",(w,b)=>{ww.init(w,b),s(w._zod,"values",()=>b.in._zod.values),s(w._zod,"optin",()=>b.in._zod.optin),s(w._zod,"optout",()=>b.out._zod.optout),s(w._zod,"propValues",()=>b.in._zod.propValues),w._zod.parse=($,W)=>{if(W.direction==="backward"){let X=b.out._zod.run($,W);if(X instanceof Promise)return X.then((G)=>yb(G,b.in,W));return yb(X,b.in,W)}let Q=b.in._zod.run($,W);if(Q instanceof Promise)return Q.then((X)=>yb(X,b.out,W));return yb(Q,b.out,W)}});function yb(w,b,$){if(w.issues.length)return w.aborted=!0,w;return b._zod.run({value:w.value,issues:w.issues},$)}var C8=O("$ZodReadonly",(w,b)=>{ww.init(w,b),s(w._zod,"propValues",()=>b.innerType._zod.propValues),s(w._zod,"values",()=>b.innerType._zod.values),s(w._zod,"optin",()=>b.innerType._zod.optin),s(w._zod,"optout",()=>b.innerType._zod.optout),w._zod.parse=($,W)=>{if(W.direction==="backward")return b.innerType._zod.run($,W);let Q=b.innerType._zod.run($,W);if(Q instanceof Promise)return Q.then(fQ);return fQ(Q)}});function fQ(w){return w.value=Object.freeze(w.value),w}var k8=O("$ZodCustom",(w,b)=>{Fw.init(w,b),ww.init(w,b),w._zod.parse=($,W)=>{return $},w._zod.check=($)=>{let W=$.value,Q=b.fn(W);if(Q instanceof Promise)return Q.then((X)=>uQ(X,$,W,w));uQ(Q,$,W,w);return}});function uQ(w,b,$,W){if(!w){let Q={code:"custom",input:$,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)Q.params=W._zod.def.params;b.issues.push(d1(Q))}}var Cz=(w)=>{let b=typeof w;switch(b){case"number":return Number.isNaN(w)?"NaN":"number";case"object":{if(Array.isArray(w))return"array";if(w===null)return"null";if(Object.getPrototypeOf(w)!==Object.prototype&&w.constructor)return w.constructor.name}}return b},kz=()=>{let w={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function b(W){return w[W]??null}let $={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${Cz(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${vb(W.values[0])}`;return`Invalid option: expected one of ${Tb(W.values,"|")}`;case"too_big":{let Q=W.inclusive?"<=":"<",X=b(W.origin);if(X)return`Too big: expected ${W.origin??"value"} to have ${Q}${W.maximum.toString()} ${X.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${Q}${W.maximum.toString()}`}case"too_small":{let Q=W.inclusive?">=":">",X=b(W.origin);if(X)return`Too small: expected ${W.origin} to have ${Q}${W.minimum.toString()} ${X.unit}`;return`Too small: expected ${W.origin} to be ${Q}${W.minimum.toString()}`}case"invalid_format":{let Q=W;if(Q.format==="starts_with")return`Invalid string: must start with "${Q.prefix}"`;if(Q.format==="ends_with")return`Invalid string: must end with "${Q.suffix}"`;if(Q.format==="includes")return`Invalid string: must include "${Q.includes}"`;if(Q.format==="regex")return`Invalid string: must match pattern ${Q.pattern}`;return`Invalid ${$[Q.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${Tb(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function v4(){return{localeError:kz()}}var Wq=Symbol("ZodOutput"),Qq=Symbol("ZodInput");class _8{constructor(){this._map=new WeakMap,this._idmap=new Map}add(w,...b){let $=b[0];if(this._map.set(w,$),$&&typeof $==="object"&&"id"in $){if(this._idmap.has($.id))throw Error(`ID ${$.id} already exists in the registry`);this._idmap.set($.id,w)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(w){let b=this._map.get(w);if(b&&typeof b==="object"&&"id"in b)this._idmap.delete(b.id);return this._map.delete(w),this}get(w){let b=w._zod.parent;if(b){let $={...this.get(b)??{}};delete $.id;let W={...$,...this._map.get(w)};return Object.keys(W).length?W:void 0}return this._map.get(w)}has(w){return this._map.has(w)}}function _z(){return new _8}var v0=_z();function x8(w,b){return new w({type:"string",...v(b)})}function h8(w,b){return new w({type:"string",format:"email",check:"string_format",abort:!1,...v(b)})}function C4(w,b){return new w({type:"string",format:"guid",check:"string_format",abort:!1,...v(b)})}function y8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,...v(b)})}function f8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(b)})}function u8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(b)})}function c8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(b)})}function m8(w,b){return new w({type:"string",format:"url",check:"string_format",abort:!1,...v(b)})}function l8(w,b){return new w({type:"string",format:"emoji",check:"string_format",abort:!1,...v(b)})}function g8(w,b){return new w({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(b)})}function i8(w,b){return new w({type:"string",format:"cuid",check:"string_format",abort:!1,...v(b)})}function n8(w,b){return new w({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(b)})}function p8(w,b){return new w({type:"string",format:"ulid",check:"string_format",abort:!1,...v(b)})}function d8(w,b){return new w({type:"string",format:"xid",check:"string_format",abort:!1,...v(b)})}function o8(w,b){return new w({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(b)})}function t8(w,b){return new w({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(b)})}function r8(w,b){return new w({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(b)})}function s8(w,b){return new w({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(b)})}function e8(w,b){return new w({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(b)})}function a8(w,b){return new w({type:"string",format:"base64",check:"string_format",abort:!1,...v(b)})}function wX(w,b){return new w({type:"string",format:"base64url",check:"string_format",abort:!1,...v(b)})}function bX(w,b){return new w({type:"string",format:"e164",check:"string_format",abort:!1,...v(b)})}function $X(w,b){return new w({type:"string",format:"jwt",check:"string_format",abort:!1,...v(b)})}function WX(w,b){return new w({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(b)})}function QX(w,b){return new w({type:"string",format:"date",check:"string_format",...v(b)})}function XX(w,b){return new w({type:"string",format:"time",check:"string_format",precision:null,...v(b)})}function GX(w,b){return new w({type:"string",format:"duration",check:"string_format",...v(b)})}function JX(w,b){return new w({type:"number",checks:[],...v(b)})}function YX(w,b){return new w({type:"number",check:"number_format",abort:!1,format:"safeint",...v(b)})}function HX(w,b){return new w({type:"boolean",...v(b)})}function zX(w,b){return new w({type:"null",...v(b)})}function DX(w){return new w({type:"unknown"})}function BX(w,b){return new w({type:"never",...v(b)})}function cb(w,b){return new I4({check:"less_than",...v(b),value:w,inclusive:!1})}function C0(w,b){return new I4({check:"less_than",...v(b),value:w,inclusive:!0})}function mb(w,b){return new N4({check:"greater_than",...v(b),value:w,inclusive:!1})}function k0(w,b){return new N4({check:"greater_than",...v(b),value:w,inclusive:!0})}function lb(w,b){return new OQ({check:"multiple_of",...v(b),value:w})}function gb(w,b){return new VQ({check:"max_length",...v(b),maximum:w})}function o1(w,b){return new MQ({check:"min_length",...v(b),minimum:w})}function ib(w,b){return new jQ({check:"length_equals",...v(b),length:w})}function k4(w,b){return new qQ({check:"string_format",format:"regex",...v(b),pattern:w})}function _4(w){return new PQ({check:"string_format",format:"lowercase",...v(w)})}function x4(w){return new IQ({check:"string_format",format:"uppercase",...v(w)})}function h4(w,b){return new NQ({check:"string_format",format:"includes",...v(b),includes:w})}function y4(w,b){return new EQ({check:"string_format",format:"starts_with",...v(b),prefix:w})}function f4(w,b){return new TQ({check:"string_format",format:"ends_with",...v(b),suffix:w})}function h1(w){return new RQ({check:"overwrite",tx:w})}function u4(w){return h1((b)=>b.normalize(w))}function c4(){return h1((w)=>w.trim())}function m4(){return h1((w)=>w.toLowerCase())}function l4(){return h1((w)=>w.toUpperCase())}function AX(w,b,$){return new w({type:"array",element:b,...v($)})}function FX(w,b,$){let W=v($);return W.abort??(W.abort=!0),new w({type:"custom",check:"custom",fn:b,...W})}function LX(w,b,$){return new w({type:"custom",check:"custom",fn:b,...v($)})}function UX(w){let b=xz(($)=>{return $.addIssue=(W)=>{if(typeof W==="string")$.issues.push(d1(W,$.value,b._zod.def));else{let Q=W;if(Q.fatal)Q.continue=!1;Q.code??(Q.code="custom"),Q.input??(Q.input=$.value),Q.inst??(Q.inst=b),Q.continue??(Q.continue=!b._zod.def.abort),$.issues.push(d1(Q))}},w($.value,$)});return b}function xz(w,b){let $=new Fw({check:"custom",...v(b)});return $._zod.check=w,$}function t1(w){return!!w._zod}function q1(w,b){if(t1(w))return T0(w,b);return w.safeParse(b)}function nb(w){if(!w)return;let b;if(t1(w))b=w._zod?.def?.shape;else b=w.shape;if(!b)return;if(typeof b==="function")try{return b()}catch{return}return b}function KX(w){if(t1(w)){let X=w._zod?.def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}}let $=w._def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}let W=w.value;if(W!==void 0)return W;return}var x0={};AW(x0,{time:()=>n4,duration:()=>p4,datetime:()=>g4,date:()=>i4,ZodISOTime:()=>VX,ZodISODuration:()=>MX,ZodISODateTime:()=>OX,ZodISODate:()=>ZX});var OX=O("ZodISODateTime",(w,b)=>{sQ.init(w,b),Ww.init(w,b)});function g4(w){return WX(OX,w)}var ZX=O("ZodISODate",(w,b)=>{eQ.init(w,b),Ww.init(w,b)});function i4(w){return QX(ZX,w)}var VX=O("ZodISOTime",(w,b)=>{aQ.init(w,b),Ww.init(w,b)});function n4(w){return XX(VX,w)}var MX=O("ZodISODuration",(w,b)=>{w8.init(w,b),Ww.init(w,b)});function p4(w){return GX(MX,w)}var jX=(w,b)=>{Cb.init(w,b),w.name="ZodError",Object.defineProperties(w,{format:{value:($)=>kW(w,$)},flatten:{value:($)=>CW(w,$)},addIssue:{value:($)=>{w.issues.push($),w.message=JSON.stringify(w.issues,n1,2)}},addIssues:{value:($)=>{w.issues.push(...$),w.message=JSON.stringify(w.issues,n1,2)}},isEmpty:{get(){return w.issues.length===0}}})},gq=O("ZodError",jX),vw=O("ZodError",jX,{Parent:Error});var qX=kb(vw),PX=_b(vw),IX=E0(vw),NX=R0(vw),EX=_W(vw),TX=xW(vw),RX=hW(vw),SX=yW(vw),vX=fW(vw),CX=uW(vw),kX=cW(vw),_X=mW(vw);var Jw=O("ZodType",(w,b)=>{return ww.init(w,b),w.def=b,w.type=b.type,Object.defineProperty(w,"_def",{value:b}),w.check=(...$)=>{return w.clone(d.mergeDefs(b,{checks:[...b.checks??[],...$.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},w.clone=($,W)=>cw(w,$,W),w.brand=()=>w,w.register=($,W)=>{return $.add(w,W),w},w.parse=($,W)=>qX(w,$,W,{callee:w.parse}),w.safeParse=($,W)=>IX(w,$,W),w.parseAsync=async($,W)=>PX(w,$,W,{callee:w.parseAsync}),w.safeParseAsync=async($,W)=>NX(w,$,W),w.spa=w.safeParseAsync,w.encode=($,W)=>EX(w,$,W),w.decode=($,W)=>TX(w,$,W),w.encodeAsync=async($,W)=>RX(w,$,W),w.decodeAsync=async($,W)=>SX(w,$,W),w.safeEncode=($,W)=>vX(w,$,W),w.safeDecode=($,W)=>CX(w,$,W),w.safeEncodeAsync=async($,W)=>kX(w,$,W),w.safeDecodeAsync=async($,W)=>_X(w,$,W),w.refine=($,W)=>w.check(vD($,W)),w.superRefine=($)=>w.check(CD($)),w.overwrite=($)=>w.check(h1($)),w.optional=()=>Gw(w),w.nullable=()=>yX(w),w.nullish=()=>Gw(yX(w)),w.nonoptional=($)=>ID(w,$),w.array=()=>g(w),w.or=($)=>a([w,$]),w.and=($)=>db(w,$),w.transform=($)=>o4(w,lX($)),w.default=($)=>jD(w,$),w.prefault=($)=>PD(w,$),w.catch=($)=>ED(w,$),w.pipe=($)=>o4(w,$),w.readonly=()=>SD(w),w.describe=($)=>{let W=w.clone();return v0.add(W,{description:$}),W},Object.defineProperty(w,"description",{get(){return v0.get(w)?.description},configurable:!0}),w.meta=(...$)=>{if($.length===0)return v0.get(w);let W=w.clone();return v0.add(W,$[0]),W},w.isOptional=()=>w.safeParse(void 0).success,w.isNullable=()=>w.safeParse(null).success,w}),fX=O("_ZodString",(w,b)=>{ub.init(w,b),Jw.init(w,b);let $=w._zod.bag;w.format=$.format??null,w.minLength=$.minimum??null,w.maxLength=$.maximum??null,w.regex=(...W)=>w.check(k4(...W)),w.includes=(...W)=>w.check(h4(...W)),w.startsWith=(...W)=>w.check(y4(...W)),w.endsWith=(...W)=>w.check(f4(...W)),w.min=(...W)=>w.check(o1(...W)),w.max=(...W)=>w.check(gb(...W)),w.length=(...W)=>w.check(ib(...W)),w.nonempty=(...W)=>w.check(o1(1,...W)),w.lowercase=(W)=>w.check(_4(W)),w.uppercase=(W)=>w.check(x4(W)),w.trim=()=>w.check(c4()),w.normalize=(...W)=>w.check(u4(...W)),w.toLowerCase=()=>w.check(m4()),w.toUpperCase=()=>w.check(l4())}),iz=O("ZodString",(w,b)=>{ub.init(w,b),fX.init(w,b),w.email=($)=>w.check(h8(nz,$)),w.url=($)=>w.check(m8(pz,$)),w.jwt=($)=>w.check($X(JD,$)),w.emoji=($)=>w.check(l8(dz,$)),w.guid=($)=>w.check(C4(xX,$)),w.uuid=($)=>w.check(y8(pb,$)),w.uuidv4=($)=>w.check(f8(pb,$)),w.uuidv6=($)=>w.check(u8(pb,$)),w.uuidv7=($)=>w.check(c8(pb,$)),w.nanoid=($)=>w.check(g8(oz,$)),w.guid=($)=>w.check(C4(xX,$)),w.cuid=($)=>w.check(i8(tz,$)),w.cuid2=($)=>w.check(n8(rz,$)),w.ulid=($)=>w.check(p8(sz,$)),w.base64=($)=>w.check(a8(QD,$)),w.base64url=($)=>w.check(wX(XD,$)),w.xid=($)=>w.check(d8(ez,$)),w.ksuid=($)=>w.check(o8(az,$)),w.ipv4=($)=>w.check(t8(wD,$)),w.ipv6=($)=>w.check(r8(bD,$)),w.cidrv4=($)=>w.check(s8($D,$)),w.cidrv6=($)=>w.check(e8(WD,$)),w.e164=($)=>w.check(bX(GD,$)),w.datetime=($)=>w.check(g4($)),w.date=($)=>w.check(i4($)),w.time=($)=>w.check(n4($)),w.duration=($)=>w.check(p4($))});function K(w){return x8(iz,w)}var Ww=O("ZodStringFormat",(w,b)=>{bw.init(w,b),fX.init(w,b)}),nz=O("ZodEmail",(w,b)=>{lQ.init(w,b),Ww.init(w,b)});var xX=O("ZodGUID",(w,b)=>{cQ.init(w,b),Ww.init(w,b)});var pb=O("ZodUUID",(w,b)=>{mQ.init(w,b),Ww.init(w,b)});var pz=O("ZodURL",(w,b)=>{gQ.init(w,b),Ww.init(w,b)});var dz=O("ZodEmoji",(w,b)=>{iQ.init(w,b),Ww.init(w,b)});var oz=O("ZodNanoID",(w,b)=>{nQ.init(w,b),Ww.init(w,b)});var tz=O("ZodCUID",(w,b)=>{pQ.init(w,b),Ww.init(w,b)});var rz=O("ZodCUID2",(w,b)=>{dQ.init(w,b),Ww.init(w,b)});var sz=O("ZodULID",(w,b)=>{oQ.init(w,b),Ww.init(w,b)});var ez=O("ZodXID",(w,b)=>{tQ.init(w,b),Ww.init(w,b)});var az=O("ZodKSUID",(w,b)=>{rQ.init(w,b),Ww.init(w,b)});var wD=O("ZodIPv4",(w,b)=>{b8.init(w,b),Ww.init(w,b)});var bD=O("ZodIPv6",(w,b)=>{$8.init(w,b),Ww.init(w,b)});var $D=O("ZodCIDRv4",(w,b)=>{W8.init(w,b),Ww.init(w,b)});var WD=O("ZodCIDRv6",(w,b)=>{Q8.init(w,b),Ww.init(w,b)});var QD=O("ZodBase64",(w,b)=>{G8.init(w,b),Ww.init(w,b)});var XD=O("ZodBase64URL",(w,b)=>{J8.init(w,b),Ww.init(w,b)});var GD=O("ZodE164",(w,b)=>{Y8.init(w,b),Ww.init(w,b)});var JD=O("ZodJWT",(w,b)=>{H8.init(w,b),Ww.init(w,b)});var uX=O("ZodNumber",(w,b)=>{R4.init(w,b),Jw.init(w,b),w.gt=(W,Q)=>w.check(mb(W,Q)),w.gte=(W,Q)=>w.check(k0(W,Q)),w.min=(W,Q)=>w.check(k0(W,Q)),w.lt=(W,Q)=>w.check(cb(W,Q)),w.lte=(W,Q)=>w.check(C0(W,Q)),w.max=(W,Q)=>w.check(C0(W,Q)),w.int=(W)=>w.check(hX(W)),w.safe=(W)=>w.check(hX(W)),w.positive=(W)=>w.check(mb(0,W)),w.nonnegative=(W)=>w.check(k0(0,W)),w.negative=(W)=>w.check(cb(0,W)),w.nonpositive=(W)=>w.check(C0(0,W)),w.multipleOf=(W,Q)=>w.check(lb(W,Q)),w.step=(W,Q)=>w.check(lb(W,Q)),w.finite=()=>w;let $=w._zod.bag;w.minValue=Math.max($.minimum??Number.NEGATIVE_INFINITY,$.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,w.maxValue=Math.min($.maximum??Number.POSITIVE_INFINITY,$.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,w.isInt=($.format??"").includes("int")||Number.isSafeInteger($.multipleOf??0.5),w.isFinite=!0,w.format=$.format??null});function r(w){return JX(uX,w)}var YD=O("ZodNumberFormat",(w,b)=>{z8.init(w,b),uX.init(w,b)});function hX(w){return YX(YD,w)}var HD=O("ZodBoolean",(w,b)=>{D8.init(w,b),Jw.init(w,b)});function Aw(w){return HX(HD,w)}var zD=O("ZodNull",(w,b)=>{B8.init(w,b),Jw.init(w,b)});function t4(w){return zX(zD,w)}var DD=O("ZodUnknown",(w,b)=>{A8.init(w,b),Jw.init(w,b)});function Qw(){return DX(DD)}var BD=O("ZodNever",(w,b)=>{F8.init(w,b),Jw.init(w,b)});function AD(w){return BX(BD,w)}var FD=O("ZodArray",(w,b)=>{L8.init(w,b),Jw.init(w,b),w.element=b.element,w.min=($,W)=>w.check(o1($,W)),w.nonempty=($)=>w.check(o1(1,$)),w.max=($,W)=>w.check(gb($,W)),w.length=($,W)=>w.check(ib($,W)),w.unwrap=()=>w.element});function g(w,b){return AX(FD,w,b)}var cX=O("ZodObject",(w,b)=>{O8.init(w,b),Jw.init(w,b),d.defineLazy(w,"shape",()=>{return b.shape}),w.keyof=()=>Iw(Object.keys(w._zod.def.shape)),w.catchall=($)=>w.clone({...w._zod.def,catchall:$}),w.passthrough=()=>w.clone({...w._zod.def,catchall:Qw()}),w.loose=()=>w.clone({...w._zod.def,catchall:Qw()}),w.strict=()=>w.clone({...w._zod.def,catchall:AD()}),w.strip=()=>w.clone({...w._zod.def,catchall:void 0}),w.extend=($)=>{return d.extend(w,$)},w.safeExtend=($)=>{return d.safeExtend(w,$)},w.merge=($)=>d.merge(w,$),w.pick=($)=>d.pick(w,$),w.omit=($)=>d.omit(w,$),w.partial=(...$)=>d.partial(gX,w,$[0]),w.required=(...$)=>d.required(iX,w,$[0])});function E(w,b){let $={type:"object",shape:w??{},...d.normalizeParams(b)};return new cX($)}function Mw(w,b){return new cX({type:"object",shape:w,catchall:Qw(),...d.normalizeParams(b)})}var mX=O("ZodUnion",(w,b)=>{S4.init(w,b),Jw.init(w,b),w.options=b.options});function a(w,b){return new mX({type:"union",options:w,...d.normalizeParams(b)})}var LD=O("ZodDiscriminatedUnion",(w,b)=>{mX.init(w,b),Z8.init(w,b)});function r4(w,b,$){return new LD({type:"union",options:b,discriminator:w,...d.normalizeParams($)})}var UD=O("ZodIntersection",(w,b)=>{V8.init(w,b),Jw.init(w,b)});function db(w,b){return new UD({type:"intersection",left:w,right:b})}var KD=O("ZodRecord",(w,b)=>{M8.init(w,b),Jw.init(w,b),w.keyType=b.keyType,w.valueType=b.valueType});function Xw(w,b,$){return new KD({type:"record",keyType:w,valueType:b,...d.normalizeParams($)})}var d4=O("ZodEnum",(w,b)=>{j8.init(w,b),Jw.init(w,b),w.enum=b.entries,w.options=Object.values(b.entries);let $=new Set(Object.keys(b.entries));w.extract=(W,Q)=>{let X={};for(let G of W)if($.has(G))X[G]=b.entries[G];else throw Error(`Key ${G} not found in enum`);return new d4({...b,checks:[],...d.normalizeParams(Q),entries:X})},w.exclude=(W,Q)=>{let X={...b.entries};for(let G of W)if($.has(G))delete X[G];else throw Error(`Key ${G} not found in enum`);return new d4({...b,checks:[],...d.normalizeParams(Q),entries:X})}});function Iw(w,b){let $=Array.isArray(w)?Object.fromEntries(w.map((W)=>[W,W])):w;return new d4({type:"enum",entries:$,...d.normalizeParams(b)})}var OD=O("ZodLiteral",(w,b)=>{q8.init(w,b),Jw.init(w,b),w.values=new Set(b.values),Object.defineProperty(w,"value",{get(){if(b.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return b.values[0]}})});function T(w,b){return new OD({type:"literal",values:Array.isArray(w)?w:[w],...d.normalizeParams(b)})}var ZD=O("ZodTransform",(w,b)=>{P8.init(w,b),Jw.init(w,b),w._zod.parse=($,W)=>{if(W.direction==="backward")throw new j0(w.constructor.name);$.addIssue=(X)=>{if(typeof X==="string")$.issues.push(d.issue(X,$.value,b));else{let G=X;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=$.value),G.inst??(G.inst=w),$.issues.push(d.issue(G))}};let Q=b.transform($.value,$);if(Q instanceof Promise)return Q.then((X)=>{return $.value=X,$});return $.value=Q,$}});function lX(w){return new ZD({type:"transform",transform:w})}var gX=O("ZodOptional",(w,b)=>{I8.init(w,b),Jw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function Gw(w){return new gX({type:"optional",innerType:w})}var VD=O("ZodNullable",(w,b)=>{N8.init(w,b),Jw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function yX(w){return new VD({type:"nullable",innerType:w})}var MD=O("ZodDefault",(w,b)=>{E8.init(w,b),Jw.init(w,b),w.unwrap=()=>w._zod.def.innerType,w.removeDefault=w.unwrap});function jD(w,b){return new MD({type:"default",innerType:w,get defaultValue(){return typeof b==="function"?b():d.shallowClone(b)}})}var qD=O("ZodPrefault",(w,b)=>{T8.init(w,b),Jw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function PD(w,b){return new qD({type:"prefault",innerType:w,get defaultValue(){return typeof b==="function"?b():d.shallowClone(b)}})}var iX=O("ZodNonOptional",(w,b)=>{R8.init(w,b),Jw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function ID(w,b){return new iX({type:"nonoptional",innerType:w,...d.normalizeParams(b)})}var ND=O("ZodCatch",(w,b)=>{S8.init(w,b),Jw.init(w,b),w.unwrap=()=>w._zod.def.innerType,w.removeCatch=w.unwrap});function ED(w,b){return new ND({type:"catch",innerType:w,catchValue:typeof b==="function"?b:()=>b})}var TD=O("ZodPipe",(w,b)=>{v8.init(w,b),Jw.init(w,b),w.in=b.in,w.out=b.out});function o4(w,b){return new TD({type:"pipe",in:w,out:b})}var RD=O("ZodReadonly",(w,b)=>{C8.init(w,b),Jw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function SD(w){return new RD({type:"readonly",innerType:w})}var nX=O("ZodCustom",(w,b)=>{k8.init(w,b),Jw.init(w,b)});function pX(w,b){return FX(nX,w??(()=>!0),b)}function vD(w,b={}){return LX(nX,w,b)}function CD(w){return UX(w)}function s4(w,b){return o4(lX(w),b)}xw(v4());var e4="2025-11-25";var dX=[e4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],P1="io.modelcontextprotocol/related-task",tb="2.0",Lw=pX((w)=>w!==null&&(typeof w==="object"||typeof w==="function")),oX=a([K(),r().int()]),tX=K(),fP=Mw({ttl:a([r(),t4()]).optional(),pollInterval:r().optional()}),kD=E({ttl:r().optional()}),_D=E({taskId:K()}),a4=Mw({progressToken:oX.optional(),[P1]:_D.optional()}),Cw=E({_meta:a4.optional()}),h0=Cw.extend({task:kD.optional()}),rX=(w)=>h0.safeParse(w).success,Uw=E({method:K(),params:Cw.loose().optional()}),hw=E({_meta:a4.optional()}),yw=E({method:K(),params:hw.loose().optional()}),Kw=Mw({_meta:a4.optional()}),rb=a([K(),r().int()]),sX=E({jsonrpc:T(tb),id:rb,...Uw.shape}).strict(),w$=(w)=>sX.safeParse(w).success,eX=E({jsonrpc:T(tb),...yw.shape}).strict(),aX=(w)=>eX.safeParse(w).success,b$=E({jsonrpc:T(tb),id:rb,result:Kw}).strict(),y0=(w)=>b$.safeParse(w).success;var i;(function(w){w[w.ConnectionClosed=-32000]="ConnectionClosed",w[w.RequestTimeout=-32001]="RequestTimeout",w[w.ParseError=-32700]="ParseError",w[w.InvalidRequest=-32600]="InvalidRequest",w[w.MethodNotFound=-32601]="MethodNotFound",w[w.InvalidParams=-32602]="InvalidParams",w[w.InternalError=-32603]="InternalError",w[w.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(i||(i={}));var $$=E({jsonrpc:T(tb),id:rb.optional(),error:E({code:r().int(),message:K(),data:Qw().optional()})}).strict();var wG=(w)=>$$.safeParse(w).success;var bG=a([sX,eX,b$,$$]),uP=a([b$,$$]),sb=Kw.strict(),xD=hw.extend({requestId:rb.optional(),reason:K().optional()}),eb=yw.extend({method:T("notifications/cancelled"),params:xD}),hD=E({src:K(),mimeType:K().optional(),sizes:g(K()).optional(),theme:Iw(["light","dark"]).optional()}),f0=E({icons:g(hD).optional()}),r1=E({name:K(),title:K().optional()}),$G=r1.extend({...r1.shape,...f0.shape,version:K(),websiteUrl:K().optional(),description:K().optional()}),yD=db(E({applyDefaults:Aw().optional()}),Xw(K(),Qw())),fD=s4((w)=>{if(w&&typeof w==="object"&&!Array.isArray(w)){if(Object.keys(w).length===0)return{form:{}}}return w},db(E({form:yD.optional(),url:Lw.optional()}),Xw(K(),Qw()).optional())),uD=Mw({list:Lw.optional(),cancel:Lw.optional(),requests:Mw({sampling:Mw({createMessage:Lw.optional()}).optional(),elicitation:Mw({create:Lw.optional()}).optional()}).optional()}),cD=Mw({list:Lw.optional(),cancel:Lw.optional(),requests:Mw({tools:Mw({call:Lw.optional()}).optional()}).optional()}),mD=E({experimental:Xw(K(),Lw).optional(),sampling:E({context:Lw.optional(),tools:Lw.optional()}).optional(),elicitation:fD.optional(),roots:E({listChanged:Aw().optional()}).optional(),tasks:uD.optional()}),lD=Cw.extend({protocolVersion:K(),capabilities:mD,clientInfo:$G}),W$=Uw.extend({method:T("initialize"),params:lD});var gD=E({experimental:Xw(K(),Lw).optional(),logging:Lw.optional(),completions:Lw.optional(),prompts:E({listChanged:Aw().optional()}).optional(),resources:E({subscribe:Aw().optional(),listChanged:Aw().optional()}).optional(),tools:E({listChanged:Aw().optional()}).optional(),tasks:cD.optional()}),iD=Kw.extend({protocolVersion:K(),capabilities:gD,serverInfo:$G,instructions:K().optional()}),Q$=yw.extend({method:T("notifications/initialized"),params:hw.optional()});var ab=Uw.extend({method:T("ping"),params:Cw.optional()}),nD=E({progress:r(),total:Gw(r()),message:Gw(K())}),pD=E({...hw.shape,...nD.shape,progressToken:oX}),w6=yw.extend({method:T("notifications/progress"),params:pD}),dD=Cw.extend({cursor:tX.optional()}),u0=Uw.extend({params:dD.optional()}),c0=Kw.extend({nextCursor:tX.optional()}),oD=Iw(["working","input_required","completed","failed","cancelled"]),m0=E({taskId:K(),status:oD,ttl:a([r(),t4()]),createdAt:K(),lastUpdatedAt:K(),pollInterval:Gw(r()),statusMessage:Gw(K())}),s1=Kw.extend({task:m0}),tD=hw.merge(m0),l0=yw.extend({method:T("notifications/tasks/status"),params:tD}),b6=Uw.extend({method:T("tasks/get"),params:Cw.extend({taskId:K()})}),$6=Kw.merge(m0),W6=Uw.extend({method:T("tasks/result"),params:Cw.extend({taskId:K()})}),cP=Kw.loose(),Q6=u0.extend({method:T("tasks/list")}),X6=c0.extend({tasks:g(m0)}),G6=Uw.extend({method:T("tasks/cancel"),params:Cw.extend({taskId:K()})}),WG=Kw.merge(m0),QG=E({uri:K(),mimeType:Gw(K()),_meta:Xw(K(),Qw()).optional()}),XG=QG.extend({text:K()}),X$=K().refine((w)=>{try{return atob(w),!0}catch{return!1}},{message:"Invalid Base64 string"}),GG=QG.extend({blob:X$}),g0=Iw(["user","assistant"]),e1=E({audience:g(g0).optional(),priority:r().min(0).max(1).optional(),lastModified:x0.datetime({offset:!0}).optional()}),JG=E({...r1.shape,...f0.shape,uri:K(),description:Gw(K()),mimeType:Gw(K()),annotations:e1.optional(),_meta:Gw(Mw({}))}),rD=E({...r1.shape,...f0.shape,uriTemplate:K(),description:Gw(K()),mimeType:Gw(K()),annotations:e1.optional(),_meta:Gw(Mw({}))}),G$=u0.extend({method:T("resources/list")}),sD=c0.extend({resources:g(JG)}),eD=u0.extend({method:T("resources/templates/list")}),aD=c0.extend({resourceTemplates:g(rD)}),J$=Cw.extend({uri:K()}),wB=J$,Y$=Uw.extend({method:T("resources/read"),params:wB}),bB=Kw.extend({contents:g(a([XG,GG]))}),$B=yw.extend({method:T("notifications/resources/list_changed"),params:hw.optional()}),WB=J$,QB=Uw.extend({method:T("resources/subscribe"),params:WB}),XB=J$,GB=Uw.extend({method:T("resources/unsubscribe"),params:XB}),JB=hw.extend({uri:K()}),YB=yw.extend({method:T("notifications/resources/updated"),params:JB}),HB=E({name:K(),description:Gw(K()),required:Gw(Aw())}),zB=E({...r1.shape,...f0.shape,description:Gw(K()),arguments:Gw(g(HB)),_meta:Gw(Mw({}))}),DB=u0.extend({method:T("prompts/list")}),BB=c0.extend({prompts:g(zB)}),AB=Cw.extend({name:K(),arguments:Xw(K(),K()).optional()}),FB=Uw.extend({method:T("prompts/get"),params:AB}),H$=E({type:T("text"),text:K(),annotations:e1.optional(),_meta:Xw(K(),Qw()).optional()}),z$=E({type:T("image"),data:X$,mimeType:K(),annotations:e1.optional(),_meta:Xw(K(),Qw()).optional()}),D$=E({type:T("audio"),data:X$,mimeType:K(),annotations:e1.optional(),_meta:Xw(K(),Qw()).optional()}),LB=E({type:T("tool_use"),name:K(),id:K(),input:Xw(K(),Qw()),_meta:Xw(K(),Qw()).optional()}),UB=E({type:T("resource"),resource:a([XG,GG]),annotations:e1.optional(),_meta:Xw(K(),Qw()).optional()}),KB=JG.extend({type:T("resource_link")}),B$=a([H$,z$,D$,KB,UB]),OB=E({role:g0,content:B$}),ZB=Kw.extend({description:K().optional(),messages:g(OB)}),VB=yw.extend({method:T("notifications/prompts/list_changed"),params:hw.optional()}),MB=E({title:K().optional(),readOnlyHint:Aw().optional(),destructiveHint:Aw().optional(),idempotentHint:Aw().optional(),openWorldHint:Aw().optional()}),jB=E({taskSupport:Iw(["required","optional","forbidden"]).optional()}),YG=E({...r1.shape,...f0.shape,description:K().optional(),inputSchema:E({type:T("object"),properties:Xw(K(),Lw).optional(),required:g(K()).optional()}).catchall(Qw()),outputSchema:E({type:T("object"),properties:Xw(K(),Lw).optional(),required:g(K()).optional()}).catchall(Qw()).optional(),annotations:MB.optional(),execution:jB.optional(),_meta:Xw(K(),Qw()).optional()}),A$=u0.extend({method:T("tools/list")}),qB=c0.extend({tools:g(YG)}),J6=Kw.extend({content:g(B$).default([]),structuredContent:Xw(K(),Qw()).optional(),isError:Aw().optional()}),mP=J6.or(Kw.extend({toolResult:Qw()})),PB=h0.extend({name:K(),arguments:Xw(K(),Qw()).optional()}),i0=Uw.extend({method:T("tools/call"),params:PB}),IB=yw.extend({method:T("notifications/tools/list_changed"),params:hw.optional()}),lP=E({autoRefresh:Aw().default(!0),debounceMs:r().int().nonnegative().default(300)}),n0=Iw(["debug","info","notice","warning","error","critical","alert","emergency"]),NB=Cw.extend({level:n0}),F$=Uw.extend({method:T("logging/setLevel"),params:NB}),EB=hw.extend({level:n0,logger:K().optional(),data:Qw()}),TB=yw.extend({method:T("notifications/message"),params:EB}),RB=E({name:K().optional()}),SB=E({hints:g(RB).optional(),costPriority:r().min(0).max(1).optional(),speedPriority:r().min(0).max(1).optional(),intelligencePriority:r().min(0).max(1).optional()}),vB=E({mode:Iw(["auto","required","none"]).optional()}),CB=E({type:T("tool_result"),toolUseId:K().describe("The unique identifier for the corresponding tool call."),content:g(B$).default([]),structuredContent:E({}).loose().optional(),isError:Aw().optional(),_meta:Xw(K(),Qw()).optional()}),kB=r4("type",[H$,z$,D$]),ob=r4("type",[H$,z$,D$,LB,CB]),_B=E({role:g0,content:a([ob,g(ob)]),_meta:Xw(K(),Qw()).optional()}),xB=h0.extend({messages:g(_B),modelPreferences:SB.optional(),systemPrompt:K().optional(),includeContext:Iw(["none","thisServer","allServers"]).optional(),temperature:r().optional(),maxTokens:r().int(),stopSequences:g(K()).optional(),metadata:Lw.optional(),tools:g(YG).optional(),toolChoice:vB.optional()}),hB=Uw.extend({method:T("sampling/createMessage"),params:xB}),L$=Kw.extend({model:K(),stopReason:Gw(Iw(["endTurn","stopSequence","maxTokens"]).or(K())),role:g0,content:kB}),U$=Kw.extend({model:K(),stopReason:Gw(Iw(["endTurn","stopSequence","maxTokens","toolUse"]).or(K())),role:g0,content:a([ob,g(ob)])}),yB=E({type:T("boolean"),title:K().optional(),description:K().optional(),default:Aw().optional()}),fB=E({type:T("string"),title:K().optional(),description:K().optional(),minLength:r().optional(),maxLength:r().optional(),format:Iw(["email","uri","date","date-time"]).optional(),default:K().optional()}),uB=E({type:Iw(["number","integer"]),title:K().optional(),description:K().optional(),minimum:r().optional(),maximum:r().optional(),default:r().optional()}),cB=E({type:T("string"),title:K().optional(),description:K().optional(),enum:g(K()),default:K().optional()}),mB=E({type:T("string"),title:K().optional(),description:K().optional(),oneOf:g(E({const:K(),title:K()})),default:K().optional()}),lB=E({type:T("string"),title:K().optional(),description:K().optional(),enum:g(K()),enumNames:g(K()).optional(),default:K().optional()}),gB=a([cB,mB]),iB=E({type:T("array"),title:K().optional(),description:K().optional(),minItems:r().optional(),maxItems:r().optional(),items:E({type:T("string"),enum:g(K())}),default:g(K()).optional()}),nB=E({type:T("array"),title:K().optional(),description:K().optional(),minItems:r().optional(),maxItems:r().optional(),items:E({anyOf:g(E({const:K(),title:K()}))}),default:g(K()).optional()}),pB=a([iB,nB]),dB=a([lB,gB,pB]),oB=a([dB,yB,fB,uB]),tB=h0.extend({mode:T("form").optional(),message:K(),requestedSchema:E({type:T("object"),properties:Xw(K(),oB),required:g(K()).optional()})}),rB=h0.extend({mode:T("url"),message:K(),elicitationId:K(),url:K().url()}),sB=a([tB,rB]),eB=Uw.extend({method:T("elicitation/create"),params:sB}),aB=hw.extend({elicitationId:K()}),wA=yw.extend({method:T("notifications/elicitation/complete"),params:aB}),Y6=Kw.extend({action:Iw(["accept","decline","cancel"]),content:s4((w)=>w===null?void 0:w,Xw(K(),a([K(),r(),Aw(),g(K())])).optional())}),bA=E({type:T("ref/resource"),uri:K()});var $A=E({type:T("ref/prompt"),name:K()}),WA=Cw.extend({ref:a([$A,bA]),argument:E({name:K(),value:K()}),context:E({arguments:Xw(K(),K()).optional()}).optional()}),QA=Uw.extend({method:T("completion/complete"),params:WA});var XA=Kw.extend({completion:Mw({values:g(K()).max(100),total:Gw(r().int()),hasMore:Gw(Aw())})}),GA=E({uri:K().startsWith("file://"),name:K().optional(),_meta:Xw(K(),Qw()).optional()}),JA=Uw.extend({method:T("roots/list"),params:Cw.optional()}),K$=Kw.extend({roots:g(GA)}),YA=yw.extend({method:T("notifications/roots/list_changed"),params:hw.optional()}),gP=a([ab,W$,QA,F$,FB,DB,G$,eD,Y$,QB,GB,i0,A$,b6,W6,Q6,G6]),iP=a([eb,w6,Q$,YA,l0]),nP=a([sb,L$,U$,Y6,K$,$6,X6,s1]),pP=a([ab,hB,eB,JA,b6,W6,Q6,G6]),dP=a([eb,w6,TB,YB,$B,IB,VB,l0,wA]),oP=a([sb,iD,XA,ZB,BB,sD,aD,bB,J6,qB,$6,X6,s1]);class u extends Error{constructor(w,b,$){super(`MCP error ${w}: ${b}`);this.code=w,this.data=$,this.name="McpError"}static fromError(w,b,$){if(w===i.UrlElicitationRequired&&$){let W=$;if(W.elicitations)return new HG(W.elicitations,b)}return new u(w,b,$)}}class HG extends u{constructor(w,b=`URL elicitation${w.length>1?"s":""} required`){super(i.UrlElicitationRequired,b,{elicitations:w})}get elicitations(){return this.data?.elicitations??[]}}function I1(w){return w==="completed"||w==="failed"||w==="cancelled"}var HA=Symbol("Let zodToJsonSchema decide on which parser to use");var EI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function O$(w){let $=nb(w)?.method;if(!$)throw Error("Schema is missing a method literal");let W=KX($);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function Z$(w,b){let $=q1(w,b);if(!$.success)throw $.error;return $.data}var LA=60000;class V${constructor(w){if(this._options=w,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(eb,(b)=>{this._oncancel(b)}),this.setNotificationHandler(w6,(b)=>{this._onprogress(b)}),this.setRequestHandler(ab,(b)=>({})),this._taskStore=w?.taskStore,this._taskMessageQueue=w?.taskMessageQueue,this._taskStore)this.setRequestHandler(b6,async(b,$)=>{let W=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!W)throw new u(i.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(W6,async(b,$)=>{let W=async()=>{let Q=b.params.taskId;if(this._taskMessageQueue){let G;while(G=await this._taskMessageQueue.dequeue(Q,$.sessionId)){if(G.type==="response"||G.type==="error"){let J=G.message,Y=J.id,H=this._requestResolvers.get(Y);if(H)if(this._requestResolvers.delete(Y),G.type==="response")H(J);else{let z=J,B=new u(z.error.code,z.error.message,z.error.data);H(B)}else{let z=G.type==="response"?"Response":"Error";this._onerror(Error(`${z} handler missing for request ${Y}`))}continue}await this._transport?.send(G.message,{relatedRequestId:$.requestId})}}let X=await this._taskStore.getTask(Q,$.sessionId);if(!X)throw new u(i.InvalidParams,`Task not found: ${Q}`);if(!I1(X.status))return await this._waitForTaskUpdate(Q,$.signal),await W();if(I1(X.status)){let G=await this._taskStore.getTaskResult(Q,$.sessionId);return this._clearTaskQueue(Q),{...G,_meta:{...G._meta,[P1]:{taskId:Q}}}}return await W()};return await W()}),this.setRequestHandler(Q6,async(b,$)=>{try{let{tasks:W,nextCursor:Q}=await this._taskStore.listTasks(b.params?.cursor,$.sessionId);return{tasks:W,nextCursor:Q,_meta:{}}}catch(W){throw new u(i.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(G6,async(b,$)=>{try{let W=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!W)throw new u(i.InvalidParams,`Task not found: ${b.params.taskId}`);if(I1(W.status))throw new u(i.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(b.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(b.params.taskId);let Q=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!Q)throw new u(i.InvalidParams,`Task not found after cancellation: ${b.params.taskId}`);return{_meta:{},...Q}}catch(W){if(W instanceof u)throw W;throw new u(i.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(w){if(!w.params.requestId)return;this._requestHandlerAbortControllers.get(w.params.requestId)?.abort(w.params.reason)}_setupTimeout(w,b,$,W,Q=!1){this._timeoutInfo.set(w,{timeoutId:setTimeout(W,b),startTime:Date.now(),timeout:b,maxTotalTimeout:$,resetTimeoutOnProgress:Q,onTimeout:W})}_resetTimeout(w){let b=this._timeoutInfo.get(w);if(!b)return!1;let $=Date.now()-b.startTime;if(b.maxTotalTimeout&&$>=b.maxTotalTimeout)throw this._timeoutInfo.delete(w),u.fromError(i.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:b.maxTotalTimeout,totalElapsed:$});return clearTimeout(b.timeoutId),b.timeoutId=setTimeout(b.onTimeout,b.timeout),!0}_cleanupTimeout(w){let b=this._timeoutInfo.get(w);if(b)clearTimeout(b.timeoutId),this._timeoutInfo.delete(w)}async connect(w){this._transport=w;let b=this.transport?.onclose;this._transport.onclose=()=>{b?.(),this._onclose()};let $=this.transport?.onerror;this._transport.onerror=(Q)=>{$?.(Q),this._onerror(Q)};let W=this._transport?.onmessage;this._transport.onmessage=(Q,X)=>{if(W?.(Q,X),y0(Q)||wG(Q))this._onresponse(Q);else if(w$(Q))this._onrequest(Q,X);else if(aX(Q))this._onnotification(Q);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Q)}`))},await this._transport.start()}_onclose(){let w=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let b=u.fromError(i.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let $ of w.values())$(b)}_onerror(w){this.onerror?.(w)}_onnotification(w){let b=this._notificationHandlers.get(w.method)??this.fallbackNotificationHandler;if(b===void 0)return;Promise.resolve().then(()=>b(w)).catch(($)=>this._onerror(Error(`Uncaught error in notification handler: ${$}`)))}_onrequest(w,b){let $=this._requestHandlers.get(w.method)??this.fallbackRequestHandler,W=this._transport,Q=w.params?._meta?.[P1]?.taskId;if($===void 0){let H={jsonrpc:"2.0",id:w.id,error:{code:i.MethodNotFound,message:"Method not found"}};if(Q&&this._taskMessageQueue)this._enqueueTaskMessage(Q,{type:"error",message:H,timestamp:Date.now()},W?.sessionId).catch((z)=>this._onerror(Error(`Failed to enqueue error response: ${z}`)));else W?.send(H).catch((z)=>this._onerror(Error(`Failed to send an error response: ${z}`)));return}let X=new AbortController;this._requestHandlerAbortControllers.set(w.id,X);let G=rX(w.params)?w.params.task:void 0,J=this._taskStore?this.requestTaskStore(w,W?.sessionId):void 0,Y={signal:X.signal,sessionId:W?.sessionId,_meta:w.params?._meta,sendNotification:async(H)=>{let z={relatedRequestId:w.id};if(Q)z.relatedTask={taskId:Q};await this.notification(H,z)},sendRequest:async(H,z,B)=>{let A={...B,relatedRequestId:w.id};if(Q&&!A.relatedTask)A.relatedTask={taskId:Q};let F=A.relatedTask?.taskId??Q;if(F&&J)await J.updateTaskStatus(F,"input_required");return await this.request(H,z,A)},authInfo:b?.authInfo,requestId:w.id,requestInfo:b?.requestInfo,taskId:Q,taskStore:J,taskRequestedTtl:G?.ttl,closeSSEStream:b?.closeSSEStream,closeStandaloneSSEStream:b?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(G)this.assertTaskHandlerCapability(w.method)}).then(()=>$(w,Y)).then(async(H)=>{if(X.signal.aborted)return;let z={result:H,jsonrpc:"2.0",id:w.id};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"response",message:z,timestamp:Date.now()},W?.sessionId);else await W?.send(z)},async(H)=>{if(X.signal.aborted)return;let z={jsonrpc:"2.0",id:w.id,error:{code:Number.isSafeInteger(H.code)?H.code:i.InternalError,message:H.message??"Internal error",...H.data!==void 0&&{data:H.data}}};if(Q&&this._taskMessageQueue)await this._enqueueTaskMessage(Q,{type:"error",message:z,timestamp:Date.now()},W?.sessionId);else await W?.send(z)}).catch((H)=>this._onerror(Error(`Failed to send response: ${H}`))).finally(()=>{this._requestHandlerAbortControllers.delete(w.id)})}_onprogress(w){let{progressToken:b,...$}=w.params,W=Number(b),Q=this._progressHandlers.get(W);if(!Q){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(w)}`));return}let X=this._responseHandlers.get(W),G=this._timeoutInfo.get(W);if(G&&X&&G.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(J){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),X(J);return}Q($)}_onresponse(w){let b=Number(w.id),$=this._requestResolvers.get(b);if($){if(this._requestResolvers.delete(b),y0(w))$(w);else{let X=new u(w.error.code,w.error.message,w.error.data);$(X)}return}let W=this._responseHandlers.get(b);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(w)}`));return}this._responseHandlers.delete(b),this._cleanupTimeout(b);let Q=!1;if(y0(w)&&w.result&&typeof w.result==="object"){let X=w.result;if(X.task&&typeof X.task==="object"){let G=X.task;if(typeof G.taskId==="string")Q=!0,this._taskProgressTokens.set(G.taskId,b)}}if(!Q)this._progressHandlers.delete(b);if(y0(w))W(w);else{let X=u.fromError(w.error.code,w.error.message,w.error.data);W(X)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(w,b,$){let{task:W}=$??{};if(!W){try{yield{type:"result",result:await this.request(w,b,$)}}catch(X){yield{type:"error",error:X instanceof u?X:new u(i.InternalError,String(X))}}return}let Q;try{let X=await this.request(w,s1,$);if(X.task)Q=X.task.taskId,yield{type:"taskCreated",task:X.task};else throw new u(i.InternalError,"Task creation did not return a task");while(!0){let G=await this.getTask({taskId:Q},$);if(yield{type:"taskStatus",task:G},I1(G.status)){if(G.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Q},b,$)};else if(G.status==="failed")yield{type:"error",error:new u(i.InternalError,`Task ${Q} failed`)};else if(G.status==="cancelled")yield{type:"error",error:new u(i.InternalError,`Task ${Q} was cancelled`)};return}if(G.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Q},b,$)};return}let J=G.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((Y)=>setTimeout(Y,J)),$?.signal?.throwIfAborted()}}catch(X){yield{type:"error",error:X instanceof u?X:new u(i.InternalError,String(X))}}}request(w,b,$){let{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:X,task:G,relatedTask:J}=$??{};return new Promise((Y,H)=>{let z=(P)=>{H(P)};if(!this._transport){z(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(w.method),G)this.assertTaskCapability(w.method)}catch(P){z(P);return}$?.signal?.throwIfAborted();let B=this._requestMessageId++,A={...w,jsonrpc:"2.0",id:B};if($?.onprogress)this._progressHandlers.set(B,$.onprogress),A.params={...w.params,_meta:{...w.params?._meta||{},progressToken:B}};if(G)A.params={...A.params,task:G};if(J)A.params={...A.params,_meta:{...A.params?._meta||{},[P1]:J}};let F=(P)=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:B,reason:String(P)}},{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:X}).catch((S)=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let k=P instanceof u?P:new u(i.RequestTimeout,String(P));H(k)};this._responseHandlers.set(B,(P)=>{if($?.signal?.aborted)return;if(P instanceof Error)return H(P);try{let k=q1(b,P.result);if(!k.success)H(k.error);else Y(k.data)}catch(k){H(k)}}),$?.signal?.addEventListener("abort",()=>{F($?.signal?.reason)});let U=$?.timeout??LA,M=()=>F(u.fromError(i.RequestTimeout,"Request timed out",{timeout:U}));this._setupTimeout(B,U,$?.maxTotalTimeout,M,$?.resetTimeoutOnProgress??!1);let q=J?.taskId;if(q){let P=(k)=>{let S=this._responseHandlers.get(B);if(S)S(k);else this._onerror(Error(`Response handler missing for side-channeled request ${B}`))};this._requestResolvers.set(B,P),this._enqueueTaskMessage(q,{type:"request",message:A,timestamp:Date.now()}).catch((k)=>{this._cleanupTimeout(B),H(k)})}else this._transport.send(A,{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:X}).catch((P)=>{this._cleanupTimeout(B),H(P)})})}async getTask(w,b){return this.request({method:"tasks/get",params:w},$6,b)}async getTaskResult(w,b,$){return this.request({method:"tasks/result",params:w},b,$)}async listTasks(w,b){return this.request({method:"tasks/list",params:w},X6,b)}async cancelTask(w,b){return this.request({method:"tasks/cancel",params:w},WG,b)}async notification(w,b){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(w.method);let $=b?.relatedTask?.taskId;if($){let G={...w,jsonrpc:"2.0",params:{...w.params,_meta:{...w.params?._meta||{},[P1]:b.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:G,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(w.method)&&!w.params&&!b?.relatedRequestId&&!b?.relatedTask){if(this._pendingDebouncedNotifications.has(w.method))return;this._pendingDebouncedNotifications.add(w.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(w.method),!this._transport)return;let G={...w,jsonrpc:"2.0"};if(b?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[P1]:b.relatedTask}}};this._transport?.send(G,b).catch((J)=>this._onerror(J))});return}let X={...w,jsonrpc:"2.0"};if(b?.relatedTask)X={...X,params:{...X.params,_meta:{...X.params?._meta||{},[P1]:b.relatedTask}}};await this._transport.send(X,b)}setRequestHandler(w,b){let $=O$(w);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(W,Q)=>{let X=Z$(w,W);return Promise.resolve(b(X,Q))})}removeRequestHandler(w){this._requestHandlers.delete(w)}assertCanSetRequestHandler(w){if(this._requestHandlers.has(w))throw Error(`A request handler for ${w} already exists, which would be overridden`)}setNotificationHandler(w,b){let $=O$(w);this._notificationHandlers.set($,(W)=>{let Q=Z$(w,W);return Promise.resolve(b(Q))})}removeNotificationHandler(w){this._notificationHandlers.delete(w)}_cleanupTaskProgressHandler(w){let b=this._taskProgressTokens.get(w);if(b!==void 0)this._progressHandlers.delete(b),this._taskProgressTokens.delete(w)}async _enqueueTaskMessage(w,b,$){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(w,b,$,W)}async _clearTaskQueue(w,b){if(this._taskMessageQueue){let $=await this._taskMessageQueue.dequeueAll(w,b);for(let W of $)if(W.type==="request"&&w$(W.message)){let Q=W.message.id,X=this._requestResolvers.get(Q);if(X)X(new u(i.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(Q);else this._onerror(Error(`Resolver missing for request ${Q} during task ${w} cleanup`))}}}async _waitForTaskUpdate(w,b){let $=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(w);if(W?.pollInterval)$=W.pollInterval}catch{}return new Promise((W,Q)=>{if(b.aborted){Q(new u(i.InvalidRequest,"Request cancelled"));return}let X=setTimeout(W,$);b.addEventListener("abort",()=>{clearTimeout(X),Q(new u(i.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(w,b){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(W)=>{if(!w)throw Error("No request provided");return await $.createTask(W,w.id,{method:w.method,params:w.params},b)},getTask:async(W)=>{let Q=await $.getTask(W,b);if(!Q)throw new u(i.InvalidParams,"Failed to retrieve task: Task not found");return Q},storeTaskResult:async(W,Q,X)=>{await $.storeTaskResult(W,Q,X,b);let G=await $.getTask(W,b);if(G){let J=l0.parse({method:"notifications/tasks/status",params:G});if(await this.notification(J),I1(G.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return $.getTaskResult(W,b)},updateTaskStatus:async(W,Q,X)=>{let G=await $.getTask(W,b);if(!G)throw new u(i.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(I1(G.status))throw new u(i.InvalidParams,`Cannot update task "${W}" from terminal status "${G.status}" to "${Q}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(W,Q,X,b);let J=await $.getTask(W,b);if(J){let Y=l0.parse({method:"notifications/tasks/status",params:J});if(await this.notification(Y),I1(J.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return $.listTasks(W,b)}}}}function zG(w){return w!==null&&typeof w==="object"&&!Array.isArray(w)}function DG(w,b){let $={...w};for(let W in b){let Q=W,X=b[Q];if(X===void 0)continue;let G=$[Q];if(zG(G)&&zG(X))$[Q]={...G,...X};else $[Q]=X}return $}var lH=BW(F9(),1),gH=BW(mH(),1);function PM(){let w=new lH.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return gH.default(w),w}class P9{constructor(w){this._ajv=w??PM()}getValidator(w){let b="$id"in w&&typeof w.$id==="string"?this._ajv.getSchema(w.$id)??this._ajv.compile(w):this._ajv.compile(w);return($)=>{if(b($))return{valid:!0,data:$,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(b.errors)}}}}class I9{constructor(w){this._server=w}requestStream(w,b,$){return this._server.requestStream(w,b,$)}async getTask(w,b){return this._server.getTask({taskId:w},b)}async getTaskResult(w,b,$){return this._server.getTaskResult({taskId:w},b,$)}async listTasks(w,b){return this._server.listTasks(w?{cursor:w}:void 0,b)}async cancelTask(w,b){return this._server.cancelTask({taskId:w},b)}}function iH(w,b,$){if(!w)throw Error(`${$} does not support task creation (required for ${b})`);switch(b){case"tools/call":if(!w.tools?.call)throw Error(`${$} does not support task creation for tools/call (required for ${b})`);break;default:break}}function nH(w,b,$){if(!w)throw Error(`${$} does not support task creation (required for ${b})`);switch(b){case"sampling/createMessage":if(!w.sampling?.createMessage)throw Error(`${$} does not support task creation for sampling/createMessage (required for ${b})`);break;case"elicitation/create":if(!w.elicitation?.create)throw Error(`${$} does not support task creation for elicitation/create (required for ${b})`);break;default:break}}class N9 extends V${constructor(w,b){super(b);if(this._serverInfo=w,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(n0.options.map(($,W)=>[$,W])),this.isMessageIgnored=($,W)=>{let Q=this._loggingLevels.get(W);return Q?this.LOG_LEVEL_SEVERITY.get($)<this.LOG_LEVEL_SEVERITY.get(Q):!1},this._capabilities=b?.capabilities??{},this._instructions=b?.instructions,this._jsonSchemaValidator=b?.jsonSchemaValidator??new P9,this.setRequestHandler(W$,($)=>this._oninitialize($)),this.setNotificationHandler(Q$,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(F$,async($,W)=>{let Q=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:X}=$.params,G=n0.safeParse(X);if(G.success)this._loggingLevels.set(Q,G.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new I9(this)};return this._experimental}registerCapabilities(w){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=DG(this._capabilities,w)}setRequestHandler(w,b){let W=nb(w)?.method;if(!W)throw Error("Schema is missing a method literal");let Q;if(t1(W)){let G=W;Q=G._zod?.def?.value??G.value}else{let G=W;Q=G._def?.value??G.value}if(typeof Q!=="string")throw Error("Schema method literal must be a string");if(Q==="tools/call"){let G=async(J,Y)=>{let H=q1(i0,J);if(!H.success){let F=H.error instanceof Error?H.error.message:String(H.error);throw new u(i.InvalidParams,`Invalid tools/call request: ${F}`)}let{params:z}=H.data,B=await Promise.resolve(b(J,Y));if(z.task){let F=q1(s1,B);if(!F.success){let U=F.error instanceof Error?F.error.message:String(F.error);throw new u(i.InvalidParams,`Invalid task creation result: ${U}`)}return F.data}let A=q1(J6,B);if(!A.success){let F=A.error instanceof Error?A.error.message:String(A.error);throw new u(i.InvalidParams,`Invalid tools/call result: ${F}`)}return A.data};return super.setRequestHandler(w,G)}return super.setRequestHandler(w,b)}assertCapabilityForMethod(w){switch(w){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${w})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${w})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${w})`);break;case"ping":break}}assertNotificationCapability(w){switch(w){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${w})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${w})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${w})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${w})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${w})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(w){if(!this._capabilities)return;switch(w){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${w})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${w})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${w})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${w})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${w})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${w})`);break;case"ping":case"initialize":break}}assertTaskCapability(w){nH(this._clientCapabilities?.tasks?.requests,w,"Client")}assertTaskHandlerCapability(w){if(!this._capabilities)return;iH(this._capabilities.tasks?.requests,w,"Server")}async _oninitialize(w){let b=w.params.protocolVersion;return this._clientCapabilities=w.params.capabilities,this._clientVersion=w.params.clientInfo,{protocolVersion:dX.includes(b)?b:e4,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"},sb)}async createMessage(w,b){if(w.tools||w.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(w.messages.length>0){let $=w.messages[w.messages.length-1],W=Array.isArray($.content)?$.content:[$.content],Q=W.some((Y)=>Y.type==="tool_result"),X=w.messages.length>1?w.messages[w.messages.length-2]:void 0,G=X?Array.isArray(X.content)?X.content:[X.content]:[],J=G.some((Y)=>Y.type==="tool_use");if(Q){if(W.some((Y)=>Y.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!J)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(J){let Y=new Set(G.filter((z)=>z.type==="tool_use").map((z)=>z.id)),H=new Set(W.filter((z)=>z.type==="tool_result").map((z)=>z.toolUseId));if(Y.size!==H.size||![...Y].every((z)=>H.has(z)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(w.tools)return this.request({method:"sampling/createMessage",params:w},U$,b);return this.request({method:"sampling/createMessage",params:w},L$,b)}async elicitInput(w,b){switch(w.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=w;return this.request({method:"elicitation/create",params:W},Y6,b)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=w.mode==="form"?w:{...w,mode:"form"},Q=await this.request({method:"elicitation/create",params:W},Y6,b);if(Q.action==="accept"&&Q.content&&W.requestedSchema)try{let G=this._jsonSchemaValidator.getValidator(W.requestedSchema)(Q.content);if(!G.valid)throw new u(i.InvalidParams,`Elicitation response content does not match requested schema: ${G.errorMessage}`)}catch(X){if(X instanceof u)throw X;throw new u(i.InternalError,`Error validating elicitation response: ${X instanceof Error?X.message:String(X)}`)}return Q}}}createElicitationCompletionNotifier(w,b){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:w}},b)}async listRoots(w,b){return this.request({method:"roots/list",params:w},K$,b)}async sendLoggingMessage(w,b){if(this._capabilities.logging){if(!this.isMessageIgnored(w.level,b))return this.notification({method:"notifications/message",params:w})}}async sendResourceUpdated(w){return this.notification({method:"notifications/resources/updated",params:w})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var pH={name:"@sequenzy/mcp",version:"0.0.141",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"bunx --bun tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^7.0.2"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var E9=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],dH={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function NM(w){let $=(w??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return $.length>0?$:"https://sequenzy.com"}function ow(w){let b=w?.trim();return b?b:void 0}function b1(w){return encodeURIComponent(w)}function Dw(w,b){return`${w}${b}`}function Bw(w,b=""){return`/dashboard/company/${b1(w)}${b}`}function oH(w,b,$){return Dw(w,`${Bw(b,"/settings")}?tab=${encodeURIComponent($)}`)}function EM(w,b){let $=E9.map((W)=>[W,b?oH(w,b,W):""]);return Object.fromEntries($)}function B1(w={},b){let $=NM(b),W=ow(w.companyId),Q={},X=EM($,W);if(!W)return{appUrl:$,routeTemplates:dH,settingsTabValues:E9,urls:Q,settingsUrls:X};Q.dashboard=Dw($,Bw(W)),Q.campaigns=Dw($,Bw(W,"/campaign")),Q.landingPages=Dw($,Bw(W,"/landing-pages")),Q.sequences=Dw($,Bw(W,"/sequences")),Q.settings=Dw($,Bw(W,"/settings")),Q.emails=Dw($,Bw(W,"/emails")),Q.subscribers=Dw($,Bw(W,"/subscribers")),Q.sentEmails=Dw($,Bw(W,"/sent-emails")),Q.segments=Dw($,Bw(W,"/segments")),Q.metrics=Dw($,Bw(W,"/metrics")),Q.transactional=Dw($,Bw(W,"/transactional"));let G=ow(w.campaignId);if(G)Q.campaign=Dw($,Bw(W,`/campaign/${b1(G)}`)),Q.campaignPreview=`${Q.campaign}?step=review`;let J=ow(w.landingPageId);if(J)Q.landingPage=Dw($,Bw(W,`/landing-pages/${b1(J)}`));let Y=ow(w.sequenceId);if(Y)Q.sequence=Dw($,Bw(W,`/sequences/${b1(Y)}`));let H=ow(w.emailId)??ow(w.templateId);if(H)Q.email=Dw($,Bw(W,`/emails/${b1(H)}`)),Q.template=Q.email;let z=ow(w.transactionalId);if(z)Q.transactionalEmail=Dw($,Bw(W,`/transactional/${b1(z)}`));let B=ow(w.emailSendId);if(B)Q.emailSend=Dw($,Bw(W,`/sent-emails/${b1(B)}`));let A=ow(w.domainId);if(A)Q.domain=Dw($,Bw(W,`/settings/domain/${b1(A)}`)),Q.domainVerify=`${Q.domain}/verify`;let F=ow(w.status);if(F)Q.campaignList=Dw($,Bw(W,`/campaign/list/${b1(F)}`)),Q.sequenceList=Dw($,Bw(W,`/sequences/list/${b1(F)}`));let U=ow(w.settingsTab);if(U)Q.settingsTab=oH($,W,U);return{appUrl:$,routeTemplates:dH,settingsTabValues:E9,urls:Q,settingsUrls:X}}var tH=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function rH(w){try{let b;switch(w){case"sequenzy://dashboard":b=await D("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await D("GET","/api/v1/account"),W=O1()??$.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");b=await D("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":b=await D("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":b=await D("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":b=await D("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":b=await D("GET","/api/v1/sequences");break;case"sequenzy://templates":b=await D("GET","/api/v1/templates");break;case"sequenzy://segments":b=await D("GET","/api/v1/segments");break;case"sequenzy://tags":b=await D("GET","/api/v1/tags");break;case"sequenzy://health":b=await D("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":b=B1();break;default:throw Error(`Unknown resource: ${w}`)}return{contents:[{uri:w,mimeType:"application/json",text:JSON.stringify(b,null,2)}]}}catch(b){return{contents:[{uri:w,mimeType:"text/plain",text:K1(b)}]}}}function C(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}function L(w,b){let $=w[b];if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function T9(w,b,$){let W=b[$];if(W===void 0||W===null)return[];if(typeof W==="string"){let X=W.trim();return X.length>0?[X]:[]}if(!Array.isArray(W))throw Error(`\`${$}\` must be an array of strings when calling \`${w}\`.`);let Q=[];return W.forEach((X,G)=>{if(typeof X!=="string")throw Error(`\`${$}\` item ${G+1} must be a string when calling \`${w}\`.`);let J=X.trim();if(J.length>0&&!Q.includes(J))Q.push(J)}),Q}function V(w,b,$){let W=L(b,$);if(W===void 0)throw Error(`\`${$}\` is required when calling \`${w}\`.`);return W}var d6=' Minimal valid core examples: {"type":"heading","content":"Title","level":1}; {"type":"text","content":"<p>Paragraph with <strong>bold</strong></p>","variant":"paragraph"}; {"type":"button","text":"Click Me","url":"https://example.com","variant":"primary"}; {"type":"image","src":"https://...","alt":"Description","width":100,"widthType":"percent","height":240,"objectFit":"cover","href":"https://example.com","align":"center"}. Heading and text use `content`; button uses `text` but also accepts `content` as an alias and defaults `variant` to `primary`. Image `widthType` accepts `percent` or `px`.';var R9=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "commerceCollection", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',S9=' Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). `accentColor` recolors every appearance, including "brutal". `optionRadius` sets answer-button corners in px (0 is square) independently of `styles.borderRadius`, while `questionColor` recolors only the question. `fontFamily` applies to the poll; `optionFontSize`, `optionFontWeight`, `optionLetterSpacing`, and `optionTextTransform` style answers, and the matching `questionFontSize`, `questionFontWeight`, `questionLetterSpacing`, and `questionTextTransform` fields style the question. Sizes and spacing are px, weights are 100-900, and transforms are "none" or "uppercase". Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page.',v9=' For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',Hw="Raw HTML is stored as one opaque block. Sequenzy preserves that markup but does not add a company logo, branded native sections, or theme-driven block design. Use blocks for editor-native design, or a drafting prompt when you want Sequenzy to compose a new branded email.",o6=' The code is minted per subscriber at run time and reaches every later email in the same sequence as {{discount.code}}. Also available: {{discount.value}} (pre-formatted, e.g. "20% off" or "$10 off"), {{discount.percentOff}}, {{discount.amountOff}}, {{discount.currency}}, and {{date.discount.expiresAt}} (locale-formatted expiry). Present the code with a { "type": "discount-code", "code": "{{discount.code}}", "label": "Your discount code" } block, or inline {{discount.code}} in any text block. These tags resolve only in emails downstream of the discount step; render_email substitutes a clearly fake sample code so the email can be previewed before anyone is enrolled, and lists anything it could not resolve under unresolvedMergeTags.',k1='For exact historical Poll/NPS respondents, use field `pollResponse`, operator `is`, and a JSON value shaped like {"v":1,"campaignId":"camp_123","blockId":"poll_1","match":{"kind":"answer","value":"loved"}}. For NPS buckets, use match {"kind":"npsBucket","bucket":"promoters"}; bucket may be `promoters`, `passives`, or `detractors`.',C9=" `styles` applies to the block's own container, not to an inner rendered element. On a button block, `styles.backgroundColor` colors the band behind the button and `styles.textColor` does not reach the label - set the top-level `buttonColor` and `buttonTextColor` fields instead, or leave them unset to inherit the email theme's primary color.",g1=" Unsupported fields are discarded and reported in the response `warnings` array rather than rejected.",A1=`Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the \`html\` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.${R9}${C9}${g1}${S9}${v9}${d6}`,t6=" Replacing a step's blocks keeps that step's existing Style > Format rather than the company default: a step that already had a logo or footer gets them back even if you omit them, and every block added that way is listed in the response `warnings`. Pass `emailPreset` to change the format. A step whose stored content is a single raw HTML block has no format, so replacing it with another single raw HTML block is stored exactly as sent; replacing it with native blocks converts the step and does add a footer.",TM=` For action_email:${t6}`,F1=`Replacement Sequenzy email blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`.${R9}${C9}${g1}${S9}${v9}${d6}`,z0=`Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer \`html\`; Sequenzy stores it as one raw HTML block and does not recreate it as native blocks. Use \`styles\` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as \`backgroundColor\`, \`backgroundOpacity\`, \`borderColor\`, \`borderWidth\`, and \`borderRadius\` are also accepted and saved under \`styles\`. Blocks can include repeat blocks over array variables such as items.${R9}${C9}${g1}${S9}${v9}${d6}`,Ub="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",sH="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",k9=500,_9=500,kw={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},Kb=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay","transport_failure"],Ob=Kb.join(", "),r6={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},RM={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},D0={type:"object",description:"Wait until a date from the trigger event before this step. Use this for renewal reminders, appointment follow-ups, trial-expiry nudges, and other subscriber-specific dates. The field value must be an ISO date string or Unix timestamp.",properties:{field:{type:"string",description:"Dot-path into the trigger event properties, e.g. renews_at or booking.startsAt."},untilDateField:{type:"string",description:"Alias for field."},offset:RM,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},B0={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date"],description:"Use duration for a fixed wait, or until_date to resolve a date from the trigger event."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},x9={type:"object",description:`Type-aware patch for the existing node. Start from get_sequence.sequence.nodes[].config. For logic_delay, set exactly one of delay ({ days, hours, minutes }), delayMs, or waitUntil; optional label is also accepted. For action_email, use name/label, subject, previewText, html/htmlContent or blocks, emailPreset, isTransactional, attachments ([{ filename, path }] URL-backed files fetched at send time; path may use {{event.*}} from the enrollment event; [] removes them), and sender/reply identity fields. For action_sms, use text, blocks, imageUrls, label, or ineligibleAction. Other node types accept their editable config keys. Managed IDs, nodeType conversion, and branch path IDs/count are not editable here; use edit_sequence_graph for topology. Webhook header patches are merged, and redacted values from get_sequence must be omitted or replaced with a real new value.${TM}`,properties:{emailPreset:{type:"string",enum:["branded","minimal"],description:"For an action_email node with native Sequenzy blocks, set the linked email's per-email Style > Format. Native block emails may include supported custom HTML blocks. Use minimal for a direct text-forward note without the company logo and with the simple footer, or branded to restore branded chrome. This does not change the company-wide default. A standalone raw HTML email does not support this field, and emailPreset must not be combined with html/htmlContent."}},additionalProperties:!0},s6={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:x9,expectedUpdatedAt:{type:"string",description:"Required optimistic-concurrency value from get_sequence.sequence.nodes[].updatedAt. The update is rejected if that node or its linked email content changed after it was read."}},required:["nodeId","changes","expectedUpdatedAt"],additionalProperties:!1},A0=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],F0=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.failed","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.created","subscriber.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","sequence.finished","sequence.failed","poll.answered"];var SM=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_api_keys","list_websites","list_integrations","get_integration","get_integration_pixel","list_integration_capabilities","list_integration_activity","list_sender_profiles","get_notification_preferences","get_tracking_settings","check_website","get_integration_guide","get_subscriber","get_subscriber_import","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_campaign_audience","render_email","list_email_sends","get_email_send","list_forms","get_form_embed","get_recipient_suppression","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_sequence_enrollments","list_sequence_goals","get_sequence_inbound_webhook","list_transactional_emails","get_transactional_email","get_stats","get_transactional_stats","get_campaign_stats","get_sequence_stats","list_campaign_events","list_sequence_events","list_email_metrics","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_subject_lines","generate_sms","get_sms_settings"]),vM=new Set(["select_company","create_company","update_company","update_notification_preferences","update_sender_profile","update_tracking_settings","update_sync_rules","update_shopify_automation_settings","connect_integration","set_integration_sync_enabled","sync_integration","activate_integration_pixel","create_api_key","update_api_key","revoke_api_key","delete_api_key","add_sending_domain","add_website","verify_sending_domain","add_subscriber","create_subscriber_import","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","trigger_subscriber_event","trigger_subscriber_events","bulk_add_subscriber_tags","bulk_remove_subscriber_tags","upsert_products","delete_product","attach_product_file","remove_product_file","upload_image_asset","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","set_template_localization","sync_template_localizations","delete_template","restart_ab_test","update_ab_test_variant","update_ab_test","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","unschedule_campaign","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_form","update_form","create_landing_page","update_landing_page","duplicate_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","generate_sequence","send_sequence_test_email","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","duplicate_sequence","archive_sequence","unarchive_sequence","create_sequence_goal","update_sequence_goal","delete_sequence_goal","configure_sequence_inbound_webhook","rotate_sequence_inbound_webhook_secret","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","delete_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback","remove_recipient_suppression"]),CM=new Set(["send_test_email","send_test_sms","send_sequence_test_email","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","add_sending_domain","add_website","verify_sending_domain","connect_integration","sync_integration","get_integration_pixel","activate_integration_pixel","enable_sequence","unarchive_sequence","resume_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery","remove_recipient_suppression"]),kM=new Set(["revoke_api_key","delete_api_key","remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","bulk_remove_subscriber_tags","delete_segment","delete_audience_sync","delete_template","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","set_integration_sync_enabled","disable_sequence","archive_sequence","delete_sequence_goal","rotate_sequence_inbound_webhook_secret","edit_sequence_graph","cancel_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook","delete_transactional_email","remove_recipient_suppression"]);function _M(w){let b=SM.has(w),$=vM.has(w);if(b===$)throw Error(`MCP tool "${w}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:b,destructiveHint:b?!1:kM.has(w),openWorldHint:CM.has(w)}}function eH(w){return{...w,annotations:{...w.annotations,..._M(w.name)}}}var h9={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains","is","is_not"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],pollResponse:["is"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"],commerceProduct:["is","is_not","at_least","less_than_count"],commerceCollection:["is","is_not","at_least","less_than_count"]},xM=Object.entries(h9).map(([w,b])=>`${w}: ${b.join(", ")}`).join("; "),y9={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","pollResponse","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct","commerceCollection"],description:`Filter field. Use \`email\` with is/is_not for exact, case-insensitive address matching (allowlists and exclusions) and with contains/not_contains for domain or substring matching. Use \`phone\` with is_not_empty/is_empty to check whether a subscriber has a phone number, and \`smsStatus\` (is/is_not one of \`subscribed\`, \`unsubscribed\`, \`not_subscribed\`) for SMS marketing consent. Use \`event\` for custom subscriber events, \`segment\` for saved segment membership, \`stripeProduct\`/\`stripeCurrentProduct\`/\`stripeTrialProduct\` for Stripe product-based segments, and \`commerceProduct\` for products purchased through commerce orders - the value is \`provider:productId\` (provider one of \`shopify\`, \`woocommerce\`, \`api\`; product ids are provider-scoped), optionally with an order-count threshold (\`provider:productId:count\`) for at_least/less_than_count; a bare product id matches the id on any provider. Use \`commerceCollection\` to segment on anyone who bought ANY product in a store collection - the value is the collection id or handle (e.g. \`skincare\`), optionally provider-prefixed and/or with an order-count threshold (\`shopify:skincare:2\`); collection membership is resolved from the synced catalog as it stands now, and only Shopify collections and WooCommerce categories are synced. Engagement fields (\`emailSent\`, \`emailDelivered\`, \`emailOpened\`, \`emailClicked\`, \`emailBounced\`, \`emailComplained\`) accept a time range as the value, a specific campaign via \`campaign:<campaign_id>\`, or \`count:timeRange\` (e.g. \`10:30d\`, \`10:all\`) with at_least/less_than_count to segment by number of opens/clicks. ${k1}`},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${xM}.`},value:{type:"string",description:`Filter value. For custom attribute empty checks, use \`attributeName:\` such as \`last_logged_in:\`. Event examples: \`saas.purchase:30d\`, \`saas.purchase:all\`, or \`saas.purchase:5:30d\` for thresholds. Segment values are segment IDs. Stripe product examples: \`prod_123\` for bought/didn't buy/current/trialing, \`prod_123:3\` for payment thresholds, \`prod_123:is_canceled\` for products set to cancel, \`prod_123:cancels_at:2026-05-26\`, \`prod_123:end_at:2026-05-26\`, or \`prod_123:start_at:7 days ago\` for product-scoped dates. Engagement examples: \`7d\`, \`30d\`, \`90d\`, \`180d\`, \`all\` for rolling time windows, \`campaign:<campaign_id>\` to scope to a specific sent campaign (use \`list_campaigns\` to find IDs), or \`count:timeRange\` like \`10:30d\` / \`10:all\` with at_least/less_than_count operators (e.g. emailClicked at_least \`10:all\` = clicked 10 or more times ever). ${k1}`}},required:["field","operator","value"],additionalProperties:!1},f9={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function e6(w){if(!Array.isArray(w))return w;return w.map((b)=>{if(typeof b!=="object"||b===null)return b;let $=b;if(typeof $.id==="string"&&$.id.trim()!=="")return $;return{...$,id:crypto.randomUUID()}})}function a6(w){if(typeof w!=="object"||w===null)return w;let b=w;if(b.kind==="filter"||"field"in b||"operator"in b||"value"in b){let $=e6([b]);return Array.isArray($)?$[0]:b}if(b.kind!=="group")return w;return{...b,id:typeof b.id==="string"&&b.id.trim()!==""?b.id:crypto.randomUUID(),children:Array.isArray(b.children)?b.children.map(a6):[]}}function hM(w){let b=w.indexOf(":");return b!==-1&&w.substring(0,b).trim().length>0}function yM(w){let b=w.indexOf(":");return b!==-1&&w.substring(b+1).trim().length>0}function aH(w){if(w==="all")return!0;let b=w.match(/^(\d+)d$/);if(!b?.[1])return!1;let $=Number.parseInt(b[1],10);return Number.isInteger($)&&$>0}function fM(w,b){let $=b.split(":");if(w==="at_least"||w==="less_than_count"){if($.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let X=$.slice(0,-2).join(":").trim(),G=$.at(-2),J=$.at(-1),Y=G===void 0?Number.NaN:Number.parseInt(G,10);return X&&Number.isInteger(Y)&&Y>0&&J!==void 0&&aH(J)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if($.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=$.slice(0,-1).join(":").trim(),Q=$.at(-1);return W&&Q!==void 0&&aH(Q)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function uM(w){let b=w.indexOf(":");if(b===-1)return{productId:w,subfilter:null,rawValue:null};let $=w.substring(0,b),W=w.substring(b+1),Q=W.indexOf(":");if(Q===-1)return{productId:$,subfilter:W,rawValue:null};return{productId:$,subfilter:W.substring(0,Q),rawValue:W.substring(Q+1)}}function cM(w){return w.trim().toLowerCase().replace(/[-\s]+/g,"_")}function mM(w){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(w)}function lM(w,b){if(b==="cancels_at"||b==="cancel_at"||b==="cancellation_at")return!0;if(w==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(b);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(b)}function gM(w){return["is","is_not","gte","lte","gt","lt"].includes(w)}function iM(w,b,$){if(w==="stripeProduct"){if(b!=="at_least"&&b!=="less_than_count")return null;let J=$.indexOf(":");if(J===-1)return null;let Y=$.substring(0,J).trim(),H=Number.parseInt($.substring(J+1).trim(),10);return Y&&Number.isInteger(H)&&H>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(w!=="stripeCurrentProduct"&&w!=="stripeTrialProduct")return null;let{productId:W,subfilter:Q,rawValue:X}=uM($);if(!W.trim())return"Stripe product filters must include a product ID.";if(!Q)return b==="is"||b==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let G=cM(Q);if(mM(G))return b==="is"||b==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!lM(w,G))return`Unsupported Stripe product subfilter "${Q}".`;if(!gM(b))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return X?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var w5=new Set(["shopify","woocommerce","api"]);function nM(w,b){let $=b.trim(),W=$.indexOf(":");if(W!==-1&&w5.has($.substring(0,W).trim()))$=$.substring(W+1).trim();if(!$)return'Purchased Product filters must include a product ID, like "shopify:42".';if(w!=="at_least"&&w!=="less_than_count")return null;let Q=$.lastIndexOf(":");if(Q===-1)return null;let X=$.substring(0,Q).trim(),G=Number.parseInt($.substring(Q+1).trim(),10);return X&&Number.isInteger(G)&&G>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function pM(w,b){let $=b.trim(),W=$.indexOf(":");if(W!==-1&&w5.has($.substring(0,W).trim()))$=$.substring(W+1).trim();if(!$)return'Purchased Collection filters must include a collection, like "shopify:summer-sale".';if(w!=="at_least"&&w!=="less_than_count")return null;let Q=$.lastIndexOf(":");if(Q===-1)return null;let X=$.substring(0,Q).trim(),G=Number.parseInt($.substring(Q+1).trim(),10);return X&&Number.isInteger(G)&&G>=1?null:'Purchased Collection threshold filters must use "provider:collection:count" with a count of at least 1.'}function dM(w){let b;try{b=JSON.parse(w)}catch{return`Poll response filters must use valid JSON. ${k1}`}if(!C(b)||b.v!==1||typeof b.campaignId!=="string"||!b.campaignId.trim()||typeof b.blockId!=="string"||!b.blockId.trim()||!C(b.match))return`Poll response filter context is invalid. ${k1}`;let $=b.match;if($.kind==="answer"&&typeof $.value==="string"&&$.value.length>0)return null;if($.kind==="npsBucket"&&($.bucket==="promoters"||$.bucket==="passives"||$.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${k1}`}function w4(w){if(typeof w!=="object"||w===null)return"Segment filters must be objects.";let b=w,$=b.field,W=b.operator,Q=b.value;if(typeof $!=="string"||!($ in h9))return`Unsupported segment filter field "${String($)}".`;if(typeof W!=="string")return`Segment filter "${$}" must include an operator.`;let X=h9[$];if(!X.includes(W))return`Operator "${W}" is not supported for ${$} filters. Use one of: ${X.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof Q!=="string"||Q.trim().length===0))return`Segment filter "${$}" must include a value.`;if($==="attribute"&&typeof Q==="string"){if(!hM(Q))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!yM(Q))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof Q==="string"){let G=fM(W,Q);if(G)return G}if($==="pollResponse"&&typeof Q==="string"){let G=dM(Q);if(G)return G}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof Q==="string"){let G=iM($,W,Q);if(G)return G}if($==="commerceProduct"&&typeof Q==="string"){let G=nM(W,Q);if(G)return G}if($==="commerceCollection"&&typeof Q==="string"){let G=pM(W,Q);if(G)return G}if($==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof Q==="string"&&Q.split(",").map((J)=>J.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function b4(w){if(typeof w!=="object"||w===null)return[];let b=w;if(b.kind==="filter"||"field"in b||"operator"in b||"value"in b){let $=w4(b);return $?[$]:[]}if(Array.isArray(b.children))return b.children.flatMap(b4);return[]}function _w(w,b,$){if(b.html!==void 0&&b.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${w}\`, not both.`);if(b.blocks!==void 0&&!Array.isArray(b.blocks))throw Error(`\`blocks\` must be an array when calling \`${w}\`.`);if($?.requireContent&&b.html===void 0&&b.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${w}\`.`)}function L1(w,b){if(b.labels===void 0)return;if(!Array.isArray(b.labels))throw Error(`\`labels\` must be an array when calling \`${w}\`.`);if(b.labels.some(($)=>typeof $!=="string"||$.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${w}\`.`)}function W5(w){let b=w.filters!==void 0,$=w.root!==void 0;if(b&&$)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!b&&!$)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(b){if(!Array.isArray(w.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(w.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if($&&(typeof w.root!=="object"||w.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=b?w.filters.flatMap((Q)=>{let X=w4(Q);return X?[X]:[]}):b4(w.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function Q5(w){let b=w.filters!==void 0,$=w.root!==void 0;if(b&&$)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(w.name===void 0&&w.filterJoinOperator===void 0&&!b&&!$)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(b){if(!Array.isArray(w.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(w.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if($&&(typeof w.root!=="object"||w.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=b?w.filters.flatMap((Q)=>{let X=w4(Q);return X?[X]:[]}):$?b4(w.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var u9=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailTheme","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingEnabled","replyTrackingDomainMode","forwardReplies"];function c9(w,b,$){if(b[$]!==void 0&&!C(b[$]))throw Error(`\`${$}\` must be an object when calling \`${w}\`.`)}function b5(w,b,$){if(b[$]!==void 0&&!Array.isArray(b[$]))throw Error(`\`${$}\` must be an array when calling \`${w}\`.`)}function X5(w){let b=new Set(["companyId",...u9]),$=Object.keys(w).filter((Q)=>!b.has(Q));if($.length>0)throw Error(`\`update_company\` accepts only editable company settings. Unsupported field${$.length===1?"":"s"}: ${$.map((Q)=>`\`${Q}\``).join(", ")}.`);let W={};for(let Q of u9)if(w[Q]!==void 0)W[Q]=w[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${u9.map((Q)=>`\`${Q}\``).join(", ")} when calling \`update_company\`.`);for(let Q of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingDomainMode"])if(w[Q]!==void 0&&typeof w[Q]!=="string")throw Error(`\`${Q}\` must be a string when calling \`update_company\`.`);if(c9("update_company",w,"brandColors"),c9("update_company",w,"socialLinks"),c9("update_company",w,"pricing"),w.emailTheme!==void 0&&w.emailTheme!==null&&!C(w.emailTheme))throw Error("`emailTheme` must be an object or null when calling `update_company`.");b5("update_company",w,"valueProps"),b5("update_company",w,"testimonials");for(let Q of["replyTrackingEnabled","forwardReplies"])if(w[Q]!==void 0&&typeof w[Q]!=="boolean")throw Error(`\`${Q}\` must be a boolean when calling \`update_company\`.`);if(w.replyTrackingDomainMode!==void 0&&w.replyTrackingDomainMode!=="sequenzy"&&w.replyTrackingDomainMode!=="custom")throw Error("`replyTrackingDomainMode` must be `sequenzy` or `custom` when calling `update_company`.");if(typeof w.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(w.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let Q of["fromEmail","replyTo"]){let X=w[Q];if(typeof X==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(X.trim()))throw Error(`\`${Q}\` must be a valid email address when calling \`update_company\`.`)}return W}var m9=["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","defaultAttributionWindowHours","doubleOptInEnabled","autoUtmEnabled","autoUtmSettings"],l9=["source","medium","campaign","content","term"];function G5(w){let b=new Set(["companyId",...m9]),$=Object.keys(w).filter((Q)=>!b.has(Q));if($.length>0)throw Error(`\`update_tracking_settings\` accepts only tracking settings. Unsupported field${$.length===1?"":"s"}: ${$.map((Q)=>`\`${Q}\``).join(", ")}. Reply tracking is set with \`update_company\`.`);let W={};for(let Q of m9)if(w[Q]!==void 0)W[Q]=w[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${m9.map((Q)=>`\`${Q}\``).join(", ")} when calling \`update_tracking_settings\`.`);for(let Q of["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","doubleOptInEnabled","autoUtmEnabled"])if(w[Q]!==void 0&&typeof w[Q]!=="boolean")throw Error(`\`${Q}\` must be a boolean when calling \`update_tracking_settings\`.`);if(w.defaultAttributionWindowHours!==void 0&&(typeof w.defaultAttributionWindowHours!=="number"||!Number.isInteger(w.defaultAttributionWindowHours)||w.defaultAttributionWindowHours<1||w.defaultAttributionWindowHours>720))throw Error("`defaultAttributionWindowHours` must be a whole number of hours between 1 and 720 when calling `update_tracking_settings`.");if(w.autoUtmSettings!==void 0&&w.autoUtmSettings!==null&&!C(w.autoUtmSettings))throw Error("`autoUtmSettings` must be an object or null when calling `update_tracking_settings`.");if(C(w.autoUtmSettings)){let Q=w.autoUtmSettings,X=Object.keys(Q).filter((G)=>!l9.includes(G));if(X.length>0)throw Error(`\`autoUtmSettings\` accepts only ${l9.map((G)=>`\`${G}\``).join(", ")}. Unsupported: ${X.map((G)=>`\`${G}\``).join(", ")}.`);for(let G of l9){let J=Q[G];if(J!==void 0&&J!==null&&typeof J!=="string")throw Error(`\`autoUtmSettings.${G}\` must be a string or null when calling \`update_tracking_settings\`.`)}}return W}var i9={profileKey:"senderProfileId",emailKey:"fromEmail",nameKey:"fromName",addressLabel:"From"},n9={profileKey:"replyProfileId",emailKey:"replyTo",nameKey:"replyToName",addressLabel:"Reply-To"};function p9(w){let{profileKey:b,emailKey:$,nameKey:W,addressLabel:Q}=w.pair,X=w.args[b]!==void 0,G=w.args[$]!==void 0,J=w.args[W]!==void 0,Y=w.location?`for ${w.location} when calling \`${w.toolName}\``:`when calling \`${w.toolName}\``,H=`\`${b}\` already sets both the ${Q} address and the display name, so send it without \`${$}\`${w.nameIsOverride?"":` and \`${W}\``}.`;if(X&&G){let[z,B]=w.profileFirst?[b,$]:[$,b];throw Error(`Provide either \`${z}\` or \`${B}\` ${Y}, not both. ${H}`)}if(X&&J&&!w.nameIsOverride)throw Error(`\`${W}\` cannot be combined with \`${b}\` ${Y}. ${H}`);if(J&&!G&&!w.nameIsOverride)throw Error(`\`${W}\` requires \`${$}\` ${Y}. Send \`${W}\` with the \`${$}\` it names, or send \`${b}\` on its own to use an existing profile's address and name.`)}function L0(w,b,$){let W=$?.replyFirst?[n9,i9]:[i9,n9];for(let Q of W)p9({toolName:w,args:b,pair:Q})}var J5=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function oM(w){return J5.some((b)=>w[b]!==void 0)}function tM(w){if(typeof w.nodeType==="string")return w.nodeType==="action_email";return w.type===void 0||w.type==="email"}function $4(w,b,$){for(let W of J5){let Q=$[W];if(Q!==void 0&&typeof Q!=="string")throw Error(`\`${W}\` must be a string for ${b} when calling \`${w}\`.`)}p9({toolName:w,args:$,pair:i9,location:b,profileFirst:!0,nameIsOverride:!0}),p9({toolName:w,args:$,pair:n9,location:b,profileFirst:!0})}function d9(w,b,$){if(oM($)&&!tM($))throw Error(`Sender identity fields are only supported for email steps at ${b} when calling \`${w}\`.`);$4(w,b,$)}function $5(w,b,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(C(W))$4(w,`${b}[${Q}]`,W)})}function g9(w,b,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(C(W))d9(w,`${b}[${Q}]`,W)})}function rM(w){if($5("update_sequence","emails",w.emails),$5("update_sequence","steps",w.steps),C(w.insertSteps))g9("update_sequence","insertSteps.steps",w.insertSteps.steps);if(!C(w.branch))return;if(Array.isArray(w.branch.branches))w.branch.branches.forEach(($,W)=>{if(C($))g9("update_sequence",`branch.branches[${W}].steps`,$.steps)});g9("update_sequence","branch.elseSteps",w.branch.elseSteps)}function Y5(w){L1("update_sequence",w);let b=["listId","tagName","segmentId","stopOnSegmentExit","eventName","propertyFilters","integrationSlug","integrationEventKey","customIntegration","inactiveDays","inactivityBaseline","minCount","timeWindowDays"];if(w.trigger===void 0&&b.some((W)=>w[W]!==void 0))throw Error("Provide `trigger` when replacing sequence trigger configuration with `update_sequence`.");if(L0("update_sequence",w),w.clearEnrollmentFieldPath===!0&&w.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(w.clearSendingWindow===!0&&w.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(w.clearBccEmails===!0&&w.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(w.branch!==void 0&&w.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");rM(w);let $={...w};if(delete $.clearEnrollmentFieldPath,delete $.clearSendingWindow,delete $.clearBccEmails,w.clearEnrollmentFieldPath===!0)$.enrollmentFieldPath=null;if(w.clearSendingWindow===!0)$.sendingWindow=null;if(w.clearBccEmails===!0)$.bccEmails=null;return $}function sM(w,b){if((b.triggerType??"event")==="event"){if(typeof b.triggerEventName!=="string"||b.triggerEventName.trim().length===0)throw Error(`\`triggerEventName\` is required when calling \`${w}\` with an event goal (the default \`triggerType\`).`);return}if(typeof b.attributePath!=="string"||b.attributePath.trim().length===0)throw Error(`\`attributePath\` is required when calling \`${w}\` with \`triggerType: "attribute_change"\`.`);let W=b.attributeCondition??"changed",Q=typeof b.attributeValue==="string"&&b.attributeValue.trim().length>0,X=typeof b.attributePreviousValue==="string"&&b.attributePreviousValue.trim().length>0;if((W==="changed_to"||W==="changed_from_to")&&!Q)throw Error(`\`attributeValue\` is required when calling \`${w}\` with \`attributeCondition\` \`changed_to\` or \`changed_from_to\`.`);if(W==="changed_from_to"&&!X)throw Error(`\`attributePreviousValue\` is required when calling \`${w}\` with \`attributeCondition: "changed_from_to"\`.`)}function H5(w){sM("create_sequence_goal",w)}function z5(w){if(typeof w.triggerEventName==="string"&&w.triggerEventName.trim().length===0)throw Error("`triggerEventName` must be a non-empty string when provided to `update_sequence_goal`.");if(typeof w.attributePath==="string"&&w.attributePath.trim().length===0)throw Error("`attributePath` must be a non-empty string when provided to `update_sequence_goal`.")}function B5(w,b,$){let W=V(w,b,"nodeId");if(!C(b.changes)||Object.keys(b.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${w}\`.`);let Q=V(w,b,"expectedUpdatedAt");return{nodeId:W,changes:b.changes,expectedUpdatedAt:Q}}function A5(w){let b=B5("update_sequence_node",w,"the node update");return{...w.confirmLiveChange!==void 0&&{confirmLiveChange:w.confirmLiveChange},nodeUpdates:[b]}}function F5(w){if(!Array.isArray(w.updates)||w.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let b=new Set,$=w.updates.map((W,Q)=>{if(!C(W))throw Error(`\`updates[${Q}]\` must be an object when calling \`update_sequence_nodes\`.`);let X=B5("update_sequence_nodes",W,`updates[${Q}]`),G=String(X.nodeId);if(b.has(G))throw Error(`\`updates[${Q}]\` targets duplicate nodeId '${G}' when calling \`update_sequence_nodes\`.`);return b.add(G),X});return{...w.confirmLiveChange!==void 0&&{confirmLiveChange:w.confirmLiveChange},nodeUpdates:$}}function L5(w){let b=V("edit_sequence_graph",w,"action"),$=V("edit_sequence_graph",w,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(b))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let Q=L(w,"nodeId"),X=L(w,"afterNodeId"),G=L(w,"beforeNodeId"),J=w.edges;if(b!=="replace_edges"&&!Q)throw Error(`\`nodeId\` is required for ${b} when calling \`edit_sequence_graph\`.`);if(b==="replace_edges"&&Q)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let Y=b==="move_node"||b==="duplicate_node";if(Y&&(X?1:0)+(G?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${b} when calling \`edit_sequence_graph\`.`);if(!Y&&(X||G))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${b} when calling \`edit_sequence_graph\`.`);if((b==="replace_edges"||b==="delete_node"&&J!==void 0)&&(!Array.isArray(J)||J.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${b} when calling \`edit_sequence_graph\`.`);if((b==="move_node"||b==="duplicate_node")&&J!==void 0)throw Error(`\`edges\` is not used with ${b} when calling \`edit_sequence_graph\`.`);let H=Array.isArray(J)?J.map((z,B)=>{if(!C(z))throw Error(`\`edges\` item ${B+1} must be an object when calling \`edit_sequence_graph\`.`);let A=V("edit_sequence_graph",z,"sourceNodeId"),F=V("edit_sequence_graph",z,"targetNodeId");if(z.condition!==void 0&&z.condition!==null&&!C(z.condition))throw Error(`\`edges\` item ${B+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:A,targetNodeId:F,...C(z.condition)?{condition:z.condition}:{}}}):void 0;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},graphEdit:{action:b,expectedRevision:$,...Q?{nodeId:Q}:{},...X?{afterNodeId:X}:{},...G?{beforeNodeId:G}:{},...H?{edges:H}:{}}}}function U5(w){let b=L(w,"type")??"email";if(!new Set(["email","sms","delay","create_discount","update_subscriber","condition","add_tag","remove_tag","add_to_list","remove_from_list","webhook","logic_wait_for_event","logic_branch"]).has(b))throw Error("`type` is not a supported dashboard sequence step when calling `insert_sequence_step`.");if(b==="logic_wait_for_event"){let G=V("insert_sequence_step",w,"eventName"),J=w.timeoutDays,Y=J===void 0?7:J;if(typeof Y!=="number"||!Number.isInteger(Y)||Y<1||Y>365)throw Error("`timeoutDays` must be a whole number from 1 to 365 when inserting `logic_wait_for_event` with `insert_sequence_step`.");let H=L(w,"timeoutAction")??"continue";if(H!=="continue"&&H!=="exit")throw Error("`timeoutAction` must be `continue` or `exit` when inserting `logic_wait_for_event` with `insert_sequence_step`.");let z={steps:[{nodeType:"logic_wait_for_event",config:{label:L(w,"label")??`Wait for ${G}`,eventName:G,timeoutDays:Y,timeoutAction:H}}]},B=L(w,"afterNodeId");if(B)z.afterNodeId=B;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:z}}if(b==="logic_branch"){let G=V("insert_sequence_step",w,"afterNodeId");if(!Array.isArray(w.branches)||w.branches.length===0)throw Error("`branches` must contain at least one typed condition when inserting `logic_branch` with `insert_sequence_step`.");let J=new Set(["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"]),Y=["id","label","conditionType","tagName","tagId","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue","targetNodeId","steps"],H=w.allowEmptyPaths===!0,z=w.branches.map((F,U)=>{if(!C(F))throw Error(`\`branches[${U}]\` must be an object when calling \`insert_sequence_step\`.`);let M=V("insert_sequence_step",F,"conditionType");if(!J.has(M))throw Error(`\`branches[${U}].conditionType\` is not supported when calling \`insert_sequence_step\`.`);let q=`branches[${U}]`;if((M==="has_tag"||M==="does_not_have_tag")&&!L(F,"tagId")&&!L(F,"tagName"))throw Error(`\`${q}\` must provide \`tagId\` or \`tagName\` for ${M} when calling \`insert_sequence_step\`.`);if(M==="in_list"&&!L(F,"listId"))throw Error(`\`${q}.listId\` is required for in_list when calling \`insert_sequence_step\`.`);if(M==="in_segment"&&!L(F,"segmentId"))throw Error(`\`${q}.segmentId\` is required for in_segment when calling \`insert_sequence_step\`.`);if(M==="event_received"&&!L(F,"eventName"))throw Error(`\`${q}.eventName\` is required for event_received when calling \`insert_sequence_step\`.`);if(M.startsWith("field_")&&(!L(F,"fieldName")||!L(F,"fieldValue")))throw Error(`\`${q}\` must provide \`fieldName\` and \`fieldValue\` for ${M} when calling \`insert_sequence_step\`.`);if(F.steps!==void 0&&!Array.isArray(F.steps))throw Error(`\`branches[${U}].steps\` must be an array when calling \`insert_sequence_step\`.`);let P=L(F,"targetNodeId"),k=Array.isArray(F.steps)&&F.steps.length>0;if(!P&&!k&&!H)throw Error(`\`branches[${U}]\` must provide \`targetNodeId\` or non-empty \`steps\` when inserting \`logic_branch\` with \`insert_sequence_step\`.`);return Object.fromEntries(Y.flatMap((S)=>F[S]===void 0?[]:[[S,F[S]]]))});if(w.elseSteps!==void 0&&!Array.isArray(w.elseSteps))throw Error("`elseSteps` must be an array when calling `insert_sequence_step`.");let B=L(w,"elseTargetNodeId"),A=Array.isArray(w.elseSteps)&&w.elseSteps.length>0;if(!B&&!A&&!H)throw Error("Provide `elseTargetNodeId` or non-empty `elseSteps` when inserting `logic_branch` with `insert_sequence_step`.");return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},branch:{afterNodeId:G,...L(w,"label")?{label:L(w,"label")}:{},branches:z,...Array.isArray(w.elseSteps)?{elseSteps:w.elseSteps}:{},...B?{elseTargetNodeId:B}:{},...H?{allowEmptyPaths:!0}:{}}}}if(b==="delay"||b==="create_discount"||b==="update_subscriber"||b==="condition"||b==="add_tag"||b==="remove_tag"||b==="add_to_list"||b==="remove_from_list"||b==="webhook"){let G;if(b==="delay"){G={type:"delay"};for(let H of["delay","delayMs","waitUntil"])if(w[H]!==void 0)G[H]=w[H];if(G.delay===void 0&&G.delayMs===void 0&&G.waitUntil===void 0)throw Error("Provide `delay`, `delayMs`, or `waitUntil` when inserting a delay step.")}else if(b==="create_discount"){G={type:"create_discount"};for(let H of["discount","label","provider","discountType","percentOff","amountOff","currency","duration","durationInMonths","appliesToAllPlans","planIds","codePrefix","maxRedemptions","lockToSubscriber","expiresAt","expiresInHours"])if(w[H]!==void 0)G[H]=w[H]}else if(b==="update_subscriber"){if(!C(w.config))throw Error("`config` is required when inserting an update_subscriber step.");G={type:"update_subscriber",nodeType:"action_update_attributes",config:w.config}}else if(b==="webhook"){let H=L(w,"method")??"POST";if(!["POST","GET","PUT","PATCH","DELETE"].includes(H))throw Error("`method` must be one of POST, GET, PUT, PATCH, or DELETE when inserting a webhook step.");if(w.headers!==void 0&&(!C(w.headers)||Object.values(w.headers).some((F)=>typeof F!=="string")))throw Error("`headers` must be an object with string values when inserting a webhook step.");let z=L(w,"onError");if(z&&!["continue","exit","fail"].includes(z))throw Error("`onError` must be `continue`, `exit`, or `fail` when inserting a webhook step.");if(w.body!==void 0&&typeof w.body!=="string")throw Error("`body` must be a JSON string when inserting a webhook step.");if(w.resultKey!==void 0&&typeof w.resultKey!=="string")throw Error("`resultKey` must be a string when inserting a webhook step.");let B=L(w,"body"),A=L(w,"resultKey");G={type:"webhook",nodeType:"action_webhook",config:{label:L(w,"label")??"Webhook",url:V("insert_sequence_step",w,"url"),method:H,...w.headers!==void 0?{headers:w.headers}:{},...B?{body:B}:{},...A?{resultKey:A}:{},...z?{onError:z}:{}}}}else if(b==="condition"){let H=V("insert_sequence_step",w,"conditionType");if(!new Set(["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"]).has(H))throw Error("`conditionType` is not supported for condition steps.");if((H==="has_tag"||H==="does_not_have_tag")&&!L(w,"tagId")&&!L(w,"tagName"))throw Error("Provide `tagId` or `tagName` for this condition step.");if(H==="in_list"&&!L(w,"listId"))throw Error("`listId` is required for an in_list condition.");if(H==="in_segment"&&!L(w,"segmentId"))throw Error("`segmentId` is required for an in_segment condition.");if(H==="event_received"&&!L(w,"eventName"))throw Error("`eventName` is required for an event_received condition.");if(H.startsWith("field_")&&(!L(w,"fieldName")||!L(w,"fieldValue")))throw Error("`fieldName` and `fieldValue` are required for field conditions.");let B={label:L(w,"label")??"Condition",conditionType:H};for(let A of["tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"])if(w[A]!==void 0)B[A]=w[A];G={type:"condition",nodeType:"logic_condition",config:B}}else{let H=b==="add_tag"||b==="remove_tag",z=b==="add_tag"?"action_add_tag":b==="remove_tag"?"action_remove_tag":b==="add_to_list"?"action_add_to_list":"action_remove_from_list",B={label:L(w,"label")??(b==="add_tag"?"Add Tag":b==="remove_tag"?"Remove Tag":b==="add_to_list"?"Add to List":"Remove from List")};if(H){let A=L(w,"tagId"),F=L(w,"tagName");if(!A&&!F)throw Error("Provide `tagId` or `tagName` when inserting a tag action.");if(A)B.tagId=A;if(F)B.tagName=F}else{B.listId=V("insert_sequence_step",w,"listId");let A=L(w,"listName");if(A)B.listName=A}G={nodeType:z,config:B}}for(let H of["delay","delayMs","waitUntil"])if(b!=="delay"&&w[H]!==void 0)G[H]=w[H];let J={steps:[G]},Y=L(w,"afterNodeId");if(Y)J.afterNodeId=Y;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:J}}let W=b==="sms",Q;if(W){d9("insert_sequence_step","SMS step",w);let G=L(w,"text"),J=Array.isArray(w.blocks)&&w.blocks.length>0;if(G===void 0&&!J)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");Q={type:"sms"};for(let Y of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(w[Y]!==void 0)Q[Y]=w[Y]}else{_w("insert_sequence_step",w,{requireContent:!0}),$4("insert_sequence_step","email step",w),Q={subject:V("insert_sequence_step",w,"subject")};for(let G of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","isTransactional","ccEmails","bccEmails","attachments"])if(w[G]!==void 0)Q[G]=w[G]}let X={steps:[Q]};if(w.afterNodeId!==void 0)X.afterNodeId=w.afterNodeId;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:X}}function D5(w,b){let $=w[b];if($===void 0)return[];if(!Array.isArray($))throw Error(`\`${b}\` must be an array when calling \`cancel_sequence_enrollments\`.`);let W=$.map((Q)=>typeof Q==="string"?Q.trim():"").filter((Q)=>Q.length>0);if($.some((Q)=>typeof Q!=="string")||W.length===0)throw Error(`\`${b}\` must contain at least one non-empty string when calling \`cancel_sequence_enrollments\`.`);return W}function K5(w){let b=L(w,"subscriberId"),$=D5(w,"subscriberIds"),W=D5(w,"fieldValues");if(w.cancelAll!==void 0&&typeof w.cancelAll!=="boolean")throw Error("`cancelAll` must be a boolean when calling `cancel_sequence_enrollments`.");let Q=w.cancelAll===!0;if((b!==void 0?1:0)+($.length>0?1:0)+(W.length>0?1:0)+(Q?1:0)!==1)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `cancelAll`, `subscriberId`, `subscriberIds`, or `fieldValues`.");let G=L(w,"fieldPath"),J=L(w,"reason");return{...Q&&{cancelAll:!0},...b!==void 0&&{subscriberId:b},...$.length>0&&{subscriberIds:$},...G!==void 0&&{fieldPath:G},...W.length>0&&{fieldValues:W},...typeof w.dryRun==="boolean"&&{dryRun:w.dryRun},...J!==void 0&&{reason:J}}}function O5(w){_w("create_campaign",w),L1("create_campaign",w);let b=L(w,"prompt")!==void 0,$=w.html!==void 0,W=w.blocks!==void 0,Q=w.templateId!==void 0;if(w.prompt!==void 0&&!b)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(b&&($||W||Q))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!b&&(w.style!==void 0||w.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!b&&L(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function Z5(w){_w("create_template",w),L1("create_template",w);let b=L(w,"prompt")!==void 0,$=[b,w.html!==void 0,w.blocks!==void 0].filter(Boolean).length;if(w.prompt!==void 0&&!b)throw Error("`prompt` cannot be empty when calling `create_template`.");if($!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!b&&(w.style!==void 0||w.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!b&&L(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function V5(w){if(L(w,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(w.targetLists!==void 0&&!C(w.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(w.sendTimeOptimization!==void 0){if(typeof w.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(w.spreadOverHours!==void 0){if(typeof w.spreadOverHours!=="number"||!Number.isInteger(w.spreadOverHours)||w.spreadOverHours<1||w.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(w.recurringInterval!==void 0&&w.recurringInterval!=="weekly"&&w.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function W4(w,b,$){let W=new Set(["companyId","landingPageId","name","slug","content"]),Q=Object.keys(b).filter((X)=>!W.has(X));if(Q.length>0)throw Error(`\`${w}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${Q.length===1?"":"s"}: ${Q.map((X)=>`\`${X}\``).join(", ")}.`);if($.requireUpdate&&b.name===void 0&&b.slug===void 0&&b.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${w}\`.`);return{...b.name!==void 0&&{name:b.name},...b.slug!==void 0&&{slug:b.slug},...b.content!==void 0&&{content:b.content}}}function M5(w){let b=new Set(["companyId","domain","verify"]),$=Object.keys(w).filter((W)=>!b.has(W));if($.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}.`);if(w.domain===void 0&&w.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...w.domain!==void 0&&{domain:w.domain},...typeof w.verify==="boolean"&&{verify:w.verify}}}function j5(w){_w("create_transactional_email",w);let b=L(w,"prompt")!==void 0,$=w.html!==void 0,W=w.blocks!==void 0;if(w.prompt!==void 0&&!b)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(b&&($||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!b&&(w.style!==void 0||w.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!b&&!$&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!b&&L(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var U0={type:"object",description:"Update Subscriber config. firstName, lastName, and customAttributeUpdates values may use trigger-event merge tags such as {{event.plan}}. Number and boolean values must be a literal or one standalone merge tag and are coerced after resolution.",properties:{label:{type:"string"},firstName:{type:["string","null"],description:"First name literal or merge tag; null clears the field."},lastName:{type:["string","null"],description:"Last name literal or merge tag; null clears the field."},status:{type:"string",enum:["active","unsubscribed","bounced"]},customAttributeUpdates:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:["string","number","boolean","null"],description:"Literal scalar, null to delete, or a standalone merge tag such as {{event.plan}}, {{event.amount}}, or {{event.active}}."},valueType:{type:"string",enum:["text","number","boolean"]}},required:["name","value"]}}},additionalProperties:!0},eM={type:"object",description:"Config for advanced nodeType steps. Required fields depend on nodeType: action_add_tag and action_remove_tag need tagId or tagName; action_add_to_list and action_remove_from_list need listId; action_update_attributes uses the Update Subscriber fields (firstName, lastName, status, customAttributeUpdates) and may use trigger-event merge tags; logic_wait_for_event needs eventName plus optional timeoutDays and timeoutAction; logic_condition needs conditionType plus that condition's resource field; action_webhook needs an HTTPS url plus optional method, headers, body, resultKey, and onError; logic_delay uses delayDays/delayHours/delayMinutes. Fields that do not apply to the node type are dropped.",properties:{...U0.properties,tagId:{type:"string",description:"action_add_tag / action_remove_tag: tag ID. Pass a name in tagName instead, because tag actions resolve tagId by ID only. has_tag / does_not_have_tag also accept a tag name here. Missing tag definitions are created automatically."},tagName:{type:"string",description:"action_add_tag / action_remove_tag / has_tag / does_not_have_tag: tag name. Use instead of tagId when you only know the name."},listId:{type:"string",description:"action_add_to_list / action_remove_from_list / in_list: list ID. It must match an existing list in this company; listName is filled in for you."},listName:{type:"string",description:"Optional cached list display name for list actions."},eventName:{type:"string",description:"logic_wait_for_event and event_received conditions: event to wait for or check, for example email.replied."},timeoutDays:{type:"number",description:"logic_wait_for_event: maximum wait in whole days from 1 to 365. Defaults to 7."},timeoutAction:{type:"string",enum:["continue","exit"],description:"logic_wait_for_event: continue to the next node or exit the sequence when the timeout is reached. Defaults to continue."},conditionType:{type:"string",enum:["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"logic_condition: condition evaluated before continuing. has_phone and sms_subscribed need no resource fields."},segmentId:{type:"string",description:"logic_condition: segment ID for in_segment."},segmentName:{type:"string",description:"Optional cached segment display name."},linkUrl:{type:"string",description:"logic_condition: optional URL substring for link_clicked. Omit to match any tracked click."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"logic_condition: scope for event_received and link_clicked. Use this_sequence to restrict activity to the current enrollment."},fieldName:{type:"string",description:"logic_condition: subscriber attribute name/path for field comparisons."},fieldValue:{type:"string",description:"logic_condition: comparison value for field comparisons."},url:{type:"string",description:"action_webhook: destination HTTPS URL called when a subscriber reaches this step. Supports merge tags like {{email}} and {{event.order_id}} resolved at execution time."},method:{type:"string",enum:["POST","GET","PUT","PATCH","DELETE"],description:"action_webhook: HTTP method. Defaults to POST."},headers:{type:"object",description:"action_webhook: optional string-valued request headers. Values support merge tags. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},body:{type:"string",description:'action_webhook: optional JSON body template for POST/PUT/PATCH. Must be valid JSON as written, with merge tags inside quoted string values ({"email": "{{email}}"}); a tag in a bare value position is rejected. Tags are resolved at execution time; when omitted, the default payload with subscriber and sequence context is sent.'},resultKey:{type:"string",description:"action_webhook: when set, the HTTP response is saved and later email steps can reference it via {{webhooks.KEY.data.field}} merge tags. Must start with a letter; letters, numbers, underscores; max 64 chars."},onError:{type:"string",enum:["continue","exit","fail"],description:"action_webhook: behavior when the request fails. continue proceeds to the next step, exit ends the sequence for the subscriber, fail marks the enrollment failed (default)."},delayDays:{type:"number",description:"logic_delay: whole days to wait."},delayHours:{type:"number",description:"logic_delay: hours to wait."},delayMinutes:{type:"number",description:"logic_delay: minutes to wait."}},additionalProperties:!0},Zb={senderProfileId:{type:"string",description:"Sender profile for this step's From identity. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"From address for this step. Its domain must be configured and verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this step. Alone it only changes the visible name; with fromEmail it also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this step's Reply-To. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Reply-To address for this step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."}},Vb={type:"object",description:"A typed step to create inside a sequence path, including email, SMS, delay, discount, subscriber actions, conditions, waits, and webhooks.",properties:{type:{type:"string",enum:["email","sms","delay","create_discount","discount","update_subscriber","condition","webhook"],description:"Sequence path step type. Omit for email steps; use delay for fixed/date waits or update_subscriber for action_update_attributes. For an event gate, use nodeType:'logic_wait_for_event' with an explicit config object."},nodeType:{type:"string",enum:["logic_delay","action_email","action_sms","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","logic_condition","action_webhook"],description:"Advanced sequence path node type. Prefer type unless creating a non-email action. Tag, list, subscriber-update, wait, condition, and webhook node types carry their fields in config, for example nodeType:'action_add_tag' with config:{ tagName:'newsletter-confirmed' }. SMS steps still use the step-level text/imageUrls/ineligibleAction, discount steps the step-level discount fields, and delays the step-level delay/delayMs/waitUntil."},config:eM,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:z0,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},isTransactional:{type:"boolean",description:"Email only: omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses CC'd on this step."},bccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses BCC'd on this step in addition to sequence BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"Email only: URL-backed file attachments (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time."},text:{type:"string",description:"SMS only: plain-text message body."},imageUrls:{type:"array",items:{type:"string"},description:"SMS only: up to two public MMS image URLs."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS only: behavior when the contact cannot receive SMS."},delay:B0,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:D0,name:{type:"string",description:"Email template name for email steps."},senderProfileId:{type:"string",description:"Sender profile for this email step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"From address for this email step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this email step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this email step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},replyTo:{type:"string",description:"Reply-To address for this email step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},discount:{type:"object",description:`Discount configuration for create_discount steps. Same shape as create_sequence steps.${o6}`,additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use stripe to dynamically create a Stripe coupon plus promotion code, or shopify to dynamically create a Shopify Admin discount code."},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1},o9={type:"object",properties:{id:{type:"string",description:"Optional stable path ID. Defaults to branch-0, branch-1, and so on. The value 'else' is reserved."},label:{type:"string",description:"Display label, for example 'Replied in this sequence'."},conditionType:{type:"string",enum:["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"Condition for this path. has_phone and sms_subscribed need no resource fields."},tagName:{type:"string",description:"Tag name for has_tag and does_not_have_tag. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag and does_not_have_tag."},listId:{type:"string",description:"List ID for in_list."},segmentId:{type:"string",description:"Segment ID for in_segment."},segmentName:{type:"string",description:"Optional display name for in_segment."},eventName:{type:"string",description:"Event name for event_received, for example email.replied."},linkUrl:{type:"string",description:"Optional URL substring for link_clicked. Omit to match any tracked click."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"Scope for event_received and link_clicked. Use this_sequence to restrict activity to the current enrollment."},fieldName:{type:"string",description:"Subscriber attribute name/path for field conditions."},fieldValue:{type:"string",description:"Comparison value for field conditions."},targetNodeId:{type:"string",description:"Optional existing node to route this branch path to. Use a node ID from get_sequence, including the sequence completion node when this path should stop. If steps are also provided, they run before this target."},steps:{type:"array",description:"Optional new steps for this path. When targetNodeId is also set, the last new step connects to that existing node.",items:Vb}},required:["conditionType"],additionalProperties:!1};function q5(w){if(!w||typeof w!=="object")return null;let b=w;if(b.success!==!1)return null;if(typeof b.error==="string")return Error(b.error);if(b.error&&typeof b.error==="object"&&typeof b.error.message==="string")return Error(b.error.message);if(typeof b.message==="string")return Error(b.message);return Error("The tool returned an unsuccessful response.")}var P5=1000,aM=1000;function t9(w){return w.trim().toLowerCase().replace(/\s+/g,"-")}function wj(w){let b=new URLSearchParams;if(typeof w.query==="string"&&w.query.trim()!=="")b.set("query",w.query.trim());if(Array.isArray(w.tags)&&w.tags.length>0)b.set("tags",w.tags.filter(($)=>typeof $==="string"&&$.trim()!=="").join(","));if(typeof w.list==="string"&&w.list.trim()!=="")b.set("list",w.list.trim());if(typeof w.listId==="string"&&w.listId.trim()!=="")b.set("listId",w.listId.trim());if(typeof w.listName==="string"&&w.listName.trim()!=="")b.set("listName",w.listName.trim());if(typeof w.segmentId==="string"&&w.segmentId.trim()!=="")b.set("segmentId",w.segmentId);if(typeof w.status==="string"&&w.status.trim()!=="")b.set("status",w.status.trim());if(w.cursor)b.set("cursor",w.cursor);else b.set("page",String(w.page));if(b.set("limit",String(w.pageSize)),w.includeTotal===!1)b.set("includeTotal","false");return b}async function N5(w,b){let $=typeof w.limit==="number"&&Number.isFinite(w.limit)?Math.max(1,Math.trunc(w.limit)):void 0,W=Math.min(P5,Math.max(1,$??P5)),Q=[],X=1,G,J=0,Y=0,H=0;while(!0){let B=wj({query:w.query,tags:w.tags,list:w.list,listId:w.listId,listName:w.listName,segmentId:w.segmentId,status:w.status,page:X,pageSize:W,cursor:G}),A=await D("GET",`/api/v1/subscribers?${B.toString()}`,void 0,b);if(H===0)J=A.pagination?.total??A.subscribers.length,Y=A.pagination?.totalPages??1;H+=1,Q.push(...A.subscribers??[]);let F=(A.subscribers??[]).length,U=A.pagination?.nextCursor??void 0,M=$!==void 0&&Q.length>=$,q;if(U)q=!1;else if(A.pagination?.hasMore!==void 0)q=!A.pagination.hasMore;else if(A.pagination?.totalPages!==void 0&&A.pagination.totalPages!==null)q=X>=A.pagination.totalPages;else q=F<W;if(M||q||F===0||H>=aM)break;if(U)G=U;else X+=1}if(J===0&&Q.length>0)J=Q.length;let z=$!==void 0?Q.slice(0,$):Q;return{success:!0,subscribers:z,pagination:{page:1,limit:W,total:J,totalPages:Y,fetchedPages:H},returned:z.length,truncated:$!==void 0&&J>0&&z.length<J}}function r9(w){let b=typeof w.email==="string"&&w.email.trim()!==""?w.email.trim():void 0,$=typeof w.externalId==="string"&&w.externalId.trim()!==""?w.externalId.trim():void 0;return{...b?{email:b}:{},...$?{externalId:$}:{}}}function tw(w,b){let $=r9(b);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${w}\`.`);return $}function Q4(w,b){let $=new URLSearchParams;if(b?.includeMachineEngagement)$.set("includeMachineEngagement","true");let W=$.toString(),Q=W?`?${W}`:"";if(w.email)return`/api/v1/subscribers/${encodeURIComponent(w.email)}${Q}`;return $.set("externalId",String(w.externalId)),`/api/v1/subscribers/external?${$.toString()}`}function s9(w){if(w.email)return`/api/v1/subscribers/${encodeURIComponent(w.email)}/notes`;let b=new URLSearchParams;return b.set("externalId",String(w.externalId)),`/api/v1/subscribers/external/notes?${b.toString()}`}async function Mb(w,b,$){return D("GET",Q4(w,$),void 0,b)}function m(w,b,$,W){let Q=L(b,$);if(Q===void 0)return;if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${w}\`.`);return Q}function jb(w,b,$,W){let Q=V(w,b,$);if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${w}\`.`);return Q}function Yw(w,b,$,W,Q){let X=b[$];if(X===void 0)return;if(typeof X!=="number"||!Number.isInteger(X)||X<W||X>Q)throw Error(`\`${$}\` must be an integer between ${W} and ${Q} when calling \`${w}\`.`);return X}function bj(w,b){let $=[],W=m(w,b,"eventType",Kb);if(W)$.push(W);if(b.eventTypes!==void 0){if(!Array.isArray(b.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${w}\`.`);b.eventTypes.forEach((Q,X)=>{if(typeof Q!=="string")throw Error(`\`eventTypes\` item ${X+1} must be a string when calling \`${w}\`.`);let G=Q.trim();if(!Kb.includes(G))throw Error(`\`eventTypes\` item ${X+1} must be one of ${Kb.join(", ")} when calling \`${w}\`.`);$.push(G)})}return[...new Set($)]}function e9(w,b){let $=new URLSearchParams,W=bj(w,b);if(W.length>0)$.set("eventTypes",W.join(","));let Q=m(w,b,"period",["1h","24h","7d","30d","90d"]);if(Q)$.set("period",Q);let X=L(b,"start");if(X)$.set("start",X);let G=L(b,"end");if(G)$.set("end",G);let J=Yw(w,b,"page",1,1e6);if(J!==void 0)$.set("page",String(J));let Y=Yw(w,b,"limit",1,500);if(Y!==void 0)$.set("limit",String(Y));if(b.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function a9(w,b){if(b.events===void 0)return;if(!Array.isArray(b.events))throw Error(`\`events\` must be an array when calling \`${w}\`.`);let $=b.events.map((W,Q)=>{if(typeof W!=="string"||!F0.includes(W))throw Error(`\`events\` item ${Q+1} must be one of ${F0.join(", ")} when calling \`${w}\`.`);return W});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${w}\`.`);return $}function wW(w,b){if(!Array.isArray(b.emails))throw Error(`\`emails\` must be an array when calling \`${w}\`.`);let $=[];if(b.emails.forEach((W,Q)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${Q+1} must be a string when calling \`${w}\`.`);let X=W.trim();if(X.length>0)$.push(X)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${w}\`.`);if($.length>k9)throw Error(`\`emails\` must include no more than ${k9} email addresses when calling \`${w}\`. Split larger batches into multiple calls.`);return $}function I5(w,b,$,W){let Q=b[$];if(Q===void 0)return;if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array when calling \`${w}\`.`);let X=[];if(Q.forEach((G,J)=>{if(typeof G!=="string")throw Error(`\`${$}\` item ${J+1} must be a string when calling \`${w}\`.`);let Y=G.trim();if(Y.length>0)X.push(Y)}),X.length===0)throw Error(`\`${$}\` must include at least one ${W} when calling \`${w}\`.`);return X}function E5(w){let $=I5("enroll_subscribers_in_sequence",w,"emails","email address"),W=I5("enroll_subscribers_in_sequence",w,"subscriberIds","subscriber ID"),Q=($?.length??0)+(W?.length??0);if(Q===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(Q>_9)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${_9} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let X=L(w,"targetNodeId");return{...$!==void 0&&{emails:$},...W!==void 0&&{subscriberIds:W},...X!==void 0&&{targetNodeId:X}}}import{readFileSync as $j,statSync as Wj}from"node:fs";import{basename as Qj}from"node:path";var Xj={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function Gj(w){let b=w.split(".").pop()?.toLowerCase()??"";return Xj[b]??null}var Jj=104857600;async function T5(w,b){if(!Ib())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let $=Gj(w);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=Wj(w).size;if(W>Jj)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let Q=$j(w),X=await D("POST","/api/v1/products/delivery/upload-url",{filename:Qj(w),contentType:$,fileSizeBytes:W},b),G=await fetch(X.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:Q});if(!G.ok)throw Error(`File upload failed (${G.status})`);return{url:X.publicUrl,fileName:X.fileName,fileSizeBytes:W,mimeType:$}}async function X4(w){let b=L(w,"companyId");if(b)return b;let $=O1();if($)return $;try{return(await D("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function qb(w,b){let $=await X4(b);if(!$)throw Error(`A company is required when calling \`${w}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function O0(w,b){if(!C(w)||!b)return w;return{...w,url:b}}function R5(w,b){if(!C(w))return w;return{...w,...b.campaign!==void 0&&{url:b.campaign},...b.campaignPreview!==void 0&&{previewUrl:b.campaignPreview}}}function K0(w,b,$){if(!Array.isArray(w)||!b)return w;return w.map((W)=>{if(!C(W))return W;let Q=L(W,"id");if(!Q)return W;let X=B1({companyId:b,...$==="campaign"&&{campaignId:Q},...$==="landingPage"&&{landingPageId:Q},...$==="sequence"&&{sequenceId:Q},...$==="template"&&{emailId:Q},...$==="transactional"&&{transactionalId:Q},...$==="emailSend"&&{emailSendId:Q}});if($==="campaign")return R5(W,X.urls);let G=$==="sequence"?X.urls.sequence:$==="landingPage"?X.urls.landingPage:$==="template"?X.urls.email:$==="transactional"?X.urls.transactionalEmail:X.urls.emailSend;return O0(W,G)})}function Yj(w){if(!Array.isArray(w))return w;return w.map((b)=>{if(!C(b))return b;let $=L(b,"id");if(!$)return b;let W=B1({companyId:$});return{...b,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var bW=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","list_email_sends","create_campaign","update_campaign","schedule_campaign","unschedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","duplicate_landing_page","delete_landing_page","list_sequences","get_sequence","send_sequence_test_email","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","update_ab_test","list_templates","get_template","create_template","update_template","set_template_localization","sync_template_localizations","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function S5(w,b,$){if(!C($)||!bW.has(w))return $;let W=C($.company)?$.company:void 0,X=L($,"selectedCompanyId")??L($,"currentCompanyId")??L($,"companyId")??(W?L(W,"id"):void 0)??(W?L(W,"companyId"):void 0)??await X4(b);if(!X)return $;let G=C($.campaign)?$.campaign:void 0,J=C($.sequence)?$.sequence:void 0,Y=C($.landingPage)?$.landingPage:void 0,H=C($.template)?$.template:void 0,z=C($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,B={companyId:X,campaignId:L(b,"campaignId")??L($,"campaignId")??(G?L(G,"id"):void 0),landingPageId:L(b,"landingPageId")??L($,"landingPageId")??(Y?L(Y,"id"):void 0),sequenceId:L(b,"sequenceId")??L($,"sequenceId")??(J?L(J,"id"):void 0),emailId:L($,"templateId")??(H?L(H,"id"):void 0)??(z?L(z,"emailId"):void 0)??L(b,"templateId"),transactionalId:L(b,"transactionalId")??(z?L(z,"id"):void 0)??L(b,"idOrSlug"),emailSendId:L(b,"emailSendId")??L($,"emailSendId")??(C($.emailSend)?L($.emailSend,"id"):void 0),status:L(b,"status")},A=B1(B),F=W?B1({companyId:X}):void 0;return{...$,...Array.isArray($.companies)&&{companies:Yj($.companies)},...Array.isArray($.campaigns)&&{campaigns:K0($.campaigns,X,"campaign")},...Array.isArray($.landingPages)&&{landingPages:K0($.landingPages,X,"landingPage")},...Array.isArray($.sequences)&&{sequences:K0($.sequences,X,"sequence")},...Array.isArray($.templates)&&{templates:K0($.templates,X,"template")},...Array.isArray($.transactional)&&{transactional:K0($.transactional,X,"transactional")},...Array.isArray($.emailSends)&&{emailSends:K0($.emailSends,X,"emailSend")},...W&&F!==void 0&&{company:{...W,url:F.urls.dashboard,settingsUrl:F.urls.settings}},...G&&A.urls.campaign!==void 0&&{campaign:R5(G,A.urls)},...J&&A.urls.sequence!==void 0&&{sequence:O0(J,A.urls.sequence)},...Y&&A.urls.landingPage!==void 0&&{landingPage:O0(Y,A.urls.landingPage)},...H&&A.urls.email!==void 0&&{template:O0(H,A.urls.email)},...z&&A.urls.transactionalEmail!==void 0&&{transactional:O0(z,A.urls.transactionalEmail)},...C($.emailSend)&&A.urls.emailSend!==void 0&&{emailSend:O0($.emailSend,A.urls.emailSend)},appUrls:A.urls}}import{readFileSync as Hj,statSync as zj}from"node:fs";import{basename as Dj,extname as C5}from"node:path";var WW=5242880,Bj=Math.ceil(WW/3)*4,Aj=Math.ceil(Bj*1.05)+256,k5={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},Fj=new Set(Object.values(k5));function $W(w){return w?.split(";")[0]?.trim().toLowerCase()||void 0}function Lj(w){return k5[C5(w).toLowerCase()]}function Uj(w){let b=C5(w);return(b?w.slice(0,-b.length):w).replace(/[-_]+/g," ").trim()||"Image"}function Kj(w){if(w.length>Aj)throw Error("Image assets must be 5MB or smaller.")}function Oj(w){let b=0,$=0;for(let Q=0;Q<w.length;Q+=1){let X=w.charCodeAt(Q);if(X===9||X===10||X===11||X===12||X===13||X===32)continue;b+=1,$=X===61?$+1:0}if(Math.floor(b*3/4)-Math.min($,2)>WW)throw Error("Image assets must be 5MB or smaller.")}function Zj(w){Kj(w);let b=w.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(b),W=$?.[2]??b;Oj(W);let Q=W.replace(/\s+/g,"");if(Q.length===0||Q.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(Q))throw Error("`imageBase64` must contain valid base64 image bytes.");return{bytes:Buffer.from(Q,"base64"),...$?.[1]?{dataUrlContentType:$W($[1])}:{}}}function v5(w){if(w<=0)throw Error("The image file is empty.");if(w>WW)throw Error("Image assets must be 5MB or smaller.")}function Vj(w){let b=Lj(w.filename)??$W(w.explicitContentType)??$W(w.dataUrlContentType);if(!b||!Fj.has(b))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return b}function Mj(w){let b,$,W;if(w.filePath!==void 0){if(!Ib())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. For a remote MCP connection, pass `imageBase64` and `filename` instead.");let X=zj(w.filePath).size;v5(X),b=Hj(w.filePath),$=w.filename??Dj(w.filePath)}else{if(!w.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!w.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let X=Zj(w.imageBase64);b=X.bytes,W=X.dataUrlContentType,$=w.filename,v5(b.byteLength)}let Q=Vj({filename:$,explicitContentType:w.contentType,dataUrlContentType:W});return{bytes:b,filename:$,contentType:Q,altText:w.altText??Uj($)}}async function _5(w){let b=Mj(w),$=b.bytes.byteLength,W=await D("POST","/api/v1/media/upload-url",{filename:b.filename,contentType:b.contentType,fileSizeBytes:$},w.companyId);return await jW(W.uploadUrl,b.bytes,b.contentType,w.companyId),(await D("POST","/api/v1/media/complete-upload",{key:W.key,filename:W.fileName,contentType:b.contentType,fileSizeBytes:$,...w.sourceWidth!==void 0&&{width:w.sourceWidth},...w.sourceHeight!==void 0&&{height:w.sourceHeight},altText:b.altText},w.companyId)).asset}var jj={type:"boolean",description:"Whether the Sequenzy operation succeeded."},Z0={type:"string",description:"Human-readable status, confirmation, or next-step message."},h5={type:"string",description:"Additional context about the result."};function N(w){return{type:"object",description:w,additionalProperties:!0}}function U1(w){return{type:"array",description:w,items:N("One item in the returned collection.")}}function Z(w){return{type:"string",description:w}}function Pb(w){return{type:["object","null"],description:w,additionalProperties:!0}}function Pw(w){return{type:["string","null"],description:w}}function y(w){return{type:"number",description:w}}function t(w){return{type:"boolean",description:w}}function j(w){return N(`The ${w} record returned by Sequenzy.`)}function h(w){return U1(`List of ${w} records returned by Sequenzy.`)}var _1="`opened` and `clicked` are unique counts deduplicated by email send (one recipient opening five times counts once), not total open events. Every count is attributed to the sends made inside the requested window, including engagement that arrives after the window ends, so `opened <= delivered <= sent` always holds. Rates use `rateDenominator` (`delivered`, or `sent` when no delivery events were recorded, reported as `rateDenominatorBasis`); `deliveryRate` and `bounceRate` divide by `sent`.",y5="Run state: branch on effectiveStatus (draft, live, enrollment_paused, paused, or archived) rather than on status, which reads `active` even when new enrollments are paused. acceptsNewEnrollments and processesExistingEnrollments answer the two questions behind it, and effectiveStatusSummary is a plain-language sentence. The legacy triggerConfig.active flag is not read by the runtime; it is reported as a mirror of acceptsNewEnrollments.",i1=N(`The sequence record returned by Sequenzy. ${y5}`),qj=U1(`List of sequence records returned by Sequenzy. ${y5}`),G4={effectiveStatus:{type:"string",enum:["draft","live","enrollment_paused","paused","archived"],description:"Resolved run state. The one field to branch on: `status` still reads `active` while new enrollments are paused."},acceptsNewEnrollments:t("Whether new subscribers can enter the sequence right now."),processesExistingEnrollments:t("Whether subscribers already inside the sequence keep advancing and receiving steps."),effectiveStatusSummary:Z("One plain-language sentence describing the run state, safe to show a user verbatim.")},x5={...i1,properties:{migratedRecipientCount:y("Recipients moved immediately from deleted steps to their surviving successor."),completedRecipientCount:y("Recipients completed because a deleted step had no surviving successor.")}},Pj={appUrls:N("Dashboard URLs for relevant Sequenzy resources."),url:Z("Primary dashboard URL for this result."),settingsUrl:Z("Company settings URL when available.")},Ij={success:jj,message:Z0,note:h5,warnings:{type:"array",description:"Non-fatal cautions about content, permissions, or follow-up actions.",items:Z("One warning.")},items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:N("One returned item.")},value:N("Fallback object wrapper used only when a tool returns a non-object value.")},Nj={get_account:{account:j("account"),companies:h("company"),apiKeyPermissions:N("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:Z("Company ID selected by the authenticated API key, when available."),selectedCompanyId:Z("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:Z("Selected company ID."),companyName:Z("Selected company name.")},get_app_urls:{dashboard:Z("Company dashboard URL."),settings:Z("Company settings URL."),campaign:Z("Campaign editor URL."),landingPage:Z("Landing page editor URL."),sequence:Z("Sequence editor URL."),email:Z("Email editor URL."),transactionalEmail:Z("Transactional email URL."),emailSend:Z("Sent email detail URL."),domain:Z("Sending domain settings URL."),urls:N("All generated URLs keyed by resource type.")},create_company:{company:j("company"),autoSelected:t("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:j("company")},get_company:{company:j("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:N("One sync rule.")},isDefault:t("Whether the company uses the inherited SaaS/ecommerce platform preset.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:N("One sync rule.")},isDefault:t("Whether the company now uses the inherited SaaS/ecommerce platform preset.")},get_shopify_automation_settings:{browseAbandonment:N("Effective browse-abandonment settings (defaults applied)."),cartAbandonment:N("Effective cart-abandonment settings (defaults applied)."),priceDrop:N("Effective price-drop settings (defaults applied)."),shopDomain:Z("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:N("Effective browse-abandonment settings after the update."),cartAbandonment:N("Effective cart-abandonment settings after the update."),priceDrop:N("Effective price-drop settings after the update."),shopDomain:Z("Connected Shopify store domain.")},create_api_key:{apiKey:N("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:Z("Newly created API key if the API response uses the short key field.")},list_api_keys:{apiKeys:h("non-secret API key metadata, including ID, name, prefix, permissions, timestamps, and active-credential status")},update_api_key:{apiKey:j("updated non-secret API key metadata, including the `scopes` now in effect (null when the key has full access)")},revoke_api_key:{apiKey:j("revoked non-secret API key metadata")},delete_api_key:{apiKey:j("deleted non-secret API key metadata")},list_websites:{websites:h("sending domain, including DNS verification and readyToSend home-transport readiness")},list_integrations:{integrations:h("connected integration, including provider, provider account ID, active and sync status, last sync time, last sync error, allowlisted non-secret details, and lastSyncSkipped (records the last sync could not import normally: suppressed profiles that cannot receive email, plus any that were not imported). Credentials are never included")},get_integration:{integration:N("The connected integration: provider, display name, category, provider account ID, active and sync status, last sync time and error, and allowlisted non-secret details. Credentials are never included."),capabilities:Pb("What this provider does: category, connect method, what it syncs, every event it emits with when it fires, attributes it writes, supported actions, availability, and caveats. Null for a provider with no catalog entry."),events:U1("Each event the provider emits, every matching tag rule and its conditions, listening sequences, and account-wide observation fields. Use activity for integration-specific delivery."),unusedEvents:{type:"array",description:"Events the provider emits that no sequence triggers on. These are the concrete automation gaps for this integration.",items:Z("Event name with no listening sequence.")},accountNeverReceivedEvents:{type:"array",description:"Provider event names this account has never received from any source. This is not integration-specific delivery evidence.",items:Z("Event name never seen account-wide.")},activity:N("Webhook and sync activity over the last 24 hours: totals by status, stalled count, last activity time, and recent failures."),pixel:Pb("Shopify only: live storefront pixel state (installed, endpoint, endpointCurrent, configurationCurrent, healthy, error, dependentEvents). Null for providers without a pixel. When error is null and healthy is false, every dependentEvent is confirmed dark; an error means Shopify could not confirm the state."),recommendations:U1("Prioritized problems and suggestions, each with a code, severity (error, warning, info), message, and a concrete action."),availableActions:{type:"array",description:"Action ids callable on this integration right now, given its current state.",items:Z("Available action id.")}},list_integration_capabilities:{providers:h("integration provider, including category, connect method, what it syncs, every event it emits with the moment that triggers it, the subscriber attributes it writes, supported actions, availability, and caveats")},list_integration_activity:{activity:h("integration activity row, including provider, action, status, event type, matched contact, message, and error. Payloads are sanitized, so no credentials appear"),windowHours:{type:"number",description:"Retention window in hours for integration activity."},note:h5},connect_integration:{integration:{type:"object",description:"The connected integration: id, provider, name, providerAccountId, sync state, and safe (non-credential) details."},webhookUrl:Z("URL to configure in the provider's webhook settings with the same secret. Always relay this to the user - delivery does not start until it is configured."),revenueSyncQueued:t("Payment providers only: whether the initial revenue backfill was queued."),backfillQueued:t("Affonso only: whether the affiliate backfill was queued."),history:{type:"object",description:"PostHog only: outcome of the optional history import request ({ requested, queued, error }). The webhook connection succeeds even if queueing the import failed."}},set_integration_sync_enabled:{integrationId:Z("The integration that was updated."),provider:Z("Provider of the updated integration."),syncEnabled:t("Sync state after the update."),changed:t("False when the integration was already in the requested state."),message:Z0},get_integration_pixel:{integrationId:Z("The Shopify integration inspected."),provider:Z("Always `shopify`."),shopDomain:Z("Store the pixel was read from."),pixel:N("Live pixel state: installed, id, endpoint it posts to, endpointCurrent (including the supported compatibility route), configurationCurrent (endpoint plus signed connection settings), healthy, and error when Shopify could not confirm."),dependentEvents:{type:"array",description:"Event names that depend on this pixel. They are confirmed unable to arrive only when pixel.error is null and pixel.healthy is false.",items:Z("Pixel-dependent event name.")},message:Z0},activate_integration_pixel:{integrationId:Z("The Shopify integration updated."),provider:Z("Always `shopify`."),shopDomain:Z("Store the pixel was installed on."),pixel:N("Pixel state after activation."),changed:t("False when the pixel was already installed and reporting to this account."),created:t("True when a new pixel was installed."),updated:t("True when an existing pixel was repointed at this account."),dependentEvents:{type:"array",description:"Event names this pixel enables.",items:Z("Pixel-dependent event name.")},message:Z0},sync_integration:{integrationId:Z("The integration being synced."),provider:Z("Provider of the synced integration."),jobId:Pw("Background job id for the queued sync, when one was created."),syncStatus:Z("Sync status after queueing. Poll get_integration to watch it progress."),message:Z0},list_sender_profiles:{senderProfiles:h("sender (From) profile, including the sending domain behind it, its DNS verification status, and whether DNS plus the home transport allow the address to send"),replyProfiles:h("reply-to profile"),defaultSenderProfileId:Pw("Company default sender profile ID. Null when no default is set."),defaultReplyProfileId:Pw("Company default reply-to profile ID. Null when no default is set.")},update_sender_profile:{senderProfile:j("renamed sender (From) profile, present when type was sender"),replyProfile:j("renamed reply-to profile, present when type was reply"),renamed:t("False when the profile already carried that name, so nothing changed.")},get_notification_preferences:{notificationPreferences:U1("One entry per notification event with its current mode: off, instant, or daily. Every event is always present; an event the user has never configured reports the platform default."),supportedModes:N("Modes each event accepts, keyed by event. campaign_completed does not accept daily."),defaults:N("Mode each event uses when the user has never configured it.")},update_notification_preferences:{notificationPreferences:U1("Every notification event with its mode after the update, not only the events that were changed."),supportedModes:N("Modes each event accepts, keyed by event. campaign_completed does not accept daily."),defaults:N("Mode each event uses when the user has never configured it.")},get_tracking_settings:{tracking:N("Open, click, and unsubscribe tracking flags, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours."),consent:N("Signup consent settings: doubleOptInEnabled, and doubleOptInEmailId for the confirmation email sent to pending contacts (null when double opt-in has never been enabled)."),autoUtm:N("Automatic UTM tagging state and its configured parameters."),trackingDomain:Pb("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:N("Inbound reply tracking configuration.")},update_tracking_settings:{message:Z0,tracking:N("Open, click, and unsubscribe tracking flags, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours, after the update."),consent:N("Signup consent settings after the update: doubleOptInEnabled, and doubleOptInEmailId for the confirmation email, which is provisioned automatically the first time double opt-in is enabled."),autoUtm:N("Automatic UTM tagging state and its configured parameters, after the update."),trackingDomain:Pb("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:N("Inbound reply tracking configuration. Unchanged by this tool; set it with update_company.")},add_website:{website:j("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},add_sending_domain:{website:j("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},check_website:{website:j("sending domain with separate DNS verification and readyToSend home-transport readiness"),ready:t("Whether the sender website is ready."),status:Z("Current processing or verification status.")},verify_sending_domain:{website:j("Sending domain with current DNS verification, readyToSend home-transport readiness, SPF, DKIM, and MAIL FROM details."),verified:t("Whether the sending domain passed the fresh DNS verification check. This does not by itself mean SES or MTA is ready."),readyToSend:t("Whether DNS and the selected home transport are both ready for sending."),message:Z("Verification result summary.")},get_integration_guide:{guide:j("integration guide"),code:Z("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:N("One setup step.")}},add_subscriber:{subscriber:j("subscriber")},create_subscriber_import:{import:j("subscriber import")},get_subscriber_import:{import:j("subscriber import")},update_subscriber:{subscriber:j("subscriber")},remove_subscriber:{subscriber:j("subscriber"),hardDeleted:t("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:j("subscriber")},list_subscriber_notes:{notes:h("subscriber note")},add_subscriber_note:{note:j("subscriber note")},delete_subscriber_note:{id:Z("Deleted subscriber note ID."),deleted:t("Whether the subscriber note was deleted.")},trigger_subscriber_event:{subscriber:j("subscriber"),event:j("recorded event with its name and whether the event definition was created"),sideEffectFailures:{type:"array",description:"Sync-rule or automation side effects that failed. The event itself is still recorded.",items:Z("One failed side effect.")}},trigger_subscriber_events:{subscriber:j("subscriber"),events:h("recorded event")},bulk_add_subscriber_tags:{tags:{type:"array",description:"Normalized tag names applied to every matched subscriber.",items:Z("One tag name.")},requested:y("Identifiers supplied in the request."),matched:y("Existing subscribers resolved."),updated:y("Subscribers whose tags actually changed."),unchanged:y("Subscribers that already carried every tag."),failed:y("Subscribers whose update failed."),notFound:N("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds. These subscribers were NOT created."),failures:h("per-subscriber failure (up to 50)"),triggeredAutomations:t("Whether tag_added sequences were allowed to enroll these contacts.")},bulk_remove_subscriber_tags:{tags:{type:"array",description:"Normalized tag names removed from every matched subscriber.",items:Z("One tag name.")},requested:y("Identifiers supplied in the request."),matched:y("Existing subscribers resolved."),updated:y("Subscribers whose tags actually changed."),unchanged:y("Subscribers that did not carry any of the tags."),failed:y("Subscribers whose update failed."),notFound:N("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds."),failures:h("per-subscriber failure (up to 50)")},search_subscribers:{subscribers:h("subscriber"),pagination:N("Pagination metadata."),returned:y("Number of subscribers returned."),truncated:t("Whether the result was truncated by the requested limit.")},list_products:{products:h("product"),pagination:N("Pagination metadata: limit, offset, count (this page), total (whole catalog) and hasMore. Page with offset when hasMore is true.")},upsert_products:{products:h("product"),created:y("Number of products created."),updated:y("Number of products updated.")},delete_product:{productId:Z("Deleted product ID.")},attach_product_file:{product:j("product"),delivery:j("digital delivery file")},remove_product_file:{product:j("product")},upload_image_asset:{asset:j("hosted image asset"),imageBlock:N("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:j("product sync job"),jobId:Z("Queued product sync job ID.")},list_tags:{tags:h("tag")},create_tag:{tag:j("tag")},update_tag:{tag:j("tag")},delete_tag:{tagId:Z("Deleted tag ID.")},list_lists:{lists:h("list")},create_list:{list:j("list")},update_list:{list:j("list")},delete_list:{listId:Z("Deleted list ID.")},add_subscribers_to_list:{list:j("list"),added:y("Number of subscribers added to the list."),skipped:y("Number of subscribers skipped.")},remove_subscribers_from_list:{list:j("list"),removed:y("Number of subscribers removed from the list."),skipped:y("Number of subscribers skipped.")},list_segments:{segments:h("segment")},create_segment:{segment:j("segment")},update_segment:{segment:j("segment")},delete_segment:{segmentId:Z("Deleted segment ID.")},get_segment_count:{count:y("Number of subscribers matching the segment."),segmentId:Z("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:h("audience sync")},list_ad_accounts:{adAccounts:h("ad account")},create_audience_sync:{audienceSync:j("audience sync")},update_audience_sync:{audienceSync:j("audience sync")},delete_audience_sync:{audienceSyncId:Z("Deleted audience sync ID.")},sync_audience_now:{audienceSync:j("audience sync"),job:j("audience sync job"),jobId:Z("Queued audience sync job ID.")},list_templates:{templates:h("email template")},get_template:{template:j("email template")},create_template:{template:j("email template")},update_template:{template:j("email template")},set_template_localization:{templateId:Z("Localized template ID."),localization:j("template localization")},sync_template_localizations:{templateId:Z("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:Z("One queued locale code.")},queuedVariantCount:y("Number of localized variants queued for translation.")},delete_template:{templateId:Z("Deleted template ID.")},list_ab_tests:{abTests:h("A/B test")},get_ab_test:{abTest:j("A/B test")},get_ab_test_stats:{abTest:j("A/B test"),stats:j("A/B test statistics")},restart_ab_test:{abTest:j("A/B test")},update_ab_test_variant:{abTest:j("A/B test"),variant:j("A/B test variant")},update_ab_test:{abTest:j("A/B test")},create_ab_test:{abTest:j("A/B test")},add_ab_test_variant:{abTest:j("A/B test"),variant:j("A/B test variant")},delete_ab_test_variant:{abTest:j("A/B test"),variantId:Z("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:Z("Deleted A/B test ID.")},list_campaigns:{campaigns:h("campaign"),pagination:N("Campaign page window: `limit`, `offset`, `count` returned in this page, `total` matching the filters, and `hasMore`. Keep calling with an advanced `offset` while `hasMore` is true to enumerate every campaign.")},get_campaign:{campaign:j("campaign")},get_campaign_audience:{campaignId:Z("Campaign the audience was resolved for."),campaignName:Z("Campaign name."),status:Z("Campaign status."),audience:N("Resolved targeting: `type`, a plain-language `summary`, `isUnset` (true when scheduling would fall back to every active subscriber), resolved `lists` and `segments` with names and a `missing` flag, `filters`, `include`/`exclude` rules, and individual subscriber adjustments."),recipientCount:y("Number of subscribers matching the effective targeting right now."),targetLists:Pb("Raw stored targeting exactly as persisted on the campaign. Null when targeting has never been set.")},get_email_send:{emailSend:j("email send, including copied-recipient identity and primary email send ID when applicable"),events:h("email delivery event")},list_email_sends:{emailSends:h("email send"),pagination:j("email send pagination"),retentionDays:y("Number of days sent-email rows remain queryable in this collection.")},get_recipient_suppression:{suppression:j("recipient suppression status")},remove_recipient_suppression:{removed:t("Whether stale bounce suppression was removed."),removedLocalBounce:t("Whether the platform-local bounce block was removed."),removedSesRegions:{type:"array",description:"AWS SES regions where a bounce suppression was removed.",items:Z("One AWS SES region.")},remainingSuppression:j("recipient suppression status after cleanup")},create_campaign:{campaign:j("campaign")},update_campaign:{campaign:j("campaign")},schedule_campaign:{campaign:j("campaign"),scheduledAt:Z("Scheduled send timestamp.")},unschedule_campaign:{campaign:j("draft campaign")},send_test_email:{emailSendId:Z("Durable test email delivery ID."),recipientEmail:Z("Test email recipient.")},send_test_sms:{smsSendId:Z("Created test SMS send ID."),toPhone:Z("Normalized E.164 destination phone.")},cancel_campaign:{campaign:j("campaign")},pause_campaign:{campaign:j("campaign")},resume_campaign:{campaign:j("campaign")},delete_campaign:{campaignId:Z("Deleted campaign ID.")},duplicate_campaign:{campaign:j("duplicated campaign")},resend_campaign_to_non_openers:{campaign:j("non-opener resend draft campaign"),estimatedNonOpenerCount:y("Estimated number of subscribers who haven't opened the original campaign.")},list_forms:{forms:h("saved form")},create_form:{form:j("saved form"),embed:N("Public action URL plus JavaScript, native form, and fetch snippets.")},update_form:{form:j("saved form"),embed:N("Public action URL plus JavaScript, native form, and fetch snippets (published forms only).")},get_form_embed:{form:j("saved form"),embed:N("Public action URL plus JavaScript, native form, and fetch snippets.")},list_landing_pages:{landingPages:h("landing page")},get_landing_page:{landingPage:j("landing page")},create_landing_page:{landingPage:j("landing page")},update_landing_page:{landingPage:j("landing page")},duplicate_landing_page:{landingPage:j("landing page")},delete_landing_page:{landingPageId:Z("Deleted landing page ID.")},publish_landing_page:{landingPage:j("landing page")},unpublish_landing_page:{landingPage:j("landing page")},connect_landing_page_domain:{landingPage:j("landing page"),domain:Z("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:j("landing page"),domain:Z("Landing page domain.")},list_sequences:{sequences:qj,pagination:N("Sequence page window: `limit` (null when limit and offset were both omitted and every sequence was returned), `offset`, `count` returned in this page, `total` matching the filters, and `hasMore`.")},get_sequence:{sequence:i1},list_sequence_enrollments:{sequenceId:Z("Sequence ID these enrollments belong to."),sequenceName:Z("Sequence name."),statuses:{type:"array",description:"Enrollment statuses included in this response. Defaults to active and waiting.",items:{type:"string",description:"Enrollment status."}},enrollments:{type:"array",description:"Contact-level enrollments matching the filters, one row per enrollment token.",items:{type:"object",description:"One subscriber's enrollment in this sequence.",properties:{enrollmentId:Z("Enrollment token ID. Stable identifier for this one run through the sequence."),sequenceId:Z("Sequence ID."),subscriberId:Z("Subscriber ID."),email:Pw("Subscriber email address. Falls back to the address captured at enrollment when the subscriber record no longer exists, and is null when neither is known."),firstName:Pw("Subscriber first name, or null when unset."),lastName:Pw("Subscriber last name, or null when unset."),subscriberStatus:Pw("Subscriber status (active, unsubscribed, bounced), or null when the subscriber record no longer exists."),status:Z("Enrollment status: active, waiting, completed, failed, or cancelled."),currentNodeId:Z("Sequence node this enrollment is currently sitting on."),currentNodeType:Z("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:Z("Current sequence node label or email subject when available."),currentNodeMissing:t("Whether the current node no longer exists in the sequence graph."),enrollmentKey:Z("Key that distinguishes concurrent enrollments of the same subscriber in this sequence."),enrollmentStartedAt:Z("ISO 8601 timestamp when this enrollment entered the sequence."),waitUntil:Pw("ISO 8601 timestamp this enrollment is scheduled to resume, or null when nothing is scheduled."),lastUpdatedAt:Z("ISO 8601 timestamp of the last change to this enrollment. For a waiting enrollment this is when it arrived at its current node; the platform does not separately track node entry time."),failedReason:Pw("Why this enrollment stopped, for status `failed`. Null for every other status and for failures recorded before this field existed. A reason repeated across enrollments on the same currentNodeId points at that step's configuration or content rather than at the contacts.")},required:["enrollmentId","sequenceId","subscriberId","status","currentNodeId","currentNodeMissing","enrollmentStartedAt"]}},pagination:N("Pagination metadata.")},send_sequence_test_email:{sequenceId:Z("Sequence ID."),nodeId:Z("Tested sequence email-step node ID."),results:U1("Per-recipient test-send results containing recipientEmail, durable emailSendId, and legacy jobId.")},create_sequence:{sequence:i1,eventTrackingCode:Z("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:N("Custom-event endpoint, payload contract, example payload, documentation URL, and get_integration_guide arguments."),requiredEvents:{type:"array",description:"Event names the application or an integration must send.",items:Z("One required event name.")}},update_sequence:{sequence:x5},update_sequence_node:{sequence:j("sequence")},update_sequence_nodes:{sequence:j("sequence")},edit_sequence_graph:{sequence:x5},insert_sequence_step:{sequence:j("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for a linear inserted step, including any delay or wait-for-event node.",items:Z("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:Z("Inserted email template ID.")},insertedEmailCount:y("Number of email steps inserted."),addedBranchNodeId:Z("New logic_branch node ID when the inserted step is a branch."),addedBranchPathNodeIds:N("Created path node IDs keyed by branch ID, plus else. Directly wired paths have empty arrays.")},enable_sequence:{sequenceId:Z("Sequence ID."),status:Z("Stored lifecycle status after the change."),enrollmentPaused:t("Whether new sequence enrollments are paused."),...G4},disable_sequence:{sequenceId:Z("Sequence ID."),status:Z("Stored lifecycle status after the change."),enrollmentPaused:t("Whether new sequence enrollments are paused."),...G4},duplicate_sequence:{sequence:i1,nodes:h("sequence node"),edges:h("sequence edge")},archive_sequence:{sequence:i1},unarchive_sequence:{sequence:i1},list_sequence_goals:{goals:h("sequence goal")},create_sequence_goal:{goal:j("sequence goal")},update_sequence_goal:{goal:j("sequence goal")},delete_sequence_goal:{goalId:Z("Deleted sequence goal ID.")},get_sequence_inbound_webhook:{webhook:j("sequence inbound webhook")},configure_sequence_inbound_webhook:{webhook:j("sequence inbound webhook")},rotate_sequence_inbound_webhook_secret:{webhook:j("sequence inbound webhook")},pause_sequence_enrollments:{sequenceId:Z("Sequence ID."),enrollmentPaused:t("Whether new sequence enrollments are paused."),...G4},resume_sequence_enrollments:{sequenceId:Z("Sequence ID."),enrollmentPaused:t("Whether new sequence enrollments are paused."),...G4},enroll_subscribers_in_sequence:{sequence:j("sequence"),enrollments:h("sequence enrollment"),enrolled:y("Number of subscribers enrolled."),skipped:y("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequenceId:Z("Sequence ID."),dryRun:t("Whether this call only reported matches instead of cancelling them."),target:N("Resolved cancellation target: mode all, subscriber, subscribers (with notFoundSubscriberIds), or field."),matchedCount:y("Active/waiting enrollments matching the target when the request started."),cancelledCount:y("Enrollments cancelled by this call."),remainingCount:y("Enrollments still matching after this call. Repeat the same request while this is above zero."),enrollments:h("sequence enrollment sample (up to 50)"),hasMore:t("Whether more enrollments matched than the returned sample.")},delete_sequence:{sequenceId:Z("Deleted sequence ID.")},list_transactional_emails:{transactional:h("transactional email with subject, all-time delivery metrics, and dashboard URL")},get_transactional_email:{transactional:j("transactional email")},create_transactional_email:{transactional:j("transactional email")},update_transactional_email:{transactional:j("transactional email")},delete_transactional_email:{deleted:N("Deleted transactional email: id, slug, name, and emailId of the email content that was kept as a reusable template.")},send_email:{emailSendId:Z("Durable email delivery ID."),emailType:{type:"string",enum:["marketing","transactional"],description:"Delivery policy accepted for the queued email."},transactional:j("transactional email")},get_stats:{stats:N(`Account-wide delivery funnel for the requested window. ${_1}`),emailType:Z("Applied structural email type filter when one was requested."),commerceForecast:j("Optional background-computed commerce AOV, 12-month customer value, and 90-day revenue forecast. Omitted when no snapshot is available; insufficient_data is returned only after eligibility was evaluated successfully.")},get_campaign_stats:{campaign:j("campaign"),stats:N(`Delivery funnel for this campaign. ${_1}`),clickedLinks:{type:"array",description:"Per-link click breakdown, most clicked first (top 20). Each entry has url, clicks, and percentage (that link's share of every recorded link click). Present only when the campaign has tracked link clicks.",items:N("One clicked link with url/clicks/share.")},polls:{type:"array",description:`Poll and NPS summaries. Each subscriber counts once per campaign poll block using their latest answer to that block; NPS entries include score, average, and promoter/passive/detractor counts. To list the exact historical respondents behind a count, use the summary blockId and the get_campaign_stats campaignId with create_segment. ${k1} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response and may be overwritten by a later poll that reuses the key.`,items:N("One poll or NPS results summary.")},recommendations:N("Product recommendation funnel: impressions, recipients, clicks, clickers, orders, legacy revenueCents, currency-safe revenueByCurrency totals, and topProducts (per-product impressions/clicks). Orders count when a subscriber buys a recommended product within 7 days of clicking it. Present only when the campaign rendered product recommendation blocks.")},get_transactional_stats:{transactional:j("transactional email"),stats:N(`Delivery funnel for this transactional email. ${_1}`),complaints:j("complaint count and rate for the selected transactional email"),clickedLinks:h("clicked link with click count and percentage share"),bounceBreakdown:j("permanent, transient, and undetermined bounce counts plus subtype details"),engagementBreakdown:j("human and machine open and click counts")},get_sequence_stats:{sequence:i1,stats:N(`Delivery funnel across every email step in this sequence. ${_1}`),steps:{type:"array",description:`Per-step delivery funnel: one entry per email step of the sequence, in graph order, each with its own sent/delivered/opened/clicked counts. Read this to answer "how many of step N went out" - do not recount list_sequence_events. Counts come from the retained event stream, so they are not limited to the 14-day list_email_sends history. ${_1}`,items:{type:"object",description:"Metrics for one email step of the sequence.",properties:{step:y("1-based position of this email step in graph order. Step 4 is the fourth email a contact receives on the traversed path; on a branching graph, positions are assigned by traversal, so cross-check nodeId when a sequence forks."),nodeId:Z("Automation node ID of this email step. Pass it to list_sequence_events or list_email_sends as automationNodeId to reach the individual recipients behind these counts, and it is the emailId that list_email_metrics reports for sequence emails."),subject:Pw("Subject line of the step's email, falling back to the node label, or null when neither is set."),stats:N(`Delivery funnel for this step alone: sent, delivered, bounced, opened, clicked, replies, unsubscribed, and their rates. ${_1}`),failedCount:y("Contacts currently stuck on this step with a failed enrollment."),failedSubscribers:U1("Up to 20 of the failed contacts on this step, as { subscriberId, email, failedAt, failedReason }.")},required:["step","nodeId","stats"],additionalProperties:!0}},enrollmentCounts:{type:"object",description:"Live enrollment-token counts for this sequence. Includes only active and waiting enrollments and is always a current snapshot, independent of historical period/start/end filters.",properties:{active:y("Active enrollment count."),waiting:y("Waiting enrollment count."),total:y("Total active plus waiting enrollment count."),byCurrentNode:{type:"array",description:"Live active and waiting enrollment counts grouped by the token's current sequence node.",items:{type:"object",description:"Enrollment counts for one current sequence node.",properties:{currentNodeId:Z("Current sequence node ID."),currentNodeType:Z("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:Z("Current sequence node label or email subject when available."),currentNodeMissing:t("Whether the current node no longer exists in the sequence graph."),active:y("Active enrollment count at this node."),waiting:y("Waiting enrollment count at this node."),total:y("Total active plus waiting enrollment count at this node.")},required:["currentNodeId","currentNodeMissing","active","waiting","total"],additionalProperties:!1}}},required:["active","waiting","total","byCurrentNode"],additionalProperties:!1},enrollmentSkipped:{type:"object",description:"Trigger matches where an unsubscribed or bounced contact could not be enrolled, including the total count and counts grouped by reason. Uses the requested period or start/end range; without an explicit range, this field defaults to the last 30 days.",properties:{count:y("Total skipped sequence enrollments."),byReason:{type:"object",description:"Skipped enrollment counts keyed by reason, such as unsubscribed or bounced.",additionalProperties:y("Skipped enrollment count for this reason.")}},required:["count","byReason"],additionalProperties:!1},recommendations:N("Product recommendation funnel aggregated across the sequence's email nodes: impressions, recipients, clicks, clickers, orders, legacy revenueCents, currency-safe revenueByCurrency totals, and topProducts. Present only when the sequence rendered product recommendation blocks.")},list_campaign_events:{events:h("campaign email event"),pagination:N("Pagination metadata.")},list_sequence_events:{events:h("sequence email event"),pagination:N("Pagination metadata.")},list_email_metrics:{emails:{type:"array",description:"One entry per email in scope: each campaign and each sequence email step, sorted by the requested sort/order.",items:{type:"object",description:"Metrics for one campaign or one sequence email step.",properties:{emailType:{type:"string",enum:["campaign","sequence"],description:"Whether this row is a campaign or a sequence email."},emailId:Z("Stable identifier: the campaign ID for campaigns, the automation node ID for sequence emails."),name:Z("Campaign name, or the sequence step's subject line falling back to its node label."),campaignId:Pw("Campaign ID, or null for sequence emails."),sequenceId:Pw("Sequence ID, or null for campaigns."),sequenceName:Pw("Name of the sequence this step belongs to, or null for campaigns."),automationNodeId:Pw("Automation node ID of this step, or null for campaigns. Pass it as automationNodeId to list_sequence_events or list_email_sends to reach the recipients behind these counts."),step:{type:["number","null"],description:"1-based position of this email in its sequence, counted in graph order, or null for campaigns. Matches the step number in get_sequence_stats steps[]."},stats:N(`Delivery funnel for this email alone. ${_1}`),conversions:y("Attributed conversions credited to this email."),revenueCents:y("Attributed revenue in minor currency units credited to this email.")},required:["emailType","emailId","name","stats"],additionalProperties:!0}},totals:N(`Summed funnel across every email matching the filters, not just the returned page, plus \`emails\` (the number of matching emails), \`conversions\`, and \`revenueCents\`. Read totals.sent for "how many of this step went out in total". ${_1}`),pagination:N("Pagination metadata."),sort:Z("Sort field the response was ordered by."),order:Z("Sort order the response was ordered by."),step:y("Echo of the step filter, present only when one was requested."),sequenceIds:{type:"array",description:"Echo of the sequence IDs the breakdown was scoped to, present only when scoped.",items:Z("Sequence ID.")}},get_subscriber_activity:{activity:h("subscriber activity event"),subscribers:h("subscriber"),pagination:N("Pagination metadata.")},list_team_members:{members:h("team member"),invitations:h("team invitation")},invite_team_member:{invitation:j("team invitation")},cancel_team_invitation:{invitationId:Z("Cancelled invitation ID.")},list_conversations:{conversations:h("inbox conversation"),pagination:N("Pagination metadata.")},get_conversation:{conversation:j("inbox conversation"),messages:h("conversation message")},reply_to_conversation:{conversation:j("inbox conversation"),message:j("conversation message")},update_conversation_status:{conversation:j("inbox conversation")},mark_conversation_read:{conversation:j("inbox conversation")},list_webhooks:{webhooks:h("outbound webhook")},create_webhook:{webhook:j("outbound webhook")},update_webhook:{webhook:j("outbound webhook")},delete_webhook:{webhookId:Z("Deleted outbound webhook ID.")},test_webhook:{webhook:j("outbound webhook"),delivery:j("test webhook delivery")},list_webhook_deliveries:{deliveries:h("webhook delivery")},replay_webhook_delivery:{delivery:j("webhook delivery"),job:j("webhook replay job")},generate_email:{email:j("generated email"),html:Z("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:N("One generated email block.")},subject:Z("Generated subject line."),previewText:Z("Generated inbox preview text.")},generate_sequence:{sequence:j("persisted AI-generated sequence draft"),deprecated:t("Always true for this deprecated alias."),deprecationMessage:Z("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:Z("One generated subject line.")},variants:h("generated subject line variant")},generate_sms:{prompt:Z("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:N("One generated SMS message.")}},get_sms_settings:{sms:N("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{},render_email:{html:Z("Email-safe HTML document, rendered exactly as it would be sent."),subject:Z("Subject line with merge tags resolved."),previewText:Pw("Inbox preview text with merge tags resolved, or null when unset."),locale:Z("Localization locale the render resolved to."),personalized:t("Whether a real contact was supplied. False means a sample contact was used, so contact-specific merge tags resolve to empty values."),trackingApplied:t("Whether auto-UTM link decoration was applied."),unresolvedMergeTags:U1(`Merge tags that rendered as an empty string, as [{ tag, reason }]. reason "unknown" means nothing provides that name, so it stays empty for every recipient - usually a typo or a tag copied from another platform. reason "no_value" means the name is recognized, or could not be checked, but is blank for this contact. A name is only called unknown when the render had a source to check it against. Without the contact's attributes nothing is checkable, since a bare {{plan}} reads the same attribute map as {{subscriber.plan}}, so pass a stored subscriberId or an inline subscriber carrying customAttributes. Beyond that, {{event.*}} needs sample event properties in variables, since a real send fills those from the enrolling event; {{recommendedProducts.*}} needs a stored subscriberId the catalog has something to recommend for; and {{discount.*}} is only checkable on a sequence step whose incoming paths all run the same discount step, never on a standalone template. Rendering a transactional email is checkable only when variables is passed, because its tags come from the variables of each send call and carry no prefix marking them. Otherwise those tags land in no_value rather than in unknown. An optional attribute this contact never had set is kept out of unknown by checking the names other contacts in the account carry, which needs the subscribers:read scope; a key without it may report such a name as unknown. An empty array means every tag in the email resolved.`),entity:N("Which entity was rendered: type, id, and variantId.")}};function Ej(w){let b=Nj[w];if(b===void 0)throw Error(`MCP tool "${w}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${w}\` MCP tool.`,properties:{...Ij,...b,...bW.has(w)?Pj:{}},additionalProperties:!0}}function f5(w){return{...w,outputSchema:Ej(w.name)}}function u5(w){if(C(w))return w;if(Array.isArray(w))return{items:w};return{value:w}}var c5=[{name:"list_ab_tests",description:"List A/B tests and their variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Optional sequence ID to filter automation A/B tests."}}}},{name:"get_ab_test",description:"Get A/B test details, variants, and per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"}},required:["abTestId"]}},{name:"get_ab_test_stats",description:"Get A/B test aggregate stats and per-variant stats. Supports period or custom start/end ranges.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},period:{type:"string",description:"Optional period: 1h, 24h, 7d, 30d, or 90d."},start:{type:"string",description:"Custom range start as ISO 8601. Requires end."},end:{type:"string",description:"Custom range end as ISO 8601. Requires start."},includeMachineEngagement:kw},required:["abTestId"]}},{name:"restart_ab_test",description:"Run another sequence A/B test after a winner is selected. By default the winner becomes the new control; pass sourceVariantId to use another variant as the control email.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to restart"},sourceVariantId:{type:"string",description:"Optional variant ID to use as the new control email. Defaults to the selected winner."},testType:{type:"string",description:"Optional test type: subject or content."},winnerThreshold:{type:"number",description:"Optional number of subscribers before selecting a winner. Must be from 10 to 1000."},variantCount:{type:"number",description:"Optional total variants including the control. Must be from 2 to 4."}},required:["abTestId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update an A/B test variant. Campaign variants are editable only in draft. Sequence variants can be edited after activity with confirmLiveChange, but earlier sends stay unchanged and combined results may no longer be accurate. Provide at least one of subject, previewText, html, or blocks. Use either html or blocks, not both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID"},subject:{type:"string",description:"Variant subject line"},previewText:{type:"string",description:"Variant preview text. Pass an empty string to clear it."},html:{type:"string",description:`Replacement HTML body. Mutually exclusive with blocks. ${Hw}`},blocks:{type:"array",description:`${F1}${g1} Mutually exclusive with html.`,items:{type:"object"}},confirmLiveChange:{type:"boolean",description:"Required as true when the sequence is active, the test is no longer a draft, or it has recorded activity. The edit affects future sends and can make combined results inaccurate."}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"update_ab_test",description:"Update A/B test settings. Campaign tests use testPercentage, testDurationMinutes, and winnerCriteria. Sequence tests use testType, winnerThreshold, and winnerCriteria; changing live or already-used sequence settings requires confirmLiveChange. Provide at least one setting.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Campaign-only percentage of the audience used for the test phase, from 5 to 50."},testDurationMinutes:{type:"number",description:"Campaign-only test duration in minutes, from 15 to 1440."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Applies to both campaign and sequence tests."},testType:{type:"string",enum:["subject","content"],description:"Sequence-only variant strategy. When winnerCriteria is omitted, subject defaults to open_rate and content defaults to click_rate."},winnerThreshold:{type:"number",description:"Sequence-only number of recipients before selecting a winner, from 10 to 1000."},confirmLiveChange:{type:"boolean",description:"Required as true when sequence settings affect an active test or a test with recorded activity."}},required:["abTestId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test or convert a sequence email node into a typed A/B test node. Provide exactly one of campaignId or automationNodeId. Control variant A is created automatically from the current email. Campaign tests may add variants later; automationNodeId conversions require at least one variants[] entry to compete with control variant A.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Draft campaign ID. Mutually exclusive with automationNodeId."},automationNodeId:{type:"string",description:"Sequence email-node ID to convert to action_ab_test. Mutually exclusive with campaignId."},confirmLiveChange:{type:"boolean",description:"Required as true when converting an email node in an active sequence."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Campaign-only percentage of the audience used for the test phase, from 5 to 50. Defaults to 20. Sequence tests use winnerThreshold instead."},testDurationMinutes:{type:"number",description:"Campaign-only test phase duration in minutes, from 15 to 1440. Defaults to 240. Sequence tests select after winnerThreshold recipients instead."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Campaign tests default to open_rate. For sequence tests, an explicit value overrides the testType default."},testType:{type:"string",enum:["subject","content"],description:"Sequence A/B test variant strategy. Subject defaults to open_rate and content defaults to click_rate unless winnerCriteria is explicit. Defaults to content."},winnerThreshold:{type:"number",description:"Sequence test sample size from 10 to 1000. Defaults to 100."},variants:{type:"array",maxItems:4,description:"Extra variants to create in addition to control variant A. Optional for campaign tests; automationNodeId conversions require at least one entry.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:`${F1}${g1}`,items:{type:"object"}}},required:["subject"]}}}}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign or sequence A/B test. Sequence variants receive their own editable email template. Variants cannot be added after the test has started. Sequence tests whose parent sequence is active require confirmLiveChange.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:`${F1}${g1}`,items:{type:"object"}},confirmLiveChange:{type:"boolean",description:"Required as true when the A/B test belongs to an active sequence, because new variants immediately enter the live rotation."}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign or sequence A/B test. This cannot be undone. Variant A is the control and cannot be deleted, and the test must keep at least the minimum number of variants. Variants cannot be removed after the test has started. Sequence tests whose parent sequence is active require confirmLiveChange.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID to delete."},confirmLiveChange:{type:"boolean",description:"Required as true when the A/B test belongs to an active sequence, because deletion immediately changes the live rotation."}},required:["abTestId","variantId"]}},{name:"delete_ab_test",description:"Permanently delete a campaign A/B test and all of its variants. This cannot be undone. Running tests (testing or winner_selected) cannot be deleted, and the linked campaign must be in draft or rejected status.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to delete."}},required:["abTestId"]}}];var m5=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. IMPORTANT: If you have access to multiple companies, you MUST either:
30
30
  1. Call select_company first to choose which company to work with, OR
31
31
  2. Pass companyId explicitly in each tool call
32
32
 
@@ -48,7 +48,7 @@ Use cases:
48
48
  - 'event_tracking': Tracking CUSTOM events only (not payment events - those come from the integration)
49
49
  - 'ecommerce': Connecting a custom e-commerce platform via the Commerce API (sync products, push orders/checkouts, power abandoned cart + back-in-stock automations)
50
50
 
51
- Before protected server-side API work, use create_api_key and save the key to .env as SEQUENZY_API_KEY. Static-site saved forms are the exception: use list_forms/create_form/get_form_embed and never place a secret key in browser code.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration), 'ecommerce' (connecting a custom e-commerce platform via the Commerce API)"}}}}];var m5=[{name:"generate_email",description:"Generate email blocks from a prompt. Generated blocks include the company's branding chrome (logo, footer with company name/address/unsubscribe) by default, matching emails created in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"},applyBranding:{type:"boolean",description:"Wrap the generated content with company branding (logo + footer). Defaults to true; set false to get raw content blocks only."},emailType:{type:"string",enum:["marketing","transactional"],description:"Email type. Transactional emails get a footer without the unsubscribe link. Defaults to marketing."}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED compatibility alias - use create_sequence] Create and persist a disabled AI-generated email sequence draft from a goal. The saved draft appears in list_sequences. The name defaults to the goal and the trigger defaults to contact_added; optionally pass listId to scope it. Review before enabling.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},name:{type:"string",description:"Optional sequence name. Defaults to the goal."},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"},listId:{type:"string",description:"Optional list ID. When provided, only contacts added to this list trigger the sequence."}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}},{name:"generate_sms",description:"Generate SMS marketing message variants from a prompt. Returns plain-text messages with per-message encoding and segment counts. Use the results as the 'text' of an SMS sequence step (insert_sequence_step with type 'sms' or a create_sequence sms step). Messages exclude opt-out footers and brand prefixes - the platform adds those automatically at send time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the SMS to generate (e.g., 'cart reminder with a free-shipping hook')"},count:{type:"number",description:"Number of message variants to generate (default: 3, max: 10)"}},required:["prompt"]}},{name:"get_sms_settings",description:"Get the company's SMS add-on status: whether SMS is enabled, plan eligibility, credit balance, brand prefix, phone numbers, and whether SMS steps will actually send. Check this before adding SMS steps to sequences so you can warn the user when SMS is not ready.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"send_test_sms",description:"Send a test SMS to a phone number. IMPORTANT: sends a real text message and charges SMS credits - only call when the user explicitly asks for a test send. Requires the SMS add-on with a verified number (check get_sms_settings). Limited to 5 test sends per hour; bypasses quiet hours; excluded from step stats.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Destination phone number in international E.164 format, e.g. +15550100123."},text:{type:"string",description:"Plain-text message body. Merge tags are not resolved for test sends to arbitrary numbers. Provide text or blocks."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable image URLs sent as MMS media (US/CA only)."},blocks:{type:"array",items:{type:"object"},description:"SMS content blocks (text + image subset). Provide text or blocks, not both."}},required:["to"]}}];var l5=[{name:"get_stats",description:"Get overview statistics for a time period, including reply count and reply rate. Counts form a funnel over the sends made inside the period: opened and clicked are unique per email send (not total open events) and include engagement that arrives after the period ends, so they never exceed sent. Rates divide by rateDenominator (delivered, falling back to sent), reported alongside rateDenominatorBasis. Set emailType to transactional for Send API and transactional SMTP open/click rates, including both direct and saved-template sends. When no emailType filter is used and a background-computed snapshot is available, the response also includes a top-level commerceForecast with predicted AOV, 12-month customer value, 90-day revenue, confidence, and data-eligibility reasons.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},period:{type:"string",description:"Time period: 7d, 30d, or 90d (default: 7d)"},emailType:{type:"string",description:"Optional structural email type filter: campaign, transactional, or sequence. Use transactional for Send API and transactional SMTP traffic."},includeMachineEngagement:uw}}},{name:"get_transactional_stats",description:"Get aggregate sends, deliveries, bounces, opens, clicks, and rates for one saved transactional email selected by ID or slug. Results are all-time by default; pass period or start/end for a window. For direct-content Send API messages, use get_stats with emailType transactional and list_email_sends/get_email_send for delivery-level detail.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Saved transactional email ID or API slug."},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days."},includeMachineEngagement:uw},required:["idOrSlug"]}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including replies and reply rate, attributed conversions, revenue (revenueCents), product recommendation funnel metrics, a per-link click breakdown in the top-level clickedLinks array, and any Poll or NPS survey summaries in the top-level polls array",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},period:{type:"string",description:"Time period: 1h, 24h, 7d, 30d, or 90d"},start:{type:"string",description:"Custom range start as an ISO 8601 timestamp; provide end too"},end:{type:"string",description:"Custom range end as an ISO 8601 timestamp; provide start too"},includeMachineEngagement:uw},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence, including aggregate and per-step replies and reply rates, attributed conversions and revenue (revenueCents), product recommendation funnel metrics, per-step failed subscribers and failure reasons, plus enrollmentSkipped counts for trigger matches where the contact could not be enrolled (unsubscribed/bounced). Pass period or start/end to use one explicit window for every historical metric; without them, enrollmentSkipped defaults to the last 30 days. The enrollmentCounts field is a live snapshot of active and waiting enrollments grouped by current node, so it is not limited by period or start/end.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days."},includeMachineEngagement:uw},required:["sequenceId"]}},{name:"list_campaign_events",description:"List paginated raw email events for a campaign. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},eventType:{type:"string",description:`Optional single event type. Supported values: ${Kb}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${Kb}. Defaults to delivery.`,items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:uw},required:["campaignId"]}},{name:"list_sequence_events",description:"List paginated raw email events for every email step in a sequence. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},eventType:{type:"string",description:`Optional single event type. Supported values: ${Kb}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${Kb}. Defaults to delivery.`,items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:uw},required:["sequenceId"]}},{name:"get_subscriber_activity",description:"Get recent activity, email stats, and current sequence enrollments for a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:uw},required:[]}}];var g5=[{name:"list_audience_syncs",description:"List Meta custom audience syncs (segment -> ad audience mappings) with their schedule and last sync status. Requires the Meta Ads integration to be connected in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_ad_accounts",description:"List the Meta ad accounts available through the connected Meta Ads integration. Use the returned account id as `adAccountId` when creating an audience sync.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_audience_sync",description:'Push a segment to a Meta custom audience and keep it synced on a schedule. Provide `segmentId` for an existing segment OR `predefinedSegmentId` for a ready-made template (for example "zero-ltv", "no-purchase-1y", "recent-buyers", "high-spenders-ecom", "non-buyers", "engaged") - the template segment is created automatically on first use. The first upload runs immediately. Note: audiences are add-only; subscribers who later leave the segment stay in the Meta audience.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Existing segment ID to sync. Mutually exclusive with `predefinedSegmentId`."},predefinedSegmentId:{type:"string",description:'Predefined segment template ID (for example "zero-ltv", "no-purchase-1y", "recent-buyers"). The segment is created automatically if it does not exist. Mutually exclusive with `segmentId`.'},adAccountId:{type:"string",description:"Meta ad account ID (act_...) from `list_ad_accounts`."},audienceName:{type:"string",description:"Name for the custom audience in Meta Ads Manager."},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"How often to re-upload the segment. Default: daily."}},required:["adAccountId","audienceName"]}},{name:"update_audience_sync",description:"Update an audience sync's frequency or pause/resume it (`isActive`).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID"},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"New sync frequency."},isActive:{type:"boolean",description:"Set false to pause the sync, true to resume it."}},required:["syncId"]}},{name:"delete_audience_sync",description:"Remove an audience sync mapping. The Meta audience itself is kept (running ads are not disrupted) - only future syncs stop.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to remove."}},required:["syncId"]}},{name:"sync_audience_now",description:"Trigger an immediate upload of the segment's subscribers to its Meta custom audience, outside the regular schedule.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to run."}},required:["syncId"]}}];var i5=[{name:"list_campaigns",description:"List campaigns. Results are paginated: the default page size is 50 and limit is capped at 100. Always read the returned `pagination` object (`limit`, `offset`, `count`, `total`, `hasMore`) and keep paging with `offset` while `hasMore` is true - a single call does not necessarily return every campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent, sending, cancelled, paused, waiting_approval, or rejected). Rejected campaign results include rejectionComment feedback when provided."},label:{type:"string",description:"Optional label name filter. Only campaigns assigned this label are returned."},limit:{type:"number",description:"Page size from 1 to 100. Defaults to 50."},offset:{type:"number",description:"Zero-based result offset. Defaults to 0."}}}},{name:"get_campaign",description:"Get campaign details and stats, including rejectionComment reviewer feedback for rejected campaigns. `emailId` is the campaign's linked email body - the same record returned by the templates tools - and can be passed as templateId to create_campaign to reuse the design; it is null for SMS campaigns. `targetLists` holds the raw audience targeting (IDs only); call get_campaign_audience for resolved list/segment names and a recipient count. Note that `computedLists` is email personalization (product lists rendered inside the email), not audience targeting.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_campaign_audience",description:"Resolve exactly who a campaign will reach. Returns the targeting kind, resolved list and segment names (flagging references that no longer exist), filter conditions, individual include/exclude adjustments, a plain-language summary, and a live recipient count. Critically, it reports whether targeting is unset - an unset campaign falls back to every active subscriber when scheduled. Use this to verify a scheduled campaign's audience before it sends.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"list_email_sends",description:"List and filter the recent sent-email delivery history shown in the dashboard. Search subject/title or recipient, filter by delivery status, email type, bounce type, or source ID, then pass a returned emailSendId to get_email_send for exact open/click timestamps and the complete event timeline. Each row carries recipientEmail, subscriberId, automationNodeId, abTestVariantId, and sent/delivered/opened/clicked timestamps, so rows join into a recipient-level delivery matrix without re-reading the raw event stream. Delivery rows are retained for 14 days.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},search:{type:"string",description:"Case-insensitive search across subject and recipient email."},subject:{type:"string",description:"Case-insensitive subject/title filter."},recipient:{type:"string",description:"Case-insensitive recipient email filter."},status:{type:"string",description:"Delivery status: pending, sent, delivered, opened, clicked, bounced, complained, failed, or suppressed. Opened includes clicked deliveries, matching the dashboard."},emailType:{type:"string",description:"Email type: campaign, transactional, or sequence."},bounceType:{type:"string",description:"Bounce type: Permanent or Transient."},campaignId:{type:"string",description:"Filter deliveries from one campaign."},transactionalEmailId:{type:"string",description:"Filter deliveries from one saved transactional email."},automationId:{type:"string",description:"Filter deliveries from one sequence/automation."},days:{type:"number",description:"History window in days, from 1 to 14. Defaults to 14."},page:{type:"number",description:"Page number starting at 1. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."},sortField:{type:"string",description:"Sort field: recipientEmail, subject, status, eventAt, sentAt, or createdAt. Defaults to createdAt."},sortOrder:{type:"string",description:"Sort order: asc or desc. Defaults to desc."}}}},{name:"get_email_send",description:"Get an email delivery by emailSendId, including queued and test sends, delivery status, provider failure reason, stored HTML, effective Reply-To, copied-recipient identity and primary email send ID, and the ClickHouse event timeline. `type` is the legacy source category; use `emailType` on the send and `deliveryPolicy` on events for the actual marketing or transactional policy when known. Queue jobs are internal execution details and are not exposed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Durable email delivery ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign. Omit all content fields to create an empty draft. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup. Defaults to draft; status 'sent' only archives an already-sent campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text. Optional when `prompt` is provided because the generated preview text will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider campaigns. ${Yw}`},blocks:{type:"array",description:A1,items:{type:"object"}},prompt:{type:"string",description:"Generate campaign blocks from a prompt. Generated blocks include the company's logo and footer, and the created campaign inherits the company brand font. Mutually exclusive with `html`, `blocks`, and `templateId`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},templateId:{type:"string",description:"Use a template instead of html"},segmentId:{type:"string",description:"Shorthand for targeting one saved segment. Equivalent to targetLists {type:'segment', segmentId}. Mutually exclusive with `targetLists`."},targetLists:{type:"object",description:"Campaign audience, saved on the draft. Omit to leave targeting unset and set it later with `update_campaign` or `schedule_campaign`. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Use this to send straight to a list without creating a segment first. Mutually exclusive with `segmentId`.",additionalProperties:!0},fromEmail:{type:"string",description:"From address for this campaign. Its domain must be configured and verified; a sender profile is created when needed."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail; omit it when using senderProfileId, which already carries its own display name."},senderProfileId:{type:"string",description:"Existing sender profile ID (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Reply-To address for this campaign. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},replyProfileId:{type:"string",description:"Existing reply profile ID (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},campaignData:{type:"object",description:"Optional campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Optional computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_campaign",description:"Update a draft campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line"},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested. Send an empty string to clear it."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider campaigns. ${Yw}`},blocks:{type:"array",description:A1,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail; omit it when using senderProfileId, which already carries its own display name."},senderProfileId:{type:"string",description:"Set an existing sender profile (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},ccEmails:{type:["array","null"],description:"Addresses CC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},bccEmails:{type:["array","null"],description:"Addresses BCC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},targetLists:{type:["object","null"],description:"Replace the draft's saved audience, using the same shapes as `create_campaign`. Send null to clear it and choose the audience in `schedule_campaign` instead; omit to leave it unchanged. Mutually exclusive with `segmentId`.",additionalProperties:!0},segmentId:{type:"string",description:"Shorthand for retargeting the draft at one saved segment. Equivalent to targetLists {type:'segment', segmentId}. Mutually exclusive with `targetLists`."},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign, as a one-off send or on a repeating weekly/monthly cadence via `recurringInterval`. Use `recurringInterval` for newsletters that go out on a fixed schedule instead of creating one campaign per issue. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Queue a campaign test email to a single address. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"unschedule_campaign",description:"Return a scheduled campaign to an editable draft. Removes its pending send and recurrence without permanently cancelling it, so it can be edited and scheduled again.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Scheduled campaign ID to return to draft."}},required:["campaignId"],additionalProperties:!1}},{name:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"resend_campaign_to_non_openers",description:"Create a draft that resends a sent campaign to everyone in the same audience who didn't open it. Copies the campaign email and reuses the original audience with a 'didn't open this campaign' rule added. Only available 6 hours after the campaign finishes sending. The draft must be scheduled or sent separately. Returns the new draft and an estimate of how many subscribers haven't opened the original.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"ID of the sent campaign to resend to non-openers."}},required:["campaignId"]}}];var n5=[{name:"submit_feedback",description:"Send product feedback about Sequenzy itself to the Sequenzy team. IMPORTANT: call this tool whenever the user wanted to accomplish something and Sequenzy did not expose functionality for it - a missing tool or argument, an unsupported workflow, a confusing behavior, or a bug. Briefly tell the user you reported the gap. This feedback goes straight to the team and shapes what gets built next. Do not use it for questions about the user's own account or data, and never include secrets or API keys. Submitting feedback never changes account data.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},message:{type:"string",description:"The feedback itself. Be specific: what was needed, what was missing or wrong, and what you did instead (workaround, gave up, used the dashboard)."},category:{type:"string",enum:["missing_capability","bug","docs","ux","praise","other"],description:"Feedback category. Use missing_capability when the user wanted something these tools do not support (default: other)."},context:{type:"string",description:"Optional: what the user was trying to accomplish, in their words, plus any relevant tool names or arguments you tried."}},required:["message"]}}];var p5=[{name:"list_forms",description:"List saved signup forms for a company, including their server-managed audience settings and public action URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list forms for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"create_form",description:"Create and publish a saved signup form whose opaque formId is a client-safe public capability. The selected lists, tags, duplicate behavior, and success action stay server-side; no API key is needed in the deployed form.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the form in. If not provided, uses the currently selected company."},name:{type:"string",description:"Internal saved-form name."},listIds:{type:"array",description:"One or more list IDs that every public submission will be added to. Use list_lists to resolve IDs.",items:{type:"string"}},tagIds:{type:"array",description:"Optional existing tag IDs applied by the saved form. Use list_tags to resolve IDs.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber. Defaults to skip."},buttonText:{type:"string",description:"Optional submit button label."},headline:{type:"string",description:"Optional form headline."},description:{type:"string",description:"Optional supporting form copy."},successMessage:{type:"string",description:"Confirmation shown after a successful submission when redirectUrl is omitted."},redirectUrl:{type:"string",description:"Optional HTTP or HTTPS URL for successful submissions. Omit it to show the saved confirmation message."},showFirstName:{type:"boolean",description:"Whether the generated form also collects first name."},showLastName:{type:"boolean",description:"Whether the generated form also collects last name."},theme:{type:"object",description:"Optional visual theme overrides so the form matches the brand instead of the default accent. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0}},required:["name","listIds"],additionalProperties:!1}},{name:"update_form",description:"Update a saved signup form: rename it, retarget its audience, edit its copy, restyle its theme, or replace its content blocks (for example to remove unwanted blocks that render publicly). Read the current content via list_forms first when editing blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."},name:{type:"string",description:"New internal saved-form name."},listIds:{type:"array",description:"Replacement list targeting. Every public submission will be added to these lists.",items:{type:"string"}},tagIds:{type:"array",description:"Replacement tag IDs applied by the saved form. Pass an empty array to clear tags.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber."},headline:{type:"string",description:"New text for the form's first heading block. Fails if the form has no heading block; edit blocks instead."},description:{type:"string",description:"New text for the form's first paragraph block. Fails if the form has no paragraph block; edit blocks instead."},buttonText:{type:"string",description:"New submit button label."},successMessage:{type:"string",description:"New confirmation message on the success screen."},redirectUrl:{type:"string",description:"HTTP or HTTPS URL for successful submissions. Pass an empty string to switch back to the confirmation message."},theme:{type:"object",description:"Visual theme overrides merged into the current theme. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0},blocks:{type:"array",description:"Full replacement for the form's content blocks. Fetch the current blocks from list_forms, modify them, and send the complete array - the form must keep exactly one email field and one submit button.",items:{type:"object",additionalProperties:!0}}},required:["formId"],additionalProperties:!1}},{name:"get_form_embed",description:"Get a published saved form's action URL, one-line JavaScript embed, minimal native form action, and fetch example. Use this for Astro, Hugo, Jekyll, Cloudflare Pages, Netlify, GitHub Pages, or any browser integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."}},required:["formId"],additionalProperties:!1}}];var d5=[{name:"upload_image_asset",description:"Upload an image to the selected company's shared media library and return a hosted URL plus a ready-to-insert Sequenzy image block. Call this before create/update campaign, sequence, template, or transactional tools, then place the returned imageBlock in the target blocks array. Provide either filePath (local stdio MCP only) or imageBase64 (works with remote MCP when the client can supply attachment bytes), not both. PNG, JPEG, GIF, and WebP are supported up to 5MB. cropHeight with objectFit:'cover' provides a precise centered screenshot crop while displayWidthPercent keeps the image responsive.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},filePath:{type:"string",description:"Local path to a PNG, JPEG, GIF, or WebP image. Available only when the MCP server runs locally. Provide filePath or imageBase64, not both."},imageBase64:{type:"string",description:"Raw base64 image bytes or a base64 data URL. Use this for remote MCP clients that can access attachment bytes. Provide imageBase64 or filePath, not both."},filename:{type:"string",description:"File name including extension. Required with imageBase64; optional override with filePath."},contentType:{type:"string",description:"Image MIME type when it cannot be inferred from filename, such as image/png."},altText:{type:"string",description:"Accessible description stored with the asset and returned as imageBlock.alt. Use an empty string only for a decorative image."},sourceWidth:{type:"integer",minimum:1,maximum:20000,description:"Optional intrinsic source width in pixels. Provide sourceWidth and sourceHeight together when known."},sourceHeight:{type:"integer",minimum:1,maximum:20000,description:"Optional intrinsic source height in pixels. Provide sourceWidth and sourceHeight together when known."},displayWidthPercent:{type:"number",minimum:1,maximum:100,description:"Responsive image width as a percentage of the email content area. Defaults to 100."},cropHeight:{type:"integer",minimum:1,maximum:2000,description:"Optional fixed display height in pixels. With objectFit:'cover', the image is centered and cropped to this height."},objectFit:{type:"string",enum:["cover","contain"],description:"How the image fits cropHeight. Defaults to cover when cropHeight is provided. Only valid with cropHeight."},align:{type:"string",enum:["left","center","right"],description:"Image alignment. Defaults to center."}},additionalProperties:!1}}];var o5=[{name:"list_conversations",description:"List inbox conversations (email replies from subscribers). Filter by status, free-text search, or unread state, with pagination.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},status:{type:"string",enum:["open","closed","all"],description:"Filter by conversation status. Defaults to all."},search:{type:"string",description:"Free-text search across conversation subjects and participants."},unread:{type:"boolean",description:"Set true to only return conversations with unread messages."},page:{type:"number",description:"Page number. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."}}}},{name:"get_conversation",description:"Get a conversation with its full message history, subscriber details, and context.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}},{name:"reply_to_conversation",description:"Send a reply in a conversation, or add an internal note. type 'outbound' (default) emails the subscriber and requires bodyText or bodyHtml; type 'note' adds a private team-only note. Replying to a closed conversation reopens it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID to reply in."},type:{type:"string",enum:["outbound","note"],description:"Message type: outbound emails the subscriber, note is internal-only. Defaults to outbound."},subject:{type:"string",description:"Optional subject override. Defaults to the conversation subject."},bodyText:{type:"string",description:"Plain-text message body."},bodyHtml:{type:"string",description:"HTML message body."}},required:["conversationId"]}},{name:"update_conversation_status",description:"Open or close a conversation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."},status:{type:"string",enum:["open","closed"],description:"New conversation status."}},required:["conversationId","status"]}},{name:"mark_conversation_read",description:"Mark all unread inbound messages in a conversation as read.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}}];var t5=[{name:"connect_integration",description:"Connect an API-key / webhook-secret integration: polar, paddle, dodo, whop, creem, chargebee, clerk, posthog, or affonso. Check list_integration_capabilities first - each connectable provider lists its exact connectFields there. Credentials are validated against the provider where possible, stored encrypted, and never returned; payment providers queue their initial revenue backfill automatically. The response includes the webhookUrl the user must configure at the provider with the same secret - always relay it. Reconnecting an already-connected provider replaces its stored credentials. OAuth and app-install providers (Stripe, Shopify, Supabase, GitHub, WooCommerce, Meta) are rejected with guidance: their flows need a human in the dashboard. SECURITY: only pass credentials the user explicitly provided for this purpose; suggest the CLI (`sequenzy integrations connect`) or dashboard when the user prefers keeping secrets out of the conversation.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Provider to connect: polar, paddle, dodo, whop, creem, chargebee, clerk, posthog, or affonso.",enum:["polar","paddle","dodo","whop","creem","chargebee","clerk","posthog","affonso"]},apiKey:{type:"string",description:"Provider API key. Required for every provider except clerk and posthog."},webhookSecret:{type:"string",description:"Signing secret of the webhook you create at the provider, pointed at the returned webhookUrl. Required for every provider. For Chargebee, pass the webhook's basic-auth credentials as username:password."},providerAccountId:{type:"string",description:"Provider account id, required for paddle (seller ID), dodo (business ID), whop (company ID, biz_...), creem (store ID), and chargebee (site name). Polar resolves it from the API key; clerk, posthog, and affonso do not use one."},settings:{type:"object",description:"PostHog only: event delivery scope. Defaults to syncing all non-internal events.",properties:{syncAllEvents:{type:"boolean",description:"Sync every event PostHog delivers."},eventAllowlist:{type:"array",items:{type:"string"},description:"Only sync these PostHog event names. Set syncAllEvents to false when using this."}}},historyImport:{type:"object",description:"PostHog only: import the project's event history after connecting. Needs a personal API key with query read access.",properties:{region:{type:"string",enum:["us","eu"],description:"PostHog Cloud region hosting the project."},projectId:{type:"string",description:"Numeric PostHog project ID."},personalApiKey:{type:"string",description:"PostHog personal API key (phx_...)."}},required:["region","projectId","personalApiKey"]},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["provider","webhookSecret"]}},{name:"get_integration",description:"Inspect one connected integration in depth: what the provider syncs, every event it can emit and when, every matching tag rule, which sequences trigger on those events, recent integration-specific activity, and prioritized recommendations. `observedByAccount` and `accountLastSeenAt` are account-wide because event definitions can also be updated by another integration or the public events API; use the retained activity log for connection-specific delivery diagnosis. Read-only; credentials are never returned. Get the id from list_integrations.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"list_integration_capabilities",description:"Describe what Sequenzy's integration providers do, whether or not they are connected. For each provider: category, how it connects, what it syncs, every event it emits with the real-world moment that triggers it, the subscriber attributes it writes, supported actions, availability, and caveats. Use this to answer 'what would connecting Stripe give me?', to compare providers before recommending one, or to check whether an event a sequence needs actually exists for that provider. Coverage differs sharply between providers - only Shopify has storefront browse tracking, and only Stripe and Chargebee cover the full trial lifecycle - so check here rather than assuming.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Only return this provider, for example `stripe`, `shopify`, `clerk`. Omit to list every provider."},category:{type:"string",description:"Filter by category: payments, ecommerce, auth, analytics, ads, affiliate, cms, developer."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_integration_activity",description:"Read recent integration webhook and sync activity, newest first. This is the log to check when an integration reports connected but contacts or events are not appearing: each row carries the action, status, event type, matched contact, and error. Payloads are sanitized at write time, so no credentials or secrets appear here. Activity is retained for 24 hours only.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Only show activity for this integration."},provider:{type:"string",description:"Only show activity for this provider, for example `stripe`."},status:{type:"string",description:"Filter by status: received, queued, processed, skipped, or failed. Use `failed` to triage a broken integration.",enum:["received","queued","processed","skipped","failed"]},limit:{type:"number",description:"Rows to return, 1-100. Defaults to 25."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"set_integration_sync_enabled",description:"Turn a supported payment integration's future bulk imports and backfills on or off. Check get_integration.availableActions first; providers without enable_sync or disable_sync are dashboard-managed. Disabling keeps the connection, credentials, and live webhook delivery active, and requires any in-flight sync to finish first. It does not disconnect the integration. Idempotent: setting the current state succeeds with `changed: false`.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},syncEnabled:{type:"boolean",description:"True to enable sync, false to pause it."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId","syncEnabled"]}},{name:"get_integration_pixel",description:"Check whether a Shopify store's storefront tracking pixel is installed and reporting to this account. Read live from Shopify on every call, because a merchant can remove the pixel without Sequenzy hearing about it. ALWAYS check this before promising that browse abandonment, cart recovery, product views, collection views, or storefront search will work: without a live pixel those events never arrive, the sequences built on them never fire, and nothing anywhere reports an error. Returns `pixel.healthy`, the endpoint and signed configuration state, and `dependentEvents` - the event names that rely on this pixel. When `pixel.error` is null and `pixel.healthy` is false, those events are confirmed dark; an error means Shopify could not confirm their state. Fix a confirmed unhealthy state with activate_integration_pixel. Shopify only; other providers return a clear error.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Shopify integration ID from list_integrations or get_integration."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"activate_integration_pixel",description:"Install the Shopify storefront tracking pixel on the connected store, or repoint an existing one at this account. This is what turns on product views, cart activity, and browse abandonment - the data every browse-abandonment and cart-recovery sequence depends on. Idempotent: an already-live pixel returns `changed: false`. Events start flowing on the next storefront visit and nothing is backfilled for the period the pixel was off, so run it before, not after, building the sequence. If the store granted an older permission set, this fails with a message naming the reconnect step rather than silently doing nothing. Shopify only.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Shopify integration ID from list_integrations or get_integration."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"sync_integration",description:"Queue a manual re-sync of customers and revenue for a payment provider integration (Stripe, Polar, Paddle, Dodo, Creem, Chargebee, Whop). Returns immediately - poll get_integration to watch `syncStatus` and `lastSyncAt`. Fails with a conflict if a sync is already running, and with a clear error naming the dashboard for providers whose backfill is not API-triggerable (Shopify products, Supabase users, PostHog history, Affonso affiliates). Check `availableActions` on get_integration to see whether this is supported before calling.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}}];var r5=[{name:"list_landing_pages",description:"List all landing pages for a company",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list landing pages for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"get_landing_page",description:"Get landing page details, content, metrics, and URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"create_landing_page",description:"Create a draft landing page. Provide content for an exact page, or a template for generated starter content.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the landing page in. If not provided, uses the currently selected company."},name:{type:"string",description:"Landing page name. Optional; defaults to a template-specific name."},slug:{type:"string",description:"Optional URL slug. It will be normalized and made unique within the company."},template:{type:"string",description:rH},content:{type:"object",description:Lb,additionalProperties:!0}},additionalProperties:!1}},{name:"update_landing_page",description:"Edit a landing page's name, slug, or full content. Provide at least one update field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Landing page name."},slug:{type:"string",description:"Landing page URL slug. It will be normalized and made unique within the company."},content:{type:"object",description:Lb,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"duplicate_landing_page",description:"Duplicate a landing page. The copy is created as a draft with its own slug and stats, so the original keeps its published URL.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID to duplicate."},name:{type:"string",description:"Optional name for the copy. Defaults to the original name with a (copy) suffix."},slug:{type:"string",description:"Optional slug for the copy. It will be normalized and made unique within the company."}},required:["landingPageId"],additionalProperties:!1}},{name:"delete_landing_page",description:"Delete a landing page",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"publish_landing_page",description:"Publish a landing page. Optional name, slug, or content updates are saved before publishing.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before publishing."},content:{type:"object",description:Lb,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"unpublish_landing_page",description:"Unpublish a landing page and return it to draft status. Optional name, slug, or content updates are saved first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before unpublishing."},content:{type:"object",description:Lb,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"connect_landing_page_domain",description:"Connect a custom domain for published landing pages. Returns the DNS target and verification records.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Custom domain, for example pages.example.com."}},required:["domain"],additionalProperties:!1}},{name:"update_landing_page_domain_settings",description:"Update landing page domain settings. Provide domain to replace the custom domain, verify true to refresh verification, or both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Replacement custom domain."},verify:{type:"boolean",description:"Refresh domain verification after any domain update."}},additionalProperties:!1}}];var s5=[{name:"list_products",description:"List synced products (Stripe, Shopify, WooCommerce) including any attached digital delivery file. Useful before attaching a file or building a purchase sequence for a specific product. Returns one page: check pagination.total and pagination.hasMore, and page with offset to read the whole catalog.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list products for. If not provided, uses the currently selected company."},provider:{type:"string",description:"Filter by provider: stripe, shopify, woocommerce, or manual."},search:{type:"string",description:"Filter products by title."},limit:{type:"number",description:"Maximum products to return (1-100). Defaults to 50. Compare pagination.total against the products returned to detect truncation."},offset:{type:"number",description:"Number of products to skip. Defaults to 0. Use with limit to page through catalogs larger than 100."}}}},{name:"upsert_products",description:"Create or update products in the catalog (Commerce API, keyed by your productId, stored under the api provider). Use this to add products that are not synced from Stripe/Shopify/WooCommerce, then attach a deliverable file with attach_product_file and build a purchase sequence for them.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},products:{type:"array",description:"Products to create or update (max 100).",items:{type:"object",properties:{productId:{type:"string",description:"Your stable product identifier (used for upserts and order line items)."},title:{type:"string",description:"Product title."},description:{type:"string",description:"Product description."},imageUrl:{type:"string",description:"Product image URL."},url:{type:"string",description:"Product page URL."},priceCents:{type:"number",description:"Price in the smallest currency unit."},currency:{type:"string",description:"ISO currency code, e.g. USD."},inStock:{type:"boolean",description:"Whether the product is in stock."},providerCreatedAt:{type:["string","null"],description:"ISO 8601 creation time from the source catalog. Omit to preserve the stored value; pass null to clear it. Used for newest-product ranking."}},required:["productId","title"]}}},required:["products"]}},{name:"delete_product",description:"Delete a product previously pushed via upsert_products (Commerce API products only), identified by your productId.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Your productId used when upserting the product."}},required:["productId"]}},{name:"attach_product_file",description:"Attach a distributable file to a product, either by public URL or by uploading a local file (filePath, local MCP server only). After a purchase of the product, sequence emails can link to it with {{event.download.url}} and {{event.download.name}}.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."},url:{type:"string",description:"Public http(s) URL of the file to deliver. Provide url or filePath, not both."},filePath:{type:"string",description:"Local path of a file to upload and attach (PDF, ePub, ZIP, image, audio, video, or text, up to 100MB). Only available when the MCP server runs locally on this machine."},fileName:{type:"string",description:"Display name for the file (e.g. guide.pdf). Used as {{event.download.name}}."}},required:["productId"]}},{name:"remove_product_file",description:"Remove the attached distributable file from a product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."}},required:["productId"]}},{name:"sync_products",description:"Queue a sync of the Stripe product catalog into the products list. Requires an active Stripe integration with bulk sync enabled. Pass integrationId when more than one Stripe account is connected; otherwise the most recently connected enabled account is used.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},integrationId:{type:"string",description:"Stripe integration ID from list_integrations. Recommended when multiple Stripe accounts are connected."}}}}];var e5=[{name:"render_email",description:"Render a campaign, sequence email step, or template to the exact email-safe HTML that would be sent, for embedding a visual preview in an external builder or dashboard, or for checking merge tags before anyone is enrolled. Pass exactly one target: campaignId, sequenceId plus nodeId, or templateId. Without a subscriber the email renders for a sample contact, so contact-specific merge tags resolve to empty values. Check unresolvedMergeTags in the response to tell an unrecognized tag apart from one that is merely blank for this contact - both render as an empty string, so the HTML alone cannot distinguish them. Only names this render could check are called unknown. Nothing is checkable without the contact's attributes, because a bare {{plan}} reads the same attribute map as {{subscriber.plan}}, so pass subscriberId (or an inline subscriber with customAttributes) to catch typos at all. On top of that, {{event.*}} needs sample event properties in variables, since a real send fills those from the enrolling event, and {{recommendedProducts.*}} is only checkable when a stored subscriberId returns recommendations. Rendering a transactional email is checkable only when variables is passed, since its tags come from the variables of each send call and nothing marks them as such. An optional attribute this contact never had set is kept out of unknown by checking the names other contacts in the account carry, which needs the subscribers:read scope. A sequence step downstream of a create_discount step renders {{discount.*}} with that step's real terms and a clearly fake sample code; when the step is reachable by paths that do not all run the same discount step, or when a template is rendered on its own, {{discount.*}} is reported as no_value rather than as a typo. Links stay clean unless tracking is true. Per-send click redirects and the open pixel are added at send time against a real email send record, so they never appear here.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to render."},sequenceId:{type:"string",description:"Sequence ID. Requires nodeId."},nodeId:{type:"string",description:"Email step node ID from get_sequence. Requires sequenceId."},templateId:{type:"string",description:"Template ID to render."},subscriberId:{type:"string",description:"Personalize as this stored subscriber. Mutually exclusive with subscriber. The rendered HTML then carries that subscriber's details, so this needs the subscribers:read scope as well."},subscriber:{type:"object",description:"Personalize as an ad-hoc contact that need not exist in the account. Mutually exclusive with subscriberId.",properties:{email:{type:"string",description:"Contact email address."},firstName:{type:"string",description:"Contact first name."},lastName:{type:"string",description:"Contact last name."},customAttributes:{type:"object",description:"Custom attributes used by merge tags and blocks.",additionalProperties:!0}},required:["email"]},variables:{type:"object",description:"Extra merge variables layered over the contact's attributes.",additionalProperties:!0},locale:{type:"string",description:"Force a localization locale instead of deriving it from the contact."},variantId:{type:"string",description:"Render a specific A/B test variant of the campaign or sequence step."},tracking:{type:"boolean",description:"Apply the company's auto-UTM link decoration as a real send would. Defaults to false so the preview shows the author's clean URLs."}},required:[]}}];var J4={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."}},a5={name:{type:"string",description:"Goal name."},description:{type:["string","null"],description:"Optional goal description."},triggerType:{type:"string",enum:["event","attribute_change"],description:"Conversion signal type. Defaults to event when creating."},triggerEventName:{type:["string","null"],description:"Required event name for event goals."},attributePath:{type:["string","null"],description:"Subscriber attribute path required for attribute_change goals."},attributeCondition:{type:["string","null"],enum:["changed","changed_to","changed_from_to",null],description:"How the subscriber attribute must change."},attributeValue:{type:["string","null"],description:"Target value for changed_to or changed_from_to."},attributePreviousValue:{type:["string","null"],description:"Previous value required for changed_from_to."},eventPropertyName:{type:["string","null"],description:"Optional event property whose numeric value is tracked."},eventPropertyLabel:{type:["string","null"],description:"Display label for the tracked event property."},attributionWindowHours:{type:"integer",minimum:1,maximum:720,description:"Attribution window in whole hours."},isActive:{type:"boolean",description:"Whether conversion tracking is active for this goal. Defaults to true when creating."}},w3=[{name:"list_sequence_goals",description:"List persisted conversion goals attached to one sequence in the dashboard.",inputSchema:{type:"object",properties:J4,required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence_goal",description:"Create a persisted event or subscriber-attribute conversion goal for one sequence. Event goals (the default triggerType) require triggerEventName; attribute_change goals require attributePath. This is distinct from create_sequence.goal, which is only an AI content prompt.",inputSchema:{type:"object",properties:{...J4,...a5},required:["sequenceId","name"],additionalProperties:!1}},{name:"update_sequence_goal",description:"Update a persisted sequence conversion goal, including its signal, attribution window, or active state.",inputSchema:{type:"object",properties:{...J4,goalId:{type:"string",description:"Sequence goal ID."},...a5},required:["sequenceId","goalId"],additionalProperties:!1}},{name:"delete_sequence_goal",description:"Delete one persisted sequence conversion goal.",inputSchema:{type:"object",properties:{...J4,goalId:{type:"string",description:"Sequence goal ID."}},required:["sequenceId","goalId"],additionalProperties:!1}}];var WW={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence with an inbound_webhook trigger."}},b3=[{name:"get_sequence_inbound_webhook",description:"Read the usable URL, mapping, sample payload, and setup status for a sequence inbound webhook.",inputSchema:{type:"object",properties:WW,required:["sequenceId"],additionalProperties:!1}},{name:"configure_sequence_inbound_webhook",description:"Create or update the secret endpoint attached to a sequence inbound_webhook trigger. On first setup, omitted mapping/sample inputs apply the selected catalog or custom integration defaults; on later calls, omitted inputs keep the saved values, so a captured sample survives mapping-only updates. Use clearFieldMapping to return to pending setup and clearSamplePayload to drop the saved sample.",inputSchema:{type:"object",properties:{...WW,fieldMapping:{type:"object",properties:{email:{type:"string"},firstName:{type:"string"},lastName:{type:"string"},properties:{type:"object",additionalProperties:{type:"string"}}},required:["email"],additionalProperties:!1},samplePayload:{type:"object",description:"Representative raw webhook payload for mapping setup.",additionalProperties:!0},clearFieldMapping:{type:"boolean",description:"Set true to clear the saved mapping and return the endpoint to pending_setup."},clearSamplePayload:{type:"boolean",description:"Set true to clear the saved sample payload."}},required:["sequenceId"],additionalProperties:!1}},{name:"rotate_sequence_inbound_webhook_secret",description:"Rotate the inbound webhook secret and return a new URL. The previous URL stops working immediately.",inputSchema:{type:"object",properties:WW,required:["sequenceId"],additionalProperties:!1}}];var $3=[{name:"list_sequences",description:"List all email sequences (automations). Read effectiveStatus (draft, live, enrollment_paused, paused, archived) to know whether a sequence is running: status alone reads `active` even when new enrollments are paused, and the legacy triggerConfig.active flag is not used by the runtime.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."},status:{type:"string",enum:["draft","active","paused","archived"],description:"Optional dashboard status filter."},search:{type:"string",description:"Case-insensitive search across sequence name and description."},labels:{type:"array",items:{type:"string"},description:"Return sequences assigned any of these dashboard label names."},limit:{type:"number",description:"Page size from 1 to 100. When limit and offset are both omitted, every sequence is returned."},offset:{type:"number",description:"Zero-based result offset."}}}},{name:"get_sequence",description:"Get sequence details, editable step content, and graph topology. Read effectiveStatus (draft, live, enrollment_paused, paused, archived) to know whether a sequence is running: status alone reads `active` even when new enrollments are paused, and the legacy triggerConfig.active flag is not used by the runtime. Each sequence.nodes item includes id, nodeType, current config, updatedAt, and updateHints with its editable/managed fields and ready-to-return expectedUpdatedAt token for update_sequence_node/update_sequence_nodes. The response also includes sequence.edges and graphRevision for safe edit_sequence_graph calls, plus sequence.emails with each email step's nodeId, linked emailId, subject, previewText, emailPreset (the per-email Style > Format for native blocks, including emails with supported custom HTML blocks; null when the entire email is standalone raw HTML), and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"],additionalProperties:!1}},{name:"list_sequence_enrollments",description:"List the individual contacts currently enrolled in a sequence, with the node each one is sitting on. Use this when get_sequence_stats gives you enrollmentCounts and you need the actual subscribers behind a number, such as everyone waiting at one step. Filter by currentNodeId (take the ID from get_sequence_stats enrollmentCounts.byCurrentNode or get_sequence nodes), status, subscriberId, or email, and page with limit/offset to export the full list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be listed."},currentNodeId:{type:"array",items:{type:"string"},description:"Only return enrollments currently sitting on these sequence node IDs."},status:{type:"array",items:{type:"string",enum:["active","waiting","completed","failed","cancelled"]},description:"Enrollment statuses to include. Defaults to active and waiting, which is every contact still moving through the sequence."},subscriberId:{type:"array",items:{type:"string"},description:"Only return enrollments for these subscriber IDs. Useful for checking where specific contacts stand."},email:{type:"string",description:"Only return enrollments for this exact email address (case-insensitive)."},sort:{type:"string",enum:["enrolled_at_desc","enrolled_at_asc","wait_until_asc","wait_until_desc"],description:"Result order. Defaults to enrolled_at_desc (most recently enrolled first). Use wait_until_asc to see who resumes next."},limit:{type:"number",description:"Enrollments per page, 1-500. Defaults to 50. Use the maximum when exporting."},offset:{type:"number",description:"Number of enrollments to skip. Page until pagination.hasMore is false."}},required:["sequenceId"],additionalProperties:!1}},{name:"send_sequence_test_email",description:"Queue a real test send for one saved email step in a sequence. Call get_sequence first and pass the target email step's nodeId. Accepts 1-10 reviewer email addresses and returns one durable emailSendId per recipient for get_email_send delivery inspection. The sequence is not enabled and no subscribers are enrolled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID containing the saved email step."},nodeId:{type:"string",description:"Email step nodeId from get_sequence. The node must belong to sequenceId."},recipients:{type:"array",minItems:1,maxItems:10,items:{type:"string",format:"email"},description:"One to ten internal reviewer email addresses. Duplicate addresses are sent only once."}},required:["sequenceId","nodeId","recipients"],additionalProperties:!1}},{name:"create_sequence",description:"Create and persist a disabled draft email sequence, follow-up series, drip campaign, nurture flow, or automation workflow. For natural-language content, provide goal and emailCount. Use explicit steps for finished caller-supplied content, exact workflows, or migrations. Configure trigger plus its relevant field, such as listId, tagName, segmentId, or eventName. Supports email and SMS steps, delays and date waits, actions that dynamically create a provider discount/code (later emails print it with {{discount.code}}), subscriber updates, event filters, enrollment rules, sending windows, and stop conditions. The saved draft appears in list_sequences. Never call enable_sequence unless the user explicitly asks to activate it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail; omit it when using senderProfileId, which already carries its own display name."},senderProfileId:{type:"string",description:"Existing sender profile ID (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},replyProfileId:{type:"string",description:"Existing reply profile ID (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},description:{type:"string",description:"Optional sequence description shown in the dashboard."},userCancellable:{type:"boolean",description:"Whether subscribers may cancel their own active enrollment."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses blind-copied on every email in the sequence (max 10)."},labels:{type:"array",items:{type:"string"},description:"Dashboard label names to assign. Missing labels are created."},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inbound_webhook","inactivity","frequency"],description:"Trigger type: contact_added, tag_added, segment_entered, event_received, inbound_webhook, inactivity, or frequency. Defaults to contact_added for a blank dashboard-compatible draft."},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},stopOnSegmentExit:{type:"boolean",description:"For segment_entered triggers, cancel active enrollments when the contact leaves the segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inbound_webhook, inactivity, and frequency triggers)"},integrationSlug:{type:"string",description:"Catalog integration slug for inbound_webhook, for example cal-com."},integrationEventKey:{type:"string",description:"Catalog integration event key for inbound_webhook."},customIntegration:{type:"object",description:"Custom inbound webhook integration descriptor with name, setupInstructions, samplePayload, and fieldMapping.",properties:{name:{type:"string"},setupInstructions:{type:"string"},samplePayload:{type:"object",additionalProperties:!0},fieldMapping:{type:"object",additionalProperties:!0},docsUrl:{type:"string"},suggestedProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},path:{type:"string"},description:{type:"string"}},required:["name","path","description"]}}},required:["name","setupInstructions","samplePayload","fieldMapping"]},propertyFilters:{type:"array",description:"Optional filters for event_received or inbound_webhook triggers. The sequence starts only when all filters match. Max 10.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},emailStyle:{type:"string",enum:["visual","plain"],description:"Style for AI-generated emails: 'visual' (designed, with heroes/imagery/rich sections) or 'plain' (personal, text-first notes with a single button). Only applies to goal-based AI generation. Defaults to the company's saved preference when omitted."},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Defaults to 'unlimited', which re-enrolls a subscriber every time the trigger fires again - for a tag_added drip that means re-applying the tag sends the whole series a second time, so set 'one_time' unless repeat runs are wanted. Exception: ecommerce.back_in_stock and ecommerce.replenishment_due triggers default to 'matching_field' so each product is notified separately; leave those alone unless the user asks otherwise. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value. Changeable later with update_sequence."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},sendingWindow:t6,stopCondition:{type:"object",description:"Optional explicit auto-stop condition, re-evaluated before every step including the first one. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'added_to_list', value: 'list_123' } when they join a list, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop. The negative forms are audience guards rather than lifecycle stops: { type: 'does_not_have_tag', value: 'allowlist' } and { type: 'removed_from_list', value: 'list_123' } cancel the run before any step sends unless the subscriber carries that tag or list membership. That is how you restrict a live event or segment trigger to a chosen set of contacts without editing the graph, for example for a first pass on a production trigger or a phased rollout. Guarded-out contacts still enroll and are then cancelled at the trigger node, so they appear as cancellations there rather than in the active or waiting enrollment counts. Clearing the guard does not retry them: nothing re-enrolls them, so they only receive the sequence if the trigger fires for them again, which one-shot triggers never do, and on the one_time enrollment mode a repeated trigger is ignored too because enrollment is blocked by the existence of any earlier run rather than by its outcome. Guard a duplicate sequence and leave the real one ungated, or enroll the missed contacts afterwards with enroll_subscribers_in_sequence, which skips the one_time check.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type. has_tag, added_to_list, entered_segment, field_changed, and event_received stop the run once the thing happens. does_not_have_tag and removed_from_list stop the run whenever the subscriber lacks that tag or list membership, so they act as a required-tag or required-list allowlist for everyone the trigger enrolls."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. For the does_not_have_tag and removed_from_list guards this is the tag or list a subscriber must have to keep receiving the sequence. Use null or omit for type 'none'."},matchConfig:{type:["object","null"],description:"Optional dashboard-compatible match config: event_property with rules[{entryFieldPath,eventFieldPath}] for event_received, or field_value with operator/value for field_changed.",additionalProperties:!0}},required:["type"]},steps:{type:"array",description:"Explicit sequence steps. Omit type for email steps, use type: 'sms' for SMS, type: 'create_discount' for a dynamic discount, or type: 'update_subscriber' with nodeType: 'action_update_attributes' and config to copy trigger-event values such as {{event.plan}} into subscriber data.",items:{type:"object",properties:{type:{type:"string",enum:["email","sms","create_discount","discount","update_subscriber"],description:"Step type. Omit or use 'email' for email content. Use 'sms' to send a text message, 'create_discount' to generate a code, or 'update_subscriber' to copy trigger data into the subscriber."},nodeType:{type:"string",enum:["action_email","action_sms","action_create_discount","action_update_attributes"],description:"Internal step type. Use action_update_attributes with config for Update Subscriber steps."},config:L0,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:H0,items:{type:"object"}},html:{type:"string",description:`HTML content for email steps. Use this for imported provider HTML. ${Yw}`},isTransactional:{type:"boolean",description:"Send this email as transactional and omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Addresses CC'd on this email step."},bccEmails:{type:"array",items:{type:"string"},description:"Addresses BCC'd on this email step in addition to sequence BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string",description:"Filename shown in the recipient's email client. Event merge tags are supported, for example file-{{event.order_id}}.pdf."},path:{type:"string",description:"Public HTTPS URL or event-backed URL template such as {{event.file_url}}; resolved per enrollment and fetched at send time."}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). Paths may use {{event.*}} values from the event that enrolled the subscriber; the resolved public URL is validated and fetched at send time."},...Ob,text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:D0,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:z0,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:`Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.${d6}`,properties:{label:{type:"string",description:"Builder label for the discount step."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use 'stripe' to dynamically create a Stripe coupon plus promotion code, or 'shopify' to dynamically create a Shopify Admin discount code. Defaults to 'stripe' when omitted."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional display name for each dynamically generated provider discount."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe","shopify"],description:"Legacy top-level discount provider. Prefer discount.provider. Supports 'stripe' and 'shopify'."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name"]}}];var W3=[{name:"update_sequence",description:"Update an existing sequence: both its settings and its steps. Sequence-level settings live directly on this tool - name, description, labels, trigger (with its trigger-specific field), enrollmentMode plus enrollmentFieldPath, enrollmentPaused, userCancellable, stopCondition, sendingWindow, bccEmails, and the sender/reply identity. This is the only way to change enrollmentMode after create_sequence, so use it to move a tag- or event-triggered sequence off the default 'unlimited' re-entry to 'one_time' or 'matching_field'. To target a specific existing step, use IDs returned by get_sequence. The emails/steps arrays edit email steps, smsSteps edits SMS steps, and subscriberUpdateSteps replaces the config of action_update_attributes steps. To insert new linear steps, use insertSteps with an afterNodeId from get_sequence; omit afterNodeId only to append to an unambiguous linear tail. Deleting a step immediately moves parked recipients to its unique surviving successor, or completes them when no successor remains; inspect migratedRecipientCount and completedRecipientCount in the returned sequence. For active sequences, structural changes such as insertSteps or branch require confirmStructuralChange:true after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},description:{type:"string",description:"Sequence description shown in the dashboard."},userCancellable:{type:"boolean",description:"Whether subscribers may cancel their own active enrollment."},labels:{type:"array",items:{type:"string"},description:"Replace dashboard labels by name. Missing labels are created; [] clears labels."},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inbound_webhook","inactivity","frequency"],description:"Atomically replace the existing dashboard trigger. Include the fields required by the new trigger type. Active sequences also require confirmLiveChange:true."},listId:{type:"string",description:"List ID for a contact_added trigger replacement."},tagName:{type:"string",description:"Tag name required for a tag_added trigger replacement."},segmentId:{type:"string",description:"Saved segment ID required for a segment_entered trigger replacement."},stopOnSegmentExit:{type:"boolean",description:"For segment_entered, stop active enrollments when the subscriber leaves the segment."},eventName:{type:"string",description:"Event name required for event_received, inbound_webhook, inactivity, and frequency trigger replacements."},propertyFilters:{type:"array",description:"Optional event-property filters for event_received or inbound_webhook.",items:{type:"object",properties:{path:{type:"string"},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"]},value:{description:"Scalar comparison value, or an array for one_of."}},required:["path","operator"],additionalProperties:!1}},integrationSlug:{type:"string",description:"Catalog integration slug for inbound_webhook."},integrationEventKey:{type:"string",description:"Catalog integration event key for inbound_webhook."},customIntegration:{type:"object",description:"Typed custom inbound webhook descriptor used instead of a catalog integration.",properties:{name:{type:"string"},setupInstructions:{type:"string"},samplePayload:{type:"object",additionalProperties:!0},fieldMapping:{type:"object",properties:{email:{type:"string"},firstName:{type:"string"},lastName:{type:"string"},properties:{type:"object",additionalProperties:{type:"string"}}},required:["email"],additionalProperties:!1},docsUrl:{type:"string"},suggestedProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},path:{type:"string"},description:{type:"string"}},required:["name","path","description"],additionalProperties:!1}}},required:["name","setupInstructions","samplePayload","fieldMapping"],additionalProperties:!1},inactiveDays:{type:"number",description:"Days without event activity required for an inactivity trigger."},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"Baseline for subscribers who have never produced the inactivity event."},minCount:{type:"number",description:"Minimum event count for a frequency trigger."},timeWindowDays:{type:"number",description:"Frequency trigger lookback window in days."},fromEmail:{type:"string",description:"Set the From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail; omit it when using senderProfileId, which already carries its own display name."},senderProfileId:{type:"string",description:"Set an existing sender profile (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},replyProfileId:{type:"string",description:"Set an existing reply profile (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},enrollmentPaused:{type:"boolean",description:"Set true to stop new enrollments for an active sequence while current recipients continue. Set false to resume new enrollments. The sequence must already be active."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence. Required for insertSteps or branch when the sequence is active; not needed for content-only email edits."},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms replacing the trigger of an active sequence. Required with trigger when the sequence is active."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. Use this to move an existing sequence off the default 'unlimited', which re-enrolls a subscriber every time the trigger fires again. 'matching_field' is only valid for event-based sequence triggers."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Omit to leave unchanged. Use clearEnrollmentFieldPath to clear it."},clearEnrollmentFieldPath:{type:"boolean",description:"Set true to clear enrollmentFieldPath without sending a nullable schema value."},sendingWindow:t6,clearSendingWindow:{type:"boolean",description:"Set true to remove the sequence sending window. Do not provide this together with sendingWindow."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses that receive a blind copy of every email this sequence sends, such as a customer support inbox (max 10). Omit to leave unchanged. Use clearBccEmails to remove them."},clearBccEmails:{type:"boolean",description:"Set true to remove the sequence BCC addresses. Do not provide this together with bccEmails."},stopCondition:{type:"object",description:"Update the sequence auto-stop condition, which is re-evaluated before every step including the first one. Example: { type: 'has_tag', value: 'customer' } ends the sequence when the subscriber has that tag. Use { type: 'entered_segment', value: 'segment_123' } to stop when they enter a segment, { type: 'field_changed', value: 'plan' } to stop when a subscriber field changes, { type: 'added_to_list', value: 'list_123' } to stop when they join a list, or { type: 'none', value: null } to clear it. The negative forms are audience guards rather than lifecycle stops: { type: 'does_not_have_tag', value: 'allowlist' } and { type: 'removed_from_list', value: 'list_123' } cancel the run before any step sends unless the subscriber carries that tag or list membership. That is how you restrict a live event or segment trigger to a chosen set of contacts without editing the graph, for example for a first pass on a production trigger or a phased rollout. Guarded-out contacts still enroll and are then cancelled at the trigger node, so they appear as cancellations there rather than in the active or waiting enrollment counts. Clearing the guard does not retry them: nothing re-enrolls them, so they only receive the sequence if the trigger fires for them again, which one-shot triggers never do, and on the one_time enrollment mode a repeated trigger is ignored too because enrollment is blocked by the existence of any earlier run rather than by its outcome. Guard a duplicate sequence and leave the real one ungated, or enroll the missed contacts afterwards with enroll_subscribers_in_sequence, which skips the one_time check.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type. has_tag, added_to_list, entered_segment, field_changed, and event_received stop the run once the thing happens. does_not_have_tag and removed_from_list stop the run whenever the subscriber lacks that tag or list membership, so they act as a required-tag or required-list allowlist for everyone the trigger enrolls."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. For the does_not_have_tag and removed_from_list guards this is the tag or list a subscriber must have to keep receiving the sequence."},matchConfig:{type:["object","null"],description:"Optional event_property or field_value match config used by dashboard stop-condition matching.",additionalProperties:!0}},required:["type"]},branch:{type:"object",description:"Insert an if/else branch into an existing sequence. Use get_sequence first to choose afterNodeId and existing target nodes. Each conditional path can provide new steps, targetNodeId, or both; the else path uses elseSteps and/or elseTargetNodeId. A target may be the completion node. Empty paths require allowEmptyPaths:true. Conditions support tag presence/absence, lists, saved segments, events, clicked links, and field comparisons. Use activityScope for event_received and link_clicked checks.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert the branch after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails."},label:{type:"string",description:"Optional branch node label."},branches:{type:"array",description:"Conditional branches evaluated in order. Each path can create steps, route directly to an existing targetNodeId, or do both. An else fallback is created automatically.",items:d9},elseSteps:{type:"array",description:"Optional new steps inside the else fallback path.",items:Zb},elseTargetNodeId:{type:"string",description:"Optional existing node to route the else path to. Use a node ID from get_sequence, including the completion node. If elseSteps are also provided, they run before this target."},allowEmptyPaths:{type:"boolean",description:"Set true only when intentionally creating UI placeholders. A path with targetNodeId is already explicit and does not need this flag."}},required:["afterNodeId","branches"]},insertSteps:{type:"object",description:"Insert one or more new linear steps into an existing sequence. Use get_sequence first, then pass afterNodeId to insert after a specific node. If afterNodeId is omitted, the steps are appended only when the sequence has exactly one linear tail. Inserted email steps require subject plus blocks or html.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},steps:{type:"array",description:"New steps to insert. Supports emails, delays, create_discount actions, webhooks, and other supported sequence path node types.",items:Zb}},required:["steps"]},emails:{type:"array",description:"Updated existing sequence emails. If you omit emailId/nodeId, items are matched by existing step order. This field does not create new steps; use insertSteps for insertion and include delay on inserted email steps when a timer is needed.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:`Updated HTML content for imported provider markup. ${Yw}`},htmlContent:{type:"string",description:`Alias for html for imported provider markup. ${Yw}`},emailPreset:{type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks, including emails that contain supported custom HTML blocks. Minimal removes the company logo and uses the simple footer; branded restores the branded chrome. Does not change the company default. Not supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:`${F1}${o6}`,items:{type:"object"}},isTransactional:{type:"boolean"},ccEmails:{type:"array",items:{type:"string"}},bccEmails:{type:"array",items:{type:"string"}},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time. Pass [] to remove all attachments."},...Ob}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules, and only edits existing email steps. Use insertSteps to create new steps.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:`Updated HTML content for imported provider markup. ${Yw}`},htmlContent:{type:"string",description:`Alias for html. ${Yw}`},emailPreset:{type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks, including emails that contain supported custom HTML blocks. Minimal removes the company logo and uses the simple footer; branded restores the branded chrome. Does not change the company default. Not supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:`${F1}${o6}`,items:{type:"object"}},isTransactional:{type:"boolean"},ccEmails:{type:"array",items:{type:"string"}},bccEmails:{type:"array",items:{type:"string"}},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time. Pass [] to remove all attachments."},...Ob}}},smsSteps:{type:"array",description:"Content updates for existing SMS steps, targeted by nodeId (an action_sms node from get_sequence.sequence.nodes). Content-only edits - use insertSteps to create new SMS steps.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_sms node ID. Required."},text:{type:"string",description:"Replacement plain-text message body. Merge tags like {{FIRST_NAME}} work. Provide text or blocks, not both."},blocks:{type:"array",items:{type:"object"},description:"Replacement SMS content blocks (text + image subset)."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable MMS image URLs. Only valid together with text."},label:{type:"string",description:"Updated display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"Updated behavior when the contact can't receive SMS."}},required:["nodeId"]}},subscriberUpdateSteps:{type:"array",description:"Full config replacements for existing Update Subscriber steps, targeted by action_update_attributes nodeId.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_update_attributes node ID."},config:L0},required:["nodeId","config"]}}},required:["sequenceId"]}},{name:"update_sequence_node",description:"Patch one existing sequence node in place. Call get_sequence first, select sequence.nodes[].id, inspect nodeType/config, and pass that node's updatedAt as expectedUpdatedAt. This supports every stored sequence node type, including delays, email/SMS content, actions, conditions, branches without topology changes, webhooks, and trigger settings. Delay example: changes:{ delay:{ days:7 } }. For a direct text-forward email, use changes:{ emailPreset:'minimal' } on its action_email node; this changes only that linked email's Style > Format. The update is type-aware and preserves fields you omit. It cannot change nodeType, managed linked-resource IDs, or graph topology; use edit_sequence_graph for structural work. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamp; the new delay applies when recipients reach the node in the future.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},nodeId:r6.properties.nodeId,changes:_9,expectedUpdatedAt:r6.properties.expectedUpdatedAt,confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing a node in an active sequence."}},required:["sequenceId","nodeId","changes","expectedUpdatedAt"],additionalProperties:!1}},{name:"update_sequence_nodes",description:"Atomically patch multiple existing sequence nodes. Call get_sequence first and include each node's id plus its updatedAt as expectedUpdatedAt. Every patch follows update_sequence_node's type-aware rules. Either every node update commits or none do, making this the preferred tool for changes such as replacing all 5-minute delays with 7-day delays or setting several action_email nodes to changes:{ emailPreset:'minimal' } without changing the company theme. A node may appear only once. It cannot change node types or graph topology. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamps.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},updates:{type:"array",description:"Non-empty node patches. Each nodeId may appear only once.",items:r6},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing nodes in an active sequence."}},required:["sequenceId","updates"],additionalProperties:!1}},{name:"edit_sequence_graph",description:"Restructure an existing sequence graph using node IDs, edges, and graphRevision from get_sequence. move_node repositions one non-split step; duplicate_node creates an independent copy; delete_node safely splices a node and immediately moves parked recipients to its unique surviving successor (or completes them when none remains); replace_edges replaces the complete topology. The returned sequence reports migratedRecipientCount and completedRecipientCount. Always call get_sequence immediately before this tool and pass its graphRevision. Active sequences require confirmStructuralChange:true after the user confirms live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},action:{type:"string",enum:["move_node","delete_node","duplicate_node","replace_edges"],description:"Graph operation."},graphRevision:{type:"string",description:"Exact graphRevision returned by the latest get_sequence call. The edit is rejected if the graph changed since then."},nodeId:{type:"string",description:"Existing node to move, duplicate, or delete. Unused by replace_edges."},afterNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately after this node. The target must have at most one outgoing path. Provide exactly one of afterNodeId or beforeNodeId."},beforeNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately before this node. All incoming paths converge through the moved/copied node, which is useful for placing a step below a branch. Provide exactly one of beforeNodeId or afterNodeId."},edges:{type:"array",description:"Complete replacement topology from get_sequence.sequence.edges. The returned edge array is already normalized for this input and can be reused directly. Required for replace_edges and when deleting a split node. Preserve each branch edge's condition.branchId. Do not include edges that reference a deleted node.",items:{type:"object",properties:{sourceNodeId:{type:"string"},targetNodeId:{type:"string"},condition:{type:"object",description:"Optional edge routing condition. Preserve condition.branchId on edges leaving logic_branch nodes."}},required:["sourceNodeId","targetNodeId"],additionalProperties:!1}},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."}},required:["sequenceId","action","graphRevision"],additionalProperties:!1}},{name:"insert_sequence_step",description:"Insert one dashboard-compatible typed step into an existing sequence: email, SMS, delay/date wait, discount (later emails print the generated code with {{discount.code}}), subscriber update, tag/list action, outbound webhook, condition gate, wait-for-event, or wired If/Else branch. Use get_sequence first and pass afterNodeId. Branch paths can target existing nodes, including completion. For active sequences, confirm the structural change first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},type:{type:"string",enum:["email","sms","delay","create_discount","update_subscriber","add_tag","remove_tag","add_to_list","remove_from_list","webhook","condition","logic_wait_for_event","logic_branch"],description:"Dashboard step type. Defaults to email."},afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."},name:{type:"string",description:"Optional email template and step name."},subject:{type:"string",description:"Email subject for the new step. Required for email steps; not used for SMS steps."},previewText:{type:"string",description:"Optional email preview text for the new step."},blocks:{type:"array",description:H0,items:{type:"object"}},html:{type:"string",description:`HTML content for an imported provider step. Provide either html or blocks, not both. ${Yw}`},isTransactional:{type:"boolean",description:"Email only: omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses CC'd on this step."},bccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses BCC'd in addition to sequence-level BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"Email only: URL-backed file attachments (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time."},senderProfileId:{type:"string",description:"Email steps only: sender profile for the new step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"Email steps only: From address for the new step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Email steps only: display name override for the new step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Email steps only: reply profile for the new step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Email steps only: Reply-To address for the new step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Email steps only: display name for a newly created reply profile. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},label:{type:"string",description:"Display label for SMS, wait-for-event, or branch steps."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},config:{...L0,description:"update_subscriber only: typed subscriber profile/custom-attribute changes."},tagId:{type:"string",description:"Tag ID for tag actions or tag conditions."},tagName:{type:"string",description:"Tag name for tag actions or tag conditions; missing definitions are created."},listId:{type:"string",description:"List ID for list actions or in_list conditions."},listName:{type:"string",description:"Optional cached list display name for list actions."},url:{type:"string",description:"webhook only: destination HTTPS URL called when a subscriber reaches this step. Supports merge tags like {{email}} and {{event.order_id}}."},method:{type:"string",enum:["POST","GET","PUT","PATCH","DELETE"],description:"webhook only: HTTP method. Defaults to POST."},headers:{type:"object",description:"webhook only: optional string-valued request headers. Values support merge tags. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},body:{type:"string",description:'webhook only: optional JSON body template for POST/PUT/PATCH. Must be valid JSON as written, with merge tags inside quoted string values ({"email": "{{email}}"}); a tag in a bare value position is rejected. Tags are resolved at execution time; when omitted, the default payload with subscriber and sequence context is sent.'},resultKey:{type:"string",description:"webhook only: when set, the HTTP response is saved and later email steps can reference it via {{webhooks.KEY.data.field}} merge tags. Must start with a letter; letters, numbers, underscores; max 64 chars."},onError:{type:"string",enum:["continue","exit","fail"],description:"webhook only: behavior when the request fails. continue proceeds to the next step, exit ends the sequence for the subscriber, fail marks the enrollment failed (default)."},segmentId:{type:"string",description:"Segment ID for in_segment conditions."},segmentName:{type:"string",description:"Optional cached segment display name."},conditionType:{type:"string",enum:["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"condition only: condition evaluated before continuing."},linkUrl:{type:"string"},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"]},fieldName:{type:"string"},fieldValue:{type:"string"},delay:D0,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:z0,eventName:{type:"string",description:"logic_wait_for_event only: event to wait for, for example email.replied."},timeoutDays:{type:"number",description:"logic_wait_for_event only: maximum wait in whole days from 1 to 365. Defaults to 7."},timeoutAction:{type:"string",enum:["continue","exit"],description:"logic_wait_for_event only: continue to the next node or exit the sequence when the timeout is reached. Defaults to continue."},discount:{type:"object",description:"create_discount only: provider discount configuration.",additionalProperties:!0},provider:{type:"string",enum:["stripe","shopify"]},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"},branches:{type:"array",description:"logic_branch only: ordered conditional paths. Each path may provide targetNodeId, steps, or both.",items:d9},elseSteps:{type:"array",description:"logic_branch only: optional new steps for the else path.",items:Zb},elseTargetNodeId:{type:"string",description:"logic_branch only: existing node for the else path, such as the original follow-up node or completion node."},allowEmptyPaths:{type:"boolean",description:"logic_branch only: set true only to create empty dashboard placeholders. Explicit target nodes do not require it."}},required:["sequenceId"],additionalProperties:!1}},{name:"enable_sequence",description:"Enable/activate a sequence. IMPORTANT: Only call this when the user EXPLICITLY asks to enable or activate a sequence. Never enable sequences automatically after creation - the user must review the content first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"disable_sequence",description:"Disable/freeze a sequence. This blocks new enrollments and holds current recipients until the sequence is enabled again. To only stop new enrollments while current recipients continue, use pause_sequence_enrollments.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"duplicate_sequence",description:"Create an independent draft copy of a sequence, including its graph, email templates, and sequence A/B tests. The original is not changed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to copy."},name:{type:"string",description:"Optional name for the copy. Defaults to the original name plus (Copy)."}},required:["sequenceId"]}},{name:"archive_sequence",description:"Archive a sequence and stop new enrollments. Archived sequences remain available in the dashboard's archive.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to archive."}},required:["sequenceId"]}},{name:"unarchive_sequence",description:"Restore an archived sequence as a disabled draft so it can be reviewed before activation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Archived sequence ID to restore."}},required:["sequenceId"]}},{name:"pause_sequence_enrollments",description:"Stop new enrollments for an active sequence while current recipients continue through the sequence. This matches the dashboard 'Stop new enrollments' control and does not freeze current recipients.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"resume_sequence_enrollments",description:"Resume new enrollments for an active sequence whose enrollment gate was paused. Use enable_sequence instead for a fully disabled/frozen sequence.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"enroll_subscribers_in_sequence",description:"Manually enroll subscribers in a sequence by email address or subscriber ID. Maximum 500 total targets per call across emails and subscriberIds. Only active subscribers are enrolled: unknown emails are returned in `notFound`, while inactive, unavailable, and already actively enrolled subscribers are counted in `skipped`. By default enrollment starts at the first step after the trigger; pass targetNodeId to start at a specific step.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to enroll subscribers in."},emails:{type:"array",items:{type:"string"},description:"Email addresses of subscribers to enroll. Combined with subscriberIds, maximum 500 total targets per call."},subscriberIds:{type:"array",items:{type:"string"},description:"Subscriber IDs to enroll. Combined with emails, maximum 500 total targets per call."},targetNodeId:{type:"string",description:"Optional node ID to start enrollment at. Use a non-trigger nodeId from get_sequence. Defaults to the first step after the trigger."}},required:["sequenceId"]}},{name:"cancel_sequence_enrollments",description:"Cancel active/waiting enrollments in one sequence. Provide sequenceId and exactly one target: cancelAll to drain every active/waiting enrollment (use this to fully stop a live sequence instead of only freezing enrollment), subscriberIds for a specific batch, subscriberId for one subscriber, or fieldValues to match stored entry event properties. Every bulk target defaults to dryRun, so pass dryRun false to actually cancel. Bulk cancellation is capped per call: while the response reports remainingCount above zero, call again with the same arguments until it reaches zero.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be cancelled."},cancelAll:{type:"boolean",description:"Cancel every active/waiting enrollment in the sequence, regardless of how contacts entered it. Use this when segment-triggered enrollments expose no shared entry field value. Defaults to dryRun; pass dryRun false to apply."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide exactly one target."},subscriberIds:{type:"array",items:{type:"string"},description:"Up to 500 subscriber IDs to cancel in this sequence. IDs that do not resolve come back in target.notFoundSubscriberIds. Provide exactly one target."},fieldPath:{type:"string",description:"Dot-path inside the token's stored entry event properties, such as order.id or event.id. Optional when the sequence has enrollmentFieldPath configured."},fieldValues:{type:"array",items:{type:"string"},description:"Entry field values to match. Cancels all active/waiting enrollments in the sequence whose entry field value is in this list. Provide exactly one target."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. cancelAll, subscriberIds, and fieldValues default to dryRun unless explicitly false; a single subscriberId cancels immediately."},reason:{type:"string",description:"Optional cancellation reason stored on matched enrollment tokens."}},required:["sequenceId"],additionalProperties:!1}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}}];var Ej={type:"object",properties:{email:{type:"string",description:"Subscriber email address. Optional when the record has a phone - such rows import as phone-only (SMS) contacts."},externalId:{type:"string",description:"Customer-owned subscriber ID"},firstName:{type:"string"},lastName:{type:"string"},phone:{type:"string",description:"Phone number. National-format values use the batch defaultPhoneCountry."},status:{type:"string",enum:["active","unsubscribed","bounced"]},tags:{type:"array",items:{type:"string"}},customAttributes:{type:"object",description:"CRM fields and other custom attributes. Values may be strings, numbers, booleans, arrays of those scalar values, or null.",additionalProperties:!0},createdAt:{type:"string",description:"Original signup date (ISO 8601) from the source platform. Set this when migrating so date-relative segments are correct immediately rather than treating every imported contact as having joined today. An existing contact's date only ever moves earlier."}},required:[],additionalProperties:!1},Q3=[{name:"add_subscriber",description:"Add one subscriber. Status is only applied when creating a new contact; use update_subscriber to change an existing contact's status. For multiple contacts or CRM records, use create_subscriber_import instead of looping this tool. For an email-only batch going into one list, add_subscribers_to_list is also available.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to add subscriber to. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Optional when phone is provided - a contact created with only a phone becomes a phone-only (SMS) contact."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},phone:{type:"string",description:"Phone number in E.164 or national format, stored as a native profile field. With no email, creates or matches a phone-only (SMS) contact."},phoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used to read a national-format phone number, such as IT or US. Defaults to US. Only send it together with phone; the stored country always comes from the parsed number."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for this phone number. Never inferred from phone presence."},firstName:{type:"string",description:"Subscriber first name, stored as a native profile field."},lastName:{type:"string",description:"Subscriber last name, stored as a native profile field."},attributes:{type:"object",description:"Custom attributes (plan, company, etc.). Use firstName/lastName for names instead of attributes."},tags:{type:"array",items:{type:"string"},description:"Tags to apply to the subscriber"},listIds:{type:"array",items:{type:"string"},description:"List IDs to add subscriber to"},status:{type:"string",enum:["active","unsubscribed","bounced"],description:"Initial subscriber status: active, unsubscribed, or bounced. Defaults to active and does not change an existing contact; use update_subscriber for existing contacts."},optInMode:{type:"string",enum:["default","confirmed","double_opt_in"],description:"Consent mode: confirmed creates active immediately when consent is verified, double_opt_in sends a confirmation email before activation, and default obeys company double opt-in settings."},createdAt:{type:"string",description:"Original signup date (ISO 8601) when importing a contact from another platform. Preserves their real history so date-relative segments like 'added in the last 30 days' are correct immediately instead of treating every imported contact as brand new. An existing contact's date only ever moves earlier. Supplying this also stops welcome sequences from firing, since it describes the past rather than a signup happening now."}},required:[]}},{name:"create_subscriber_import",description:"Queue one CRM-grade subscriber import with up to 5,000 full contact records. Supports names, external IDs, phones, statuses, tags, lists, and custom attributes. Prefer this over repeated add_subscriber calls. Returns an import ID for get_subscriber_import. Use optInMode='confirmed' only when the contacts already gave verified email consent.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},subscribers:{type:"array",minItems:1,maxItems:5000,items:Ej,description:"Full subscriber records to import in one batch."},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How existing contacts are handled. Defaults to skip. Merge fills missing fields; overwrite replaces public fields without reactivating unsubscribed contacts."},fileName:{type:"string",description:"Optional source label shown in import history, such as copper-export.csv."},listIds:{type:"array",items:{type:"string"},description:"Lists to add every successfully imported active subscriber to."},enrollInSequences:{type:"boolean",description:"Whether matching sequences may enroll imported contacts. Defaults to false and requires automations:trigger."},defaultPhoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used for national-format phone numbers, such as SG or US."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for every imported phone number."},optInMode:{type:"string",enum:["default","confirmed","double_opt_in"],description:"Email consent mode. Default follows workspace double opt-in settings. Confirmed creates active contacts immediately and must only be used for verified consent. Double_opt_in may send confirmation email and requires automations:trigger."}},required:["subscribers"]}},{name:"get_subscriber_import",description:"Get progress, counts, skipped reasons, and failure summaries for a queued subscriber import.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},importId:{type:"string",description:"Import ID or batch ID returned by create_subscriber_import."}},required:["importId"]}},{name:"update_subscriber",description:"Update an existing subscriber's profile, phone, status, attributes, or tags. Names and phones are native profile fields - set them here rather than as custom attributes. Setting status to unsubscribed suppresses the contact from all marketing, deactivates list memberships, and cancels active sequence enrollments while preserving the record and suppression history.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},firstName:{type:"string",description:"New first name, stored as a native profile field. Pass an empty string to clear it."},lastName:{type:"string",description:"New last name, stored as a native profile field. Pass an empty string to clear it."},phone:{type:"string",description:"New phone number in E.164 or national format, stored as a native profile field. Pass an empty string to clear it, which is rejected for a phone-only (SMS) contact that has no email. Changing the number resets SMS consent unless smsConsent is sent in the same call."},phoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used to read a national-format phone number, such as IT or US. Defaults to US. Only send it together with phone; the stored country always comes from the parsed number."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for this phone number; false unsubscribes them from SMS. Omitting this leaves consent unchanged unless phone changes, which resets consent because it belonged to the old number. Consent is never inferred from phone presence."},status:{type:"string",enum:["active","unsubscribed","bounced"],description:"New global subscriber status. Use unsubscribed for compliance-grade suppression without deleting the record. Use active only when the contact has valid consent to be resubscribed."},attributes:{type:"object",description:"Custom attributes to update. Use firstName/lastName for names instead of attributes."},addTags:{type:"array",items:{type:"string"},description:"Tags to add"},removeTags:{type:"array",items:{type:"string"},description:"Tags to remove"}},required:[]}},{name:"remove_subscriber",description:"Unsubscribe a subscriber while preserving the record and suppression history. Only permanently deletes when hardDelete is true.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},hardDelete:{type:"boolean",description:"If true, permanently deletes the subscriber and suppression history. Defaults to false, which globally unsubscribes the contact, deactivates list memberships, and cancels active sequence enrollments."}},required:[]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, notes, list memberships, sequence enrollments, email stats, and recent activity. For commerce customers, customAttributes include nightly predictive analytics: predictedLtv (next-12-month spend), churnRisk (percent), expectedNextOrderAt, avgDaysBetweenOrders, and predictionConfidence.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:uw},required:[]}},{name:"list_subscriber_notes",description:"List internal notes for a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"add_subscriber_note",description:"Add an internal note to a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},body:{type:"string",description:"Internal note body, up to 5000 characters."}},required:["body"]}},{name:"delete_subscriber_note",description:"Delete one internal subscriber note by note ID.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},noteId:{type:"string",description:"Subscriber note ID to delete."}},required:["noteId"]}},{name:"trigger_subscriber_event",description:"Emit a custom event for one subscriber, exactly as an integration or the public API would. This is the supported way to exercise event triggers, matching-field idempotency, branch conditions, and stop conditions end to end without waiting for real traffic. The event is recorded, sync rules apply, and matching event_received sequences enroll. Creates the subscriber if they do not exist. Use trigger_subscriber_events for several events on the same contact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},event:{type:"string",description:"Event name, such as saas.purchase or invoice.paid. The event definition is created if it does not exist."},properties:{type:"object",description:"Event properties. Include the sequence's matching field (for example order.id or invoice.id) when testing idempotency or cancellation by field value.",additionalProperties:!0},firstName:{type:"string",description:"First name applied to the subscriber profile."},lastName:{type:"string",description:"Last name applied to the subscriber profile."},attributes:{type:"object",description:"Custom attributes to set on the subscriber.",additionalProperties:!0},occurredAt:{type:"string",description:"When the event actually happened (ISO 8601). Omit for live events. If this is more than an hour in the past the event is recorded as history: it is stored with its real timestamp and counts for segments and the timeline, but no sequences enroll, no sync rules apply, no waiting steps resume, and no webhooks fire. A historical event also moves the contact's signup date back to when it occurred (never later), so imported contacts do not read as added today. Use this when backfilling from another platform - never to fake a live event, since the side effects you are testing will not run."},eventId:{type:"string",description:"Your own id for this event. Makes a historical import idempotent: re-sending the same eventId writes nothing new."}},required:["event"]}},{name:"trigger_subscriber_events",description:"Emit several custom events for one subscriber in order. Events are processed independently and sequentially, so a partial failure can still leave earlier events recorded.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},events:{type:"array",minItems:1,maxItems:500,items:{type:"object",properties:{name:{type:"string",description:"Event name"},properties:{type:"object",description:"Event properties",additionalProperties:!0},occurredAt:{type:"string",description:"When the event actually happened (ISO 8601). When every event in the batch is more than an hour old the batch is imported as history in one idempotent write, with no sequences, sync rules, waiting steps or webhooks; the contact's signup date also moves back to the earliest event in the batch (never later)."},eventId:{type:"string",description:"Your own id for this event, making a re-run idempotent."}},required:["name"],additionalProperties:!1},description:"Events to trigger, in order, for this subscriber."},firstName:{type:"string"},lastName:{type:"string"},attributes:{type:"object",description:"Custom attributes to set on the subscriber.",additionalProperties:!0}},required:["events"]}},{name:"bulk_add_subscriber_tags",description:"Add tags to up to 500 existing subscribers in one call, identified by emails, externalIds, or subscriberIds. Built for reconciling historical or derived tags: subscribers that do not exist are reported in notFound instead of being created, and tag automations do NOT run unless triggerAutomations is true. Needs the subscribers:tag scope, which the agent_safe key preset includes; a tag name that does not exist yet also needs tags:write. Use add_subscriber or update_subscriber for single-contact changes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tags:{type:"array",minItems:1,items:{type:"string"},description:"Tag names to add to every matched subscriber."},emails:{type:"array",items:{type:"string"},description:"Subscriber emails to tag. Combine with externalIds/subscriberIds as needed; at least one identifier list is required."},externalIds:{type:"array",items:{type:"string"},description:"Customer-owned subscriber IDs to tag."},subscriberIds:{type:"array",items:{type:"string"},description:"Sequenzy subscriber IDs to tag."},triggerAutomations:{type:"boolean",description:"Whether tag_added sequences may enroll these contacts. Defaults to false, which is what backfills want. Requires the automations:trigger scope."}},required:["tags"]}},{name:"bulk_remove_subscriber_tags",description:"Remove tags from up to 500 existing subscribers in one call, identified by emails, externalIds, or subscriberIds. Subscribers that do not exist are reported in notFound. Needs the subscribers:tag scope; the broader subscribers:write scope also satisfies it. Use this to roll back or reconcile a derived-tag backfill.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tags:{type:"array",minItems:1,items:{type:"string"},description:"Tag names to remove from every matched subscriber."},emails:{type:"array",items:{type:"string"},description:"Subscriber emails to untag."},externalIds:{type:"array",items:{type:"string"},description:"Customer-owned subscriber IDs to untag."},subscriberIds:{type:"array",items:{type:"string"},description:"Sequenzy subscriber IDs to untag."}},required:["tags"]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, list, or segment. If you omit limit, the tool fetches all pages and returns every match.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query (email or name)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},list:{type:"string",description:"Filter by subscriber list ID or exact list name. Prefer listId when known."},listId:{type:"string",description:"Filter by subscriber list ID."},listName:{type:"string",description:"Filter by exact subscriber list name when the list ID is not known."},segmentId:{type:"string",description:"Filter by segment ID"},status:{type:"string",description:"Filter by subscriber status: active, unsubscribed, or bounced."},limit:{type:"number",description:"Maximum results to return. If omitted, the tool returns all matches across pages."}}}}];var X3={companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Exact recipient email address to inspect or clean up."},region:{type:"string",description:"Optional AWS SES region such as us-east-1. Omit to check every SES region currently used by the company."}},G3=[{name:"get_recipient_suppression",description:"Check whether one recipient is suppressed by Sequenzy's bounce/complaint safeguards or the regional Amazon SES account-level suppression list. This exact-address lookup never exposes other recipients from the shared SES account.",inputSchema:{type:"object",properties:X3,required:["email"],additionalProperties:!1}},{name:"remove_recipient_suppression",description:"Remove stale bounce suppression for an exact recipient associated with the company. Clears matching Amazon SES bounce entries and Sequenzy's local bounce block, then reactivates bounced company subscribers. Complaint and unsubscribe protections are never removed.",inputSchema:{type:"object",properties:X3,required:["email"],additionalProperties:!1}}];var J3=[{name:"list_tags",description:"List all tags in the account",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list tags for. If not provided, uses the currently selected company."}}}},{name:"create_tag",description:"Create a new tag definition. The name is normalized to lowercase with hyphens (e.g. 'VIP Customer' becomes 'vip-customer'). Color defaults to gray.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Tag name. Normalized to lowercase with hyphens."},color:{type:"string",enum:[...B0],description:"Tag color. Defaults to gray."}},required:["name"]}},{name:"update_tag",description:"Update a tag's color. System tags cannot be updated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."},color:{type:"string",enum:[...B0],description:"New tag color."}},required:["tagId","color"]}},{name:"delete_tag",description:"Permanently delete a tag and remove it from all subscribers. This cannot be undone. System tags and tags used by sequences cannot be deleted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."}},required:["tagId"]}},{name:"list_lists",description:"List all subscriber lists",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list lists for. If not provided, uses the currently selected company."}}}},{name:"create_list",description:"Create a new subscriber list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the list in. If not provided, uses the currently selected company."},name:{type:"string",description:"List name"},description:{type:"string",description:"List description"}},required:["name"]}},{name:"update_list",description:"Update a subscriber list's name, description, or privacy. Only the provided fields are changed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to update."},name:{type:"string",description:"New list name."},description:{type:["string","null"],description:"New list description. Pass null to clear it."},isPrivate:{type:"boolean",description:"Whether the list is private."}},required:["listId"]}},{name:"delete_list",description:"Permanently delete a subscriber list and remove all of its memberships. Subscribers themselves are kept. This cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to delete."}},required:["listId"]}},{name:"add_subscribers_to_list",description:"Bulk add existing or new subscribers to a subscriber list from an email array. Existing subscribers are added to the list without requiring a per-subscriber update call.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to add subscribers to."},emails:{type:"array",items:{type:"string"},description:"Email addresses to add to the list. Maximum 500 per call."},duplicateStrategy:{type:"string",description:"Duplicate strategy for existing subscribers: skip, merge, or overwrite. Defaults to skip."},enrollInSequences:{type:"boolean",description:"Whether newly created subscribers should enroll in matching sequences. Defaults to false."},optInMode:{type:"string",description:"Consent mode for newly created subscribers: default, confirmed, or double_opt_in. Defaults to default."}},required:["listId","emails"]}},{name:"remove_subscribers_from_list",description:"Remove subscribers from a list by email address. Maximum 500 emails per call. Subscribers stay in the account; only the list membership is removed. Returns the removed count plus a notFound array of emails that did not match a subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to remove subscribers from."},emails:{type:"array",items:{type:"string"},description:"Email addresses to remove from the list. Maximum 500 per call."}},required:["listId","emails"]}},{name:"list_segments",description:"List all segments",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list segments for. If not provided, uses the currently selected company."}}}},{name:"create_segment",description:'Create a new segment from explicit filter rules. Use `filters` plus `filterJoinOperator` for flat legacy rules, or `root` for nested AND/OR groups such as `{ "kind": "group", "joinOperator": "and", "children": [{ "kind": "filter", "field": "attribute", "operator": "gte", "value": "mrr:50" }, { "kind": "group", "joinOperator": "or", "children": [{ "kind": "filter", "field": "tag", "operator": "contains", "value": "vip" }, { "kind": "filter", "field": "event", "operator": "is_not", "value": "saas.purchase:30d" }] }] }`. Supports `event` and `segment` fields, Stripe product purchase/current/trial/date filters, and campaign-specific engagement filters.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the segment in. If not provided, uses the currently selected company."},name:{type:"string",description:"Segment name"},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:h9,minItems:1,description:'Array of segment filters. Example custom attribute empty check: [{"id":"filter-1","field":"attribute","operator":"is_empty","value":"last_logged_in:"}]. Example Stripe purchase filter: [{"id":"filter-1","field":"stripeProduct","operator":"is","value":"prod_123"}]. Example threshold filter: [{"id":"filter-1","field":"stripeProduct","operator":"at_least","value":"prod_123:3"}]. Example commerce product purchase filter (value is provider:productId since product ids are provider-scoped): [{"id":"filter-1","field":"commerceProduct","operator":"is","value":"api:prod-starter-kit"}]. Example repeat-buyer filter: [{"id":"filter-1","field":"commerceProduct","operator":"at_least","value":"shopify:42:2"}]. Example commerce collection filter (anyone who bought any product in the collection; value is a collection id or handle): [{"id":"filter-1","field":"commerceCollection","operator":"is","value":"skincare"}]. Example trial cancellation filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:is_canceled"}]. Example trial end filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:end_at:2026-05-26"}]. Example campaign-specific engagement combo: [{"id":"filter-1","field":"emailBounced","operator":"is","value":"campaign:cmp_abc"},{"id":"filter-2","field":"emailBounced","operator":"is_not","value":"campaign:cmp_xyz"}]. Combine them with `filterJoinOperator: "or"` to match any filter.'},root:{...y9,description:"Nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["name"]}},{name:"update_segment",description:"Update a segment's name and/or filter rules. Use the same `filters` plus `filterJoinOperator` or nested `root` shapes as create_segment; providing `filters` or `root` replaces the segment's existing rules.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to update."},name:{type:"string",description:"New segment name."},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:h9,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...y9,description:"Replacement nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["segmentId"]}},{name:"delete_segment",description:"Permanently delete a segment. This cannot be undone. Subscribers are not affected.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to delete."}},required:["segmentId"]}},{name:"get_segment_count",description:"Get the number of subscribers in a segment",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID"}},required:["segmentId"]}}];var Y3=[{name:"list_team_members",description:"List team members for the company, including the owner, members with their roles, and pending or expired invitations.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"invite_team_member",description:"Invite a team member by email with role admin, viewer, or restricted. Existing Sequenzy users are added to the team immediately; others receive an email invitation. Billing access (canManageBilling) can only be granted by the company owner and is not available for restricted members.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Email address of the person to invite."},role:{type:"string",enum:["admin","viewer","restricted"],description:"Team role. Admins can manage the workspace; viewers have read-only access; restricted members can open direct campaign links only."},canManageBilling:{type:"boolean",description:"Whether the member can manage billing. Only the company owner can grant billing access. Defaults to false."}},required:["email","role"]}},{name:"cancel_team_invitation",description:"Cancel a pending team invitation. Invitations that have already been accepted cannot be cancelled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},invitationId:{type:"string",description:"Invitation ID to cancel. Use list_team_members to find pending invitations."}},required:["invitationId"]}}];var H3=[{name:"list_templates",description:"List the company's 50 most recently created email bodies, including per-locale localization sync status. Results include standalone templates plus recent bodies behind campaigns and transactional emails. To retrieve a specific campaign body even when it is not among these 50 results, pass the campaign's emailId to get_template. Bodies are kept when their campaign or transactional email is deleted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"create_template",description:"Create a new email template. For net-new email content requested in natural language, use `prompt`; do not write HTML or construct blocks yourself. Use `blocks` only for finished caller-supplied Sequenzy content and `html` only for supplied or explicitly requested preserved HTML.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line. Optional with `prompt`."},previewText:{type:["string","null"],description:"Optional preview text override."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider templates. ${Yw}`},blocks:{type:"array",description:A1,items:{type:"object"}},prompt:{type:"string",description:"Natural-language request for Sequenzy to generate branded native template blocks."},style:{type:"string",description:"Generation style; valid only with `prompt`."},tone:{type:"string",description:"Generation tone; valid only with `prompt`."},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `previewText`, `html`, `blocks`, or `labels` is required, and only those update fields are accepted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},previewText:{type:["string","null"],description:"Inbox preview text. Send null to clear the existing preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider templates. ${Yw}`},blocks:{type:"array",description:A1,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"set_template_localization",description:"Create or replace one caller-supplied localized variant of a template. The locale must be enabled for the company and cannot be its primary locale. Provide exactly one of `html` or `blocks`.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locale:{type:"string",description:"Enabled non-primary locale code such as es, fr, or pt-BR."},subject:{type:"string",description:"Localized email subject line."},previewText:{type:["string","null"],description:"Optional localized inbox preview text."},html:{type:"string",description:`Localized email HTML. Mutually exclusive with \`blocks\`. ${Yw}`},blocks:{type:"array",description:A1,items:{type:"object"}}},required:["templateId","locale","subject"],additionalProperties:!1}},{name:"sync_template_localizations",description:"Queue AI translation for selected template locales. Omit `locales` to sync every enabled non-primary locale. This works even when automatic on-save localization is disabled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locales:{type:"array",description:"Optional enabled non-primary locale codes to sync. Omit to sync all enabled non-primary locales.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}}];var z3=[{name:"list_transactional_emails",description:"List transactional email templates with subjects, delivery metrics, API slugs, and dashboard URLs. Search by name, slug, or email title; filter active state; and sort by sends, opens, open rate, clicks, or CTR.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},search:{type:"string",description:"Case-insensitive search across template name, API slug, and linked email subject/title."},status:{type:"string",description:"Template status: all, active, or disabled."},sort:{type:"string",description:"Sort field: date, sends, opens, open-rate, clicks, or ctr. Defaults to date."},order:{type:"string",description:"Sort order: asc or desc. Defaults to desc."},includeMachineEngagement:{type:"boolean",description:"Include bot, scanner, and privacy-proxy engagement in open and click metrics. Defaults to false."}},additionalProperties:!1}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"]}},{name:"create_transactional_email",description:"Create a saved transactional email template with an API slug. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Transactional email name."},slug:{type:"string",description:"Optional API slug used when sending by slug, for example `password-reset`. If omitted, Sequenzy generates one from the name."},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. ${Yw}`},blocks:{type:"array",description:`${A1} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Generated blocks include the company's branding (logo and a footer without an unsubscribe link). Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Prompt-created templates default to false; explicit HTML/blocks retain the compatibility default of true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. ${Yw}`},blocks:{type:"array",description:`${F1} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"delete_transactional_email",description:"Permanently delete a saved transactional email template by ID or slug. Use this to retire an obsolete template: the slug stops sending and becomes free to reuse. Already-sent deliveries and their stats are kept, so history and analytics survive the delete. The linked email content stays as a reusable template and comes back as `deleted.emailId`; pass that to `delete_template` to remove the content too. To stop sends without losing the template, call `update_transactional_email` with `enabled` set to false instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Queue one email using either a saved transactional email API slug (`templateId`) or direct `subject` and `html` content. The default delivery policy is transactional. When the recipient matches a subscriber, saved first and last names fill omitted name variables; explicit variables take precedence. Set `emailType` to `marketing` to add subscriber suppression, a marketing footer, and RFC 8058 one-click unsubscribe. Company Reply-To defaults are inherited when no override is provided, and `{{viewInBrowserUrl}}` is replaced with a hosted copy URL. Use `trackingSettings` with `clickTracking` or `openTracking` set to `false` to disable click-link rewriting or the open-tracking pixel for this send only; these opt-out fields cannot enable tracking the account has disabled. Returns a durable emailSendId and the accepted emailType; pass the ID to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line. Required with `html` when `templateId` is omitted."},html:{type:"string",description:"Direct-send HTML body. Required with `subject` when `templateId` is omitted; the MCP server maps this to the transactional API `body` field. Use `{{viewInBrowserUrl}}` for a hosted copy link generated at send time."},templateId:{type:"string",description:"Saved transactional email API slug, for example `welcome-email`. The field name is retained for MCP compatibility and is mapped to the transactional API `slug` field."},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }. When the recipient matches a subscriber, saved first and last names fill omitted name variables; explicit values, including blanks, take precedence. Variables are HTML-escaped; a template can prefix a tag with 'html.' ({{html.prerenderedHtml}}) to insert a trusted, sanitized HTML value unescaped."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics, localization, and saved-name personalization on single-recipient sends. Maximum length: 255 characters."},emailType:{type:"string",description:"Delivery policy: `transactional` (default) or `marketing`. Marketing mode supports exactly one recipient and automatically applies subscriber suppression, the standard unsubscribe footer, and RFC 8058 headers."},replyTo:{type:"string",description:"Optional Reply-To address, formatted as `email@example.com` or `Name <email@example.com>`. When omitted, the saved template or company default is used."},trackingSettings:{type:"object",description:"Per-send tracking opt-outs. Each field defaults to `true`, meaning the account tracking settings apply; set a field to `false` to disable that tracking for this send only. These fields cannot enable tracking the account has disabled.",properties:{clickTracking:{type:"boolean",description:"Set to `false` to skip click-link rewriting for this send only, which helps when tracking redirects break universal or deep links."},openTracking:{type:"boolean",description:"Set to `false` to skip the open-tracking pixel for this send only."}},additionalProperties:!1}},required:["to"],additionalProperties:!1}}];var D3=[{name:"list_webhooks",description:"List outbound webhook endpoints and their subscribed event types.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_webhook",description:"Create an outbound webhook endpoint. IMPORTANT: the response includes a signingSecret that is returned only once - show it to the user immediately so they can store it and verify webhook signatures. If events is omitted, a default set of event types is subscribed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Webhook endpoint name."},url:{type:"string",description:"HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...A0]},description:"Event types to subscribe to. If omitted, a default set is used."}},required:["name","url"]}},{name:"update_webhook",description:"Update an outbound webhook endpoint's name, URL, subscribed events, or status (enabled/disabled). Providing events replaces the existing event list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},name:{type:"string",description:"New webhook endpoint name."},url:{type:"string",description:"New HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...A0]},description:"Replacement event type subscriptions."},status:{type:"string",enum:["enabled","disabled"],description:"Enable or disable deliveries to this endpoint."}},required:["webhookId"]}},{name:"delete_webhook",description:"Permanently delete an outbound webhook endpoint along with its delivery history. This cannot be undone. To keep the endpoint but stop deliveries, use update_webhook with status disabled instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to delete."}},required:["webhookId"]}},{name:"test_webhook",description:"Send a test event to an outbound webhook endpoint to verify it is reachable and signatures can be validated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to test."}},required:["webhookId"]}},{name:"list_webhook_deliveries",description:"List recent delivery attempts for an outbound webhook endpoint, including status and response codes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},limit:{type:"number",description:"Maximum number of deliveries to return, from 1 to 100. Defaults to 20."}},required:["webhookId"]}},{name:"replay_webhook_delivery",description:"Replay a previous webhook delivery, re-sending the same event payload to the endpoint.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},deliveryId:{type:"string",description:"Delivery ID to replay. Use list_webhook_deliveries to find delivery IDs."}},required:["webhookId","deliveryId"]}}];var B3=[...c5,...t5,...Q3,...G3,...s5,...J3,...g5,...H3,...f5,...i5,...e5,...p5,...r5,...d5,...$3,...W3,...w3,...b3,...z3,...l5,...Y3,...o5,...D3,...m5,...n5];async function A3(w,b){let $;switch(w){case"get_account":{let W=await D("GET","/api/v1/account"),Q=K1();$={...W,selectedCompanyId:Q??W.currentCompanyId};break}case"select_company":{let W=b.companyId,Q=await D("GET","/api/v1/account"),X=Q.companies?.find((G)=>G.id===W);if(!X)throw Error(`Company not found. Available companies: ${Q.companies?.map((G)=>`${G.name} (${G.id})`).join(", ")??"none"}`);Ib(W),$={success:!0,message:`Switched to company: ${X.name}`,companyId:X.id,companyName:X.name};break}case"get_app_urls":{let W=await Q4(b);$={...B1({companyId:W,campaignId:L(b,"campaignId"),landingPageId:L(b,"landingPageId"),sequenceId:L(b,"sequenceId"),emailId:L(b,"emailId")??L(b,"templateId"),transactionalId:L(b,"transactionalId"),emailSendId:L(b,"emailSendId"),domainId:L(b,"domainId"),status:L(b,"status"),settingsTab:L(b,"settingsTab")}),...W===void 0&&{note:"No company ID is selected. Call get_account, select_company, or pass companyId to get concrete dashboard URLs."}};break}case"create_company":{let W=await D("POST","/api/v1/companies",{name:b.name,domain:b.domain});if(!W.success)throw Error("Failed to create company");let Q=W.company.id,X=6,G=0,J=W.company.status;while(J==="processing"&&G<X){await new Promise((z)=>setTimeout(z,20000)),G++;let H=await D("GET",`/api/v1/companies/${Q}`);if(H.success)J=H.company.status}Ib(Q);let Y=await D("GET",`/api/v1/companies/${Q}`);$={success:!0,company:Y.company,message:J==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${Y.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let W=b.companyId;$=await D("GET",`/api/v1/companies/${W}`);break}case"update_company":{let W=await jb("update_company",b),Q=Q5(b);$=await D("PATCH",`/api/v1/companies/${W}`,Q);break}case"get_sync_rules":{let W=b.companyId;$=await D("GET","/api/v1/sync-rules",void 0,W);break}case"update_sync_rules":{let W=b.companyId;if(b.syncRules!==null&&!Array.isArray(b.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");$=await D("PUT","/api/v1/sync-rules",{syncRules:b.syncRules},W);break}case"get_shopify_automation_settings":{let W=b.companyId;$=await D("GET","/api/v1/shopify/automation-settings",void 0,W);break}case"update_shopify_automation_settings":{let W=b.companyId,Q={};if(b.browseAbandonment!==void 0)Q.browseAbandonment=b.browseAbandonment;if(b.cartAbandonment!==void 0)Q.cartAbandonment=b.cartAbandonment;if(b.priceDrop!==void 0)Q.priceDrop=b.priceDrop;if(Object.keys(Q).length===0)throw Error("Provide `browseAbandonment`, `cartAbandonment`, and/or `priceDrop` when calling `update_shopify_automation_settings`.");$=await D("PUT","/api/v1/shopify/automation-settings",Q,W);break}case"create_api_key":{let W=b.companyId,Q={};if(typeof b.name==="string")Q.name=b.name;if(typeof b.preset==="string")Q.preset=b.preset;if(Array.isArray(b.scopes))Q.scopes=b.scopes;$=await D("POST","/api/v1/api-keys",Q,W);break}case"list_api_keys":{let W=await jb(w,b);$=await D("GET","/api/v1/api-keys",void 0,W);break}case"update_api_key":{let W=await jb(w,b),Q={};if(typeof b.name==="string")Q.name=b.name;if(typeof b.preset==="string")Q.preset=b.preset;if(Array.isArray(b.scopes))Q.scopes=b.scopes;if(Object.keys(Q).length===0)throw Error("Provide at least one of `name`, `preset`, or `scopes` when calling `update_api_key`.");$=await D("PATCH",`/api/v1/api-keys/${encodeURIComponent(String(b.apiKeyId))}`,Q,W);break}case"revoke_api_key":case"delete_api_key":{let W=await jb(w,b);$=await D("DELETE",`/api/v1/api-keys/${encodeURIComponent(String(b.apiKeyId))}`,void 0,W);break}case"list_websites":{let W=b.companyId;$=await D("GET","/api/v1/websites",void 0,W);break}case"add_sending_domain":case"add_website":{let W=b.companyId;$=await D("POST","/api/v1/websites",{domain:b.domain},W);break}case"check_website":{let W=b.companyId;$=await D("GET",`/api/v1/websites/${encodeURIComponent(String(b.domain))}`,void 0,W);break}case"verify_sending_domain":{let W=b.companyId;$=await D("POST",`/api/v1/websites/${encodeURIComponent(String(b.domain))}/verify`,void 0,W);break}case"list_integrations":{let W=b.companyId,Q=new URLSearchParams;if(b.includeInactive===!0)Q.set("includeInactive","true");let X=Q.toString();$=await D("GET",`/api/v1/integrations${X?`?${X}`:""}`,void 0,W);break}case"list_sender_profiles":{let W=b.companyId;$=await D("GET","/api/v1/sender-profiles",void 0,W);break}case"update_sender_profile":{let{companyId:W,profileId:Q}=b,X=b.type==="reply"?`/api/v1/reply-profiles/${encodeURIComponent(Q)}`:`/api/v1/sender-profiles/${encodeURIComponent(Q)}`;$=await D("PATCH",X,{name:b.name},W);break}case"get_tracking_settings":{let W=b.companyId;$=await D("GET","/api/v1/tracking-settings",void 0,W);break}case"update_tracking_settings":{let W=b.companyId,Q=X5(b);$=await D("PATCH","/api/v1/tracking-settings",Q,W);break}case"get_notification_preferences":{let W=b.companyId;$=await D("GET","/api/v1/notification-preferences",void 0,W);break}case"update_notification_preferences":{let W=b.companyId;$=await D("PATCH","/api/v1/notification-preferences",{notificationPreferences:b.notificationPreferences},W);break}case"get_integration_guide":$=await D("POST","/api/v1/integration-guide",b);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function F3(w,b){let $;switch(w){case"generate_email":{let W=b.companyId;$=await D("POST","/api/v1/generate/email",b,W);break}case"generate_subject_lines":{let W=b.companyId;$=await D("POST","/api/v1/generate/subjects",b,W);break}case"generate_sms":{let W=b.companyId;$=await D("POST","/api/v1/generate/sms",b,W);break}case"get_sms_settings":{let W=b.companyId;$=await D("GET","/api/v1/sms/settings",void 0,W);break}case"send_test_sms":{let W=b.companyId,Q={to:Z("send_test_sms",b,"to")};for(let X of["text","imageUrls","blocks"])if(b[X]!==void 0)Q[X]=b[X];$=await D("POST","/api/v1/sms/test",Q,W);break}case"submit_feedback":{let W=b.companyId,Q={message:Z("submit_feedback",b,"message"),source:"mcp"};for(let X of["category","context"])if(b[X]!==void 0)Q[X]=b[X];$=await D("POST","/api/v1/feedback",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function L3(w,b){let $;switch(w){case"list_transactional_emails":{let W=b.companyId,Q=new URLSearchParams,X=L(b,"search"),G=n("list_transactional_emails",b,"status",["all","active","disabled"]),J=n("list_transactional_emails",b,"sort",["date","sends","opens","open-rate","clicks","ctr"]),Y=n("list_transactional_emails",b,"order",["asc","desc"]);if(X)Q.set("search",X);if(G)Q.set("status",G);if(J)Q.set("sort",J);if(Y)Q.set("order",Y);if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let H=Q.toString();$=await D("GET",`/api/v1/transactional${H?`?${H}`:""}`,void 0,W);break}case"get_transactional_email":{let W=b.companyId;$=await D("GET",`/api/v1/transactional/${b.idOrSlug}`,void 0,W);break}case"create_transactional_email":{let W=b.companyId,Q=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),X=Object.keys(b).filter((J)=>!Q.has(J));if(X.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);V5(b);let G=Object.fromEntries(Object.entries(b).filter(([J])=>J!=="companyId"));$=await D("POST","/api/v1/transactional",G,W);break}case"update_transactional_email":{let W=b.companyId,Q=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),X=Object.keys(b).filter((J)=>!Q.has(J));if(X.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);if(Cw("update_transactional_email",b),b.name===void 0&&b.enabled===void 0&&b.subject===void 0&&b.previewText===void 0&&b.html===void 0&&b.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let G=Object.fromEntries(Object.entries(b).filter(([J])=>J!=="companyId"&&J!=="idOrSlug"));$=await D("PATCH",`/api/v1/transactional/${b.idOrSlug}`,G,W);break}case"delete_transactional_email":{let W=b.companyId,Q=Z("delete_transactional_email",b,"idOrSlug");$=await D("DELETE",`/api/v1/transactional/${encodeURIComponent(Q)}`,void 0,W);break}case"send_email":{let W=b.companyId,Q=Z("send_email",b,"to"),X=b.templateId===void 0?void 0:Z("send_email",b,"templateId"),G=b.subject===void 0?void 0:Z("send_email",b,"subject"),J=b.html===void 0?void 0:Z("send_email",b,"html"),Y=b.emailType===void 0?void 0:Z("send_email",b,"emailType"),H=b.replyTo===void 0?void 0:Z("send_email",b,"replyTo");if(Y!==void 0&&Y!=="marketing"&&Y!=="transactional")throw Error("`emailType` must be `marketing` or `transactional` when calling `send_email`.");if(X!==void 0&&(G!==void 0||J!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(X===void 0&&(G===void 0||J===void 0))throw Error("Provide either `templateId` or both `subject` and `html` when calling `send_email`.");let z;if(b.trackingSettings!==void 0){if(typeof b.trackingSettings!=="object"||b.trackingSettings===null||Array.isArray(b.trackingSettings))throw Error("`trackingSettings` must be an object with optional boolean `clickTracking` and `openTracking` fields when calling `send_email`.");let A=b.trackingSettings;z={};for(let F of["clickTracking","openTracking"]){let U=A[F];if(U===void 0)continue;if(typeof U!=="boolean")throw Error(`\`trackingSettings.${F}\` must be a boolean when calling \`send_email\`.`);z[F]=U}}let B=Object.fromEntries(Object.entries({to:Q,slug:X,subject:G,body:J,variables:b.variables,subscriberExternalId:b.subscriberExternalId,emailType:Y,replyTo:H,trackingSettings:z}).filter(([,A])=>A!==void 0));$=await D("POST","/api/v1/transactional/send",B,W);break}case"get_stats":{let W=b.companyId,Q=b.period??"7d",X=new URLSearchParams({period:String(Q)}),G=b.emailType===void 0?void 0:Z("get_stats",b,"emailType");if(G!==void 0&&!["campaign","transactional","sequence"].includes(G))throw Error("`emailType` must be `campaign`, `transactional`, or `sequence` when calling `get_stats`.");if(G)X.set("emailType",G);if(b.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");$=await D("GET",`/api/v1/metrics?${X.toString()}`,void 0,W);break}case"get_campaign_stats":{let W=b.companyId,Q=new URLSearchParams;if(typeof b.period==="string")Q.set("period",b.period);if(typeof b.start==="string")Q.set("start",b.start);if(typeof b.end==="string")Q.set("end",b.end);if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let X=Q.toString();$=await D("GET",`/api/v1/metrics/campaigns/${b.campaignId}${X?`?${X}`:""}`,void 0,W);break}case"get_transactional_stats":{let W=b.companyId,Q=Z("get_transactional_stats",b,"idOrSlug"),X=new URLSearchParams;for(let J of["period","start","end"])if(typeof b[J]==="string"&&b[J].trim())X.set(J,b[J].trim());if(b.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");let G=X.toString();$=await D("GET",`/api/v1/metrics/transactional/${encodeURIComponent(Q)}${G?`?${G}`:""}`,void 0,W);break}case"get_sequence_stats":{let W=b.companyId,Q=new URLSearchParams;for(let G of["period","start","end"])if(typeof b[G]==="string"&&b[G].trim())Q.set(G,b[G].trim());if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let X=Q.toString();$=await D("GET",`/api/v1/metrics/sequences/${b.sequenceId}${X?`?${X}`:""}`,void 0,W);break}case"list_campaign_events":{let W=b.companyId,Q=Z("list_campaign_events",b,"campaignId"),G=s9("list_campaign_events",b).toString();$=await D("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(Q)}/events${G?`?${G}`:""}`,void 0,W);break}case"list_sequence_events":{let W=b.companyId,Q=Z("list_sequence_events",b,"sequenceId"),G=s9("list_sequence_events",b).toString();$=await D("GET",`/api/v1/metrics/sequences/${encodeURIComponent(Q)}/events${G?`?${G}`:""}`,void 0,W);break}case"get_subscriber_activity":{let W=b.companyId,Q=ow("get_subscriber_activity",b),X=await Mb(Q,W,{includeMachineEngagement:b.includeMachineEngagement===!0});$={success:X.success,email:X.subscriber.email,emailStats:X.subscriber.emailStats??null,activity:X.subscriber.activity??[],sequenceEnrollments:X.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function U3(w,b){let $;switch(w){case"list_tags":{let W=b.companyId;$=await D("GET","/api/v1/tags",void 0,W);break}case"create_tag":{let W=b.companyId,Q=Z("create_tag",b,"name"),X=n("create_tag",b,"color",B0);$=await D("POST","/api/v1/tags",{name:Q,...X!==void 0&&{color:X}},W);break}case"update_tag":{let W=b.companyId,Q=Z("update_tag",b,"tagId"),X=Vb("update_tag",b,"color",B0);$=await D("PATCH",`/api/v1/tags/${encodeURIComponent(Q)}`,{color:X},W);break}case"delete_tag":{let W=b.companyId,Q=Z("delete_tag",b,"tagId");$=await D("DELETE",`/api/v1/tags/${encodeURIComponent(Q)}`,void 0,W);break}case"list_lists":{let W=b.companyId;$=await D("GET","/api/v1/lists",void 0,W);break}case"create_list":{let W=b.companyId;$=await D("POST","/api/v1/lists",b,W);break}case"update_list":{let W=b.companyId,Q=Z("update_list",b,"listId");if(b.name===void 0&&b.description===void 0&&b.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(b.name!==void 0&&L(b,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(b.description!==void 0&&b.description!==null&&typeof b.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(b.isPrivate!==void 0&&typeof b.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");$=await D("PATCH",`/api/v1/lists/${encodeURIComponent(Q)}`,{...b.name!==void 0&&{name:L(b,"name")},...b.description!==void 0&&{description:b.description},...b.isPrivate!==void 0&&{isPrivate:b.isPrivate}},W);break}case"delete_list":{let W=b.companyId,Q=Z("delete_list",b,"listId");$=await D("DELETE",`/api/v1/lists/${encodeURIComponent(Q)}`,void 0,W);break}case"add_subscribers_to_list":{let W=b.companyId,Q=Z("add_subscribers_to_list",b,"listId"),X=a9("add_subscribers_to_list",b),G=n("add_subscribers_to_list",b,"duplicateStrategy",["skip","merge","overwrite"])??"skip",J=n("add_subscribers_to_list",b,"optInMode",["default","confirmed","double_opt_in"])??"default";$=await D("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers`,{emails:X,duplicateStrategy:G,enrollInSequences:b.enrollInSequences===!0,optInMode:J},W);break}case"remove_subscribers_from_list":{let W=b.companyId,Q=Z("remove_subscribers_from_list",b,"listId"),X=a9("remove_subscribers_from_list",b);$=await D("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers/remove`,{emails:X},W);break}case"list_segments":{let W=b.companyId;$=await D("GET","/api/v1/segments",void 0,W);break}case"create_segment":{$5(b);let W=b.companyId;$=await D("POST","/api/v1/segments",{...b,...b.filters!==void 0?{filters:s6(b.filters)}:{},...b.root!==void 0?{root:e6(b.root)}:{}},W);break}case"update_segment":{W5(b);let W=b.companyId,Q=Z("update_segment",b,"segmentId"),X=L(b,"name"),G=n("update_segment",b,"filterJoinOperator",["and","or"]);$=await D("PATCH",`/api/v1/segments/${encodeURIComponent(Q)}`,{...X!==void 0&&{name:X},...G!==void 0&&{filterJoinOperator:G},...b.filters!==void 0?{filters:s6(b.filters)}:{},...b.root!==void 0?{root:e6(b.root)}:{}},W);break}case"delete_segment":{let W=b.companyId,Q=Z("delete_segment",b,"segmentId");$=await D("DELETE",`/api/v1/segments/${encodeURIComponent(Q)}`,void 0,W);break}case"get_segment_count":{let W=b.companyId;$=await D("GET",`/api/v1/segments/${b.segmentId}/count`,void 0,W);break}case"list_audience_syncs":{let W=b.companyId;$=await D("GET","/api/v1/audience-syncs",void 0,W);break}case"list_ad_accounts":{let W=b.companyId;$=await D("GET","/api/v1/ad-accounts",void 0,W);break}case"create_audience_sync":{let W=b.companyId,Q=L(b,"segmentId"),X=L(b,"predefinedSegmentId");if(Q&&X)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!Q&&!X)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");$=await D("POST","/api/v1/audience-syncs",{segmentId:Q,predefinedSegmentId:X,adAccountId:Z("create_audience_sync",b,"adAccountId"),audienceName:Z("create_audience_sync",b,"audienceName"),...b.frequency!==void 0?{frequency:b.frequency}:{}},W);break}case"update_audience_sync":{let W=b.companyId,Q=Z("update_audience_sync",b,"syncId");$=await D("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,{...b.frequency!==void 0?{frequency:b.frequency}:{},...b.isActive!==void 0?{isActive:b.isActive}:{}},W);break}case"delete_audience_sync":{let W=b.companyId,Q=Z("delete_audience_sync",b,"syncId");$=await D("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,void 0,W);break}case"sync_audience_now":{let W=b.companyId,Q=Z("sync_audience_now",b,"syncId");$=await D("POST",`/api/v1/audience-syncs/${encodeURIComponent(Q)}/sync`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function K3(w,b){let $;switch(w){case"list_templates":{let W=b.companyId,Q=new URLSearchParams,X=L(b,"label");if(X)Q.set("label",X);$=await D("GET",`/api/v1/templates${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_template":{let W=b.companyId;$=await D("GET",`/api/v1/templates/${b.templateId}`,void 0,W);break}case"create_template":{let W=b.companyId;O5(b);let Q=Object.fromEntries(Object.entries(b).filter(([X])=>X!=="companyId"));$=await D("POST","/api/v1/templates",Q,W);break}case"update_template":{let W=b.companyId,Q=new Set(["companyId","templateId","name","subject","previewText","html","blocks","labels"]),X=Object.keys(b).filter((G)=>!Q.has(G));if(X.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);if(Cw("update_template",b),L1("update_template",b),b.name===void 0&&b.subject===void 0&&b.previewText===void 0&&b.html===void 0&&b.blocks===void 0&&b.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `previewText`, `html`, `blocks`, or `labels` when calling `update_template`.");$=await D("PUT",`/api/v1/templates/${b.templateId}`,b,W);break}case"set_template_localization":{let W=b.companyId,Q=Z("set_template_localization",b,"templateId"),X=Z("set_template_localization",b,"locale"),G=Z("set_template_localization",b,"subject"),J=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),Y=Object.keys(b).filter((z)=>!J.has(z));if(Y.length>0)throw Error(`\`set_template_localization\` received unsupported field${Y.length===1?"":"s"}: ${Y.map((z)=>`\`${z}\``).join(", ")}.`);Cw("set_template_localization",b,{requireContent:!0});let H={subject:G};if(b.previewText!==void 0)H.previewText=b.previewText;if(b.html!==void 0)H.html=b.html;if(b.blocks!==void 0)H.blocks=b.blocks;$=await D("PUT",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/${encodeURIComponent(X)}`,H,W);break}case"sync_template_localizations":{let W=b.companyId,Q=Z("sync_template_localizations",b,"templateId"),X=new Set(["companyId","templateId","locales"]),G=Object.keys(b).filter((Y)=>!X.has(Y));if(G.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${G.length===1?"":"s"}: ${G.map((Y)=>`\`${Y}\``).join(", ")}.`);let J;if(b.locales!==void 0){if(!Array.isArray(b.locales)||b.locales.length===0||b.locales.some((Y)=>typeof Y!=="string"||Y.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");J=b.locales.map((Y)=>Y.trim())}$=await D("POST",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/sync`,J===void 0?{}:{locales:J},W);break}case"delete_template":{let W=b.companyId;$=await D("DELETE",`/api/v1/templates/${b.templateId}`,void 0,W);break}case"list_ab_tests":{let W=b.companyId,Q=new URLSearchParams,X=L(b,"sequenceId");if(X)Q.set("sequenceId",X);$=await D("GET",`/api/v1/ab-tests${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_ab_test":{let W=b.companyId;$=await D("GET",`/api/v1/ab-tests/${b.abTestId}`,void 0,W);break}case"get_ab_test_stats":{let W=b.companyId,Q=new URLSearchParams,X=L(b,"period"),G=L(b,"start"),J=L(b,"end");if(X)Q.set("period",X);if(G)Q.set("start",G);if(J)Q.set("end",J);if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");$=await D("GET",`/api/v1/ab-tests/${b.abTestId}/stats${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"restart_ab_test":{let W=b.companyId,Q=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),X=Object.keys(b).filter((H)=>!Q.has(H));if(X.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${X.length===1?"":"s"}: ${X.map((H)=>`\`${H}\``).join(", ")}.`);let G=L(b,"testType");if(G!==void 0&&G!=="subject"&&G!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let J=b.winnerThreshold===void 0?void 0:Number(b.winnerThreshold);if(J!==void 0&&(!Number.isInteger(J)||J<10||J>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let Y=b.variantCount===void 0?void 0:Number(b.variantCount);if(Y!==void 0&&(!Number.isInteger(Y)||Y<2||Y>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");$=await D("POST",`/api/v1/ab-tests/${b.abTestId}/restart`,{sourceVariantId:L(b,"sourceVariantId"),testType:G,winnerThreshold:J,variantCount:Y},W);break}case"update_ab_test_variant":{let W=b.companyId,Q=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks","confirmLiveChange"]),X=Object.keys(b).filter((G)=>!Q.has(G));if(X.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`confirmLiveChange\` fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);if(Cw("update_ab_test_variant",b),b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test_variant`.");if(b.subject===void 0&&b.previewText===void 0&&b.html===void 0&&b.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");$=await D("PATCH",`/api/v1/ab-tests/${b.abTestId}/variants/${b.variantId}`,b,W);break}case"update_ab_test":{let W=b.companyId,Q=Z("update_ab_test",b,"abTestId"),X=new Set(["companyId","abTestId","name","testPercentage","testDurationMinutes","winnerCriteria","testType","winnerThreshold","confirmLiveChange"]),G=Object.keys(b).filter((F)=>!X.has(F));if(G.length>0)throw Error(`\`update_ab_test\` received unsupported field${G.length===1?"":"s"}: ${G.map((F)=>`\`${F}\``).join(", ")}.`);if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test`.");let J=L(b,"name"),Y=Bw("update_ab_test",b,"testPercentage",5,50),H=Bw("update_ab_test",b,"testDurationMinutes",15,1440),z=n("update_ab_test",b,"winnerCriteria",["open_rate","click_rate"]),B=n("update_ab_test",b,"testType",["subject","content"]),A=Bw("update_ab_test",b,"winnerThreshold",10,1000);if(J===void 0&&Y===void 0&&H===void 0&&z===void 0&&B===void 0&&A===void 0)throw Error("Provide at least one of `name`, `testPercentage`, `testDurationMinutes`, `winnerCriteria`, `testType`, or `winnerThreshold` when calling `update_ab_test`.");$=await D("PATCH",`/api/v1/ab-tests/${encodeURIComponent(Q)}`,{...J!==void 0&&{name:J},...Y!==void 0&&{testPercentage:Y},...H!==void 0&&{testDurationMinutes:H},...z!==void 0&&{winnerCriteria:z},...B!==void 0&&{testType:B},...A!==void 0&&{winnerThreshold:A},...b.confirmLiveChange===!0&&{confirmLiveChange:!0}},W);break}case"create_ab_test":{let W=b.companyId,Q=L(b,"campaignId"),X=L(b,"automationNodeId");if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `create_ab_test`.");if(Boolean(Q)===Boolean(X))throw Error("Provide exactly one of `campaignId` or `automationNodeId` when calling `create_ab_test`.");let G=L(b,"name"),J=Bw("create_ab_test",b,"testPercentage",5,50),Y=Bw("create_ab_test",b,"testDurationMinutes",15,1440),H=n("create_ab_test",b,"winnerCriteria",["open_rate","click_rate"]),z=n("create_ab_test",b,"testType",["subject","content"]),B=Bw("create_ab_test",b,"winnerThreshold",10,1000);if(b.variants!==void 0){if(!Array.isArray(b.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");b.variants.forEach((F,U)=>{if(!C(F)||typeof F.subject!=="string"||F.subject.trim()==="")throw Error(`\`variants\` item ${U+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(F.blocks!==void 0&&!Array.isArray(F.blocks))throw Error(`\`variants\` item ${U+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}let A=Array.isArray(b.variants)?b.variants:void 0;if(X!==void 0&&(!A||A.length<1))throw Error("`variants` must include at least one competing variant when calling `create_ab_test` with `automationNodeId`.");if(A&&A.length>4)throw Error("`variants` supports at most four extra variants when calling `create_ab_test`.");$=await D("POST","/api/v1/ab-tests",{...Q!==void 0&&{campaignId:Q},...X!==void 0&&{automationNodeId:X},...b.confirmLiveChange===!0&&{confirmLiveChange:!0},...G!==void 0&&{name:G},...J!==void 0&&{testPercentage:J},...Y!==void 0&&{testDurationMinutes:Y},...H!==void 0&&{winnerCriteria:H},...z!==void 0&&{testType:z},...B!==void 0&&{winnerThreshold:B},...b.variants!==void 0&&{variants:b.variants}},W);break}case"add_ab_test_variant":{let W=b.companyId,Q=Z("add_ab_test_variant",b,"abTestId"),X=Z("add_ab_test_variant",b,"subject"),G=L(b,"previewText");if(b.blocks!==void 0&&!Array.isArray(b.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `add_ab_test_variant`.");$=await D("POST",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants`,{subject:X,...G!==void 0&&{previewText:G},...b.blocks!==void 0&&{blocks:b.blocks},...b.confirmLiveChange===!0&&{confirmLiveChange:!0}},W);break}case"delete_ab_test_variant":{let W=b.companyId,Q=Z("delete_ab_test_variant",b,"abTestId"),X=Z("delete_ab_test_variant",b,"variantId");if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `delete_ab_test_variant`.");$=await D("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants/${encodeURIComponent(X)}${b.confirmLiveChange===!0?"?confirmLiveChange=true":""}`,void 0,W);break}case"delete_ab_test":{let W=b.companyId,Q=Z("delete_ab_test",b,"abTestId");$=await D("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}`,void 0,W);break}case"list_campaigns":{let W=b.companyId,Q=new URLSearchParams;if(b.status)Q.set("status",String(b.status));let X=L(b,"label");if(X)Q.set("label",X);for(let G of["limit","offset"])if(b[G]!==void 0)Q.set(G,String(b[G]));$=await D("GET",`/api/v1/campaigns?${Q}`,void 0,W);break}case"get_campaign":{let W=b.companyId;$=await D("GET",`/api/v1/campaigns/${b.campaignId}`,void 0,W);break}case"get_campaign_audience":{let W=b.companyId;$=await D("GET",`/api/v1/campaigns/${encodeURIComponent(String(b.campaignId))}/audience`,void 0,W);break}case"get_email_send":{let W=b.companyId;$=await D("GET",`/api/v1/email-sends/${encodeURIComponent(String(b.emailSendId))}`,void 0,W);break}case"list_email_sends":{let W=b.companyId,Q=new URLSearchParams,X=["search","subject","recipient","campaignId","transactionalEmailId","automationId"];for(let q of X){let P=L(b,q);if(P)Q.set(q,P)}let G=n("list_email_sends",b,"status",["pending","sent","delivered","opened","clicked","bounced","complained","failed","suppressed"]),J=n("list_email_sends",b,"emailType",["campaign","transactional","sequence"]),Y=n("list_email_sends",b,"bounceType",["Permanent","Transient"]),H=n("list_email_sends",b,"sortField",["recipientEmail","subject","status","eventAt","sentAt","createdAt"]),z=n("list_email_sends",b,"sortOrder",["asc","desc"]),B=Bw("list_email_sends",b,"days",1,14),A=Bw("list_email_sends",b,"page",1,Number.MAX_SAFE_INTEGER),F=Bw("list_email_sends",b,"limit",1,100),U=[["status",G],["emailType",J],["bounceType",Y],["sortField",H],["sortOrder",z],["days",B],["page",A],["limit",F]];for(let[q,P]of U)if(P!==void 0)Q.set(q,String(P));let V=Q.toString();$=await D("GET",`/api/v1/email-sends${V?`?${V}`:""}`,void 0,W);break}case"create_campaign":{let W=b.companyId;K5(b),F0("create_campaign",b);let Q=Object.fromEntries(Object.entries(b).filter(([X])=>X!=="companyId"));$=await D("POST","/api/v1/campaigns",Q,W);break}case"update_campaign":{let W=b.companyId,Q=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","ccEmails","bccEmails","campaignData","computedLists","targetLists","segmentId","labels"]),X=Object.keys(b).filter((G)=>!Q.has(G));if(X.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, audience, and label update fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);if(Cw("update_campaign",b),L1("update_campaign",b),F0("update_campaign",b,{replyFirst:!0}),b.segmentId!==void 0&&b.targetLists!==void 0)throw Error("Provide either `segmentId` or `targetLists` when calling `update_campaign`, not both.");if(b.name===void 0&&b.subject===void 0&&b.trackingCode===void 0&&b.html===void 0&&b.blocks===void 0&&b.fromEmail===void 0&&b.senderProfileId===void 0&&b.replyTo===void 0&&b.replyProfileId===void 0&&b.ccEmails===void 0&&b.bccEmails===void 0&&b.campaignData===void 0&&b.computedLists===void 0&&b.targetLists===void 0&&b.segmentId===void 0&&b.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, audience, or label field when calling `update_campaign`.");$=await D("PUT",`/api/v1/campaigns/${b.campaignId}`,b,W);break}case"schedule_campaign":{let W=b.companyId,Q=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),X=Object.keys(b).filter((G)=>!Q.has(G));if(X.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);Z5(b),$=await D("POST",`/api/v1/campaigns/${b.campaignId}/schedule`,{scheduledAt:b.scheduledAt,...b.targetLists!==void 0&&{targetLists:b.targetLists},...b.sendTimeOptimization!==void 0&&{sendTimeOptimization:b.sendTimeOptimization},...b.spreadOverHours!==void 0&&{spreadOverHours:b.spreadOverHours},...b.recurringInterval!==void 0&&{recurringInterval:b.recurringInterval}},W);break}case"send_test_email":{let W=b.companyId;$=await D("POST",`/api/v1/campaigns/${b.campaignId}/test`,{to:b.to},W);break}case"cancel_campaign":{let W=b.companyId,Q=Z("cancel_campaign",b,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/cancel`,void 0,W);break}case"unschedule_campaign":{let W=b.companyId,Q=Z("unschedule_campaign",b,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/unschedule`,void 0,W);break}case"pause_campaign":{let W=b.companyId,Q=Z("pause_campaign",b,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/pause`,void 0,W);break}case"resume_campaign":{let W=b.companyId,Q=Z("resume_campaign",b,"campaignId"),X=Bw("resume_campaign",b,"spreadOverHours",1,72);$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resume`,{...X!==void 0&&{spreadOverHours:X}},W);break}case"delete_campaign":{let W=b.companyId,Q=Z("delete_campaign",b,"campaignId");$=await D("DELETE",`/api/v1/campaigns/${encodeURIComponent(Q)}`,void 0,W);break}case"duplicate_campaign":{let W=b.companyId,Q=Z("duplicate_campaign",b,"campaignId"),X=n("duplicate_campaign",b,"mode",["campaign","ab_test","variant"]),G=L(b,"variantId");if(X==="variant"&&G===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/duplicate`,{...X!==void 0&&{mode:X},...G!==void 0&&{variantId:G}},W);break}case"resend_campaign_to_non_openers":{let W=b.companyId,Q=Z("resend_campaign_to_non_openers",b,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resend-to-non-openers`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function O3(w,b){let $;switch(w){case"list_forms":{let W=b.companyId;$=await D("GET","/api/v1/forms",void 0,W);break}case"create_form":{let W=b.companyId,Q=Z("create_form",b,"name"),X=Array.isArray(b.listIds)?b.listIds.filter((Y)=>typeof Y==="string").map((Y)=>Y.trim()).filter(Boolean):[];if(X.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let G=n("create_form",b,"duplicateStrategy",["skip","merge","overwrite"]),J={name:Q,listIds:X};for(let Y of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName","theme"])if(b[Y]!==void 0)J[Y]=b[Y];if(G!==void 0)J.duplicateStrategy=G;$=await D("POST","/api/v1/forms",J,W);break}case"update_form":{let W=b.companyId,Q=Z("update_form",b,"formId"),X=n("update_form",b,"duplicateStrategy",["skip","merge","overwrite"]),G={};for(let J of["name","listIds","tagIds","buttonText","headline","description","successMessage","redirectUrl","theme","blocks"])if(b[J]!==void 0)G[J]=b[J];if(X!==void 0)G.duplicateStrategy=X;if(Object.keys(G).length===0)throw Error("Provide at least one field to change when calling `update_form`.");$=await D("PATCH",`/api/v1/forms/${encodeURIComponent(Q)}`,G,W);break}case"get_form_embed":{let W=b.companyId,Q=Z("get_form_embed",b,"formId");$=await D("GET",`/api/v1/forms/embed/${encodeURIComponent(Q)}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function Y4(w,b,$,W,Q){let X=w[b];if(X===void 0)return;if(typeof X!=="number"||!Number.isFinite(X)||X<$||X>W||Q&&!Number.isInteger(X))throw Error(`\`${b}\` must be a ${Q?"integer":"number"} between ${$} and ${W} when calling \`upload_image_asset\`.`);return X}async function Z3(w,b){if(w!=="upload_image_asset")return{handled:!1,result:void 0};let $=L(b,"filePath"),W=L(b,"imageBase64");if($===void 0===(W===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let Q=L(b,"filename");if(W!==void 0&&Q===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let X=Y4(b,"sourceWidth",1,20000,!0),G=Y4(b,"sourceHeight",1,20000,!0);if(X===void 0!==(G===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let J=Y4(b,"displayWidthPercent",1,100,!1)??100,Y=Y4(b,"cropHeight",1,2000,!0),H=L(b,"objectFit");if(H!==void 0&&H!=="cover"&&H!=="contain")throw Error("`objectFit` must be 'cover' or 'contain' when calling `upload_image_asset`.");if(H!==void 0&&Y===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let z=L(b,"align");if(z!==void 0&&!["left","center","right"].includes(z))throw Error("`align` must be 'left', 'center', or 'right' when calling `upload_image_asset`.");let B=typeof b.altText==="string"?b.altText.trim():void 0;if(B!==void 0&&B.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let A=await k5({companyId:L(b,"companyId"),filePath:$,imageBase64:W,filename:Q,contentType:L(b,"contentType"),altText:B,sourceWidth:X,sourceHeight:G}),F={type:"image",src:A.url,alt:A.altText??"",width:J,widthType:"percent",...Y!==void 0&&{height:Y,objectFit:H??"cover"},...z!==void 0&&{align:z}};return{handled:!0,result:{success:!0,asset:A,imageBlock:F,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}async function M3(w,b){let $=b.companyId,W;switch(w){case"connect_integration":{let Q=Z("connect_integration",b,"provider"),X=Z("connect_integration",b,"webhookSecret");W=await D("POST","/api/v1/integrations/connect",{provider:Q,webhookSecret:X,...typeof b.apiKey==="string"&&b.apiKey?{apiKey:b.apiKey}:{},...typeof b.providerAccountId==="string"&&b.providerAccountId?{providerAccountId:b.providerAccountId}:{},...b.settings!==void 0?{settings:b.settings}:{},...b.historyImport!==void 0?{historyImport:b.historyImport}:{}},$);break}case"get_integration":{let Q=Z("get_integration",b,"integrationId");W=await D("GET",`/api/v1/integrations/${encodeURIComponent(Q)}`,void 0,$);break}case"list_integration_capabilities":{let Q=new URLSearchParams;if(typeof b.provider==="string"&&b.provider)Q.set("provider",b.provider);if(typeof b.category==="string"&&b.category)Q.set("category",b.category);let X=Q.toString();W=await D("GET",`/api/v1/integrations/catalog${X?`?${X}`:""}`,void 0,$);break}case"list_integration_activity":{let Q=new URLSearchParams;if(typeof b.integrationId==="string"&&b.integrationId)Q.set("integrationId",b.integrationId);if(typeof b.provider==="string"&&b.provider)Q.set("provider",b.provider);if(typeof b.status==="string"&&b.status)Q.set("status",b.status);if(typeof b.limit==="number")Q.set("limit",String(b.limit));let X=Q.toString();W=await D("GET",`/api/v1/integrations/activity${X?`?${X}`:""}`,void 0,$);break}case"set_integration_sync_enabled":{let Q=Z("set_integration_sync_enabled",b,"integrationId");if(typeof b.syncEnabled!=="boolean")throw Error("`syncEnabled` must be a boolean when calling `set_integration_sync_enabled`.");W=await D("PATCH",`/api/v1/integrations/${encodeURIComponent(Q)}`,{syncEnabled:b.syncEnabled},$);break}case"get_integration_pixel":{let Q=Z("get_integration_pixel",b,"integrationId");W=await D("GET",`/api/v1/integrations/${encodeURIComponent(Q)}/pixel`,void 0,$);break}case"activate_integration_pixel":{let Q=Z("activate_integration_pixel",b,"integrationId");W=await D("POST",`/api/v1/integrations/${encodeURIComponent(Q)}/pixel`,void 0,$);break}case"sync_integration":{let Q=Z("sync_integration",b,"integrationId");W=await D("POST",`/api/v1/integrations/${encodeURIComponent(Q)}/sync`,void 0,$);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:W}}async function V3(w,b){let $;switch(w){case"list_landing_pages":{let W=b.companyId;$=await D("GET","/api/v1/landing-pages",void 0,W);break}case"get_landing_page":{let W=b.companyId;$=await D("GET",`/api/v1/landing-pages/${b.landingPageId}`,void 0,W);break}case"create_landing_page":{let W=b.companyId,Q=new Set(["companyId","name","slug","template","content"]),X=Object.keys(b).filter((G)=>!Q.has(G));if(X.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);$=await D("POST","/api/v1/landing-pages",{...b.name!==void 0&&{name:b.name},...b.slug!==void 0&&{slug:b.slug},...b.template!==void 0&&{template:b.template},...b.content!==void 0&&{content:b.content}},W);break}case"update_landing_page":{let W=b.companyId,Q=$4("update_landing_page",b,{requireUpdate:!0});$=await D("PUT",`/api/v1/landing-pages/${b.landingPageId}`,Q,W);break}case"publish_landing_page":{let W=b.companyId,Q=$4("publish_landing_page",b,{requireUpdate:!1});$=await D("POST",`/api/v1/landing-pages/${b.landingPageId}/publish`,Q,W);break}case"unpublish_landing_page":{let W=b.companyId,Q=$4("unpublish_landing_page",b,{requireUpdate:!1});$=await D("POST",`/api/v1/landing-pages/${b.landingPageId}/unpublish`,Q,W);break}case"duplicate_landing_page":{let W=b.companyId;$=await D("POST",`/api/v1/landing-pages/${b.landingPageId}/duplicate`,{...b.name!==void 0&&{name:b.name},...b.slug!==void 0&&{slug:b.slug}},W);break}case"delete_landing_page":{let W=b.companyId;$=await D("DELETE",`/api/v1/landing-pages/${b.landingPageId}`,void 0,W);break}case"connect_landing_page_domain":{let W=b.companyId;$=await D("POST","/api/v1/landing-pages/domain",{domain:b.domain},W);break}case"update_landing_page_domain_settings":{let W=b.companyId,Q=M5(b);$=await D("PUT","/api/v1/landing-pages/domain",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function j3(w,b){let $;switch(w){case"list_products":{let W=b.companyId,Q=new URLSearchParams;if(typeof b.provider==="string"&&b.provider.trim())Q.set("provider",b.provider.trim());if(typeof b.search==="string"&&b.search.trim())Q.set("search",b.search.trim());let X=Bw("list_products",b,"limit",1,100);if(X!==void 0)Q.set("limit",String(X));let G=Bw("list_products",b,"offset",0,Number.MAX_SAFE_INTEGER);if(G!==void 0)Q.set("offset",String(G));let J=Q.size>0?`?${Q.toString()}`:"";$=await D("GET",`/api/v1/products${J}`,void 0,W);break}case"upsert_products":{let W=b.companyId;if(!Array.isArray(b.products)||b.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");$=await D("POST","/api/v1/products",{products:b.products},W);break}case"delete_product":{let W=b.companyId,Q=Z("delete_product",b,"productId");$=await D("DELETE",`/api/v1/products/${encodeURIComponent(Q)}`,void 0,W);break}case"attach_product_file":{let W=b.companyId,Q=Z("attach_product_file",b,"productId"),X=L(b,"url"),G=L(b,"filePath");if(X===void 0===(G===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let J;if(G!==void 0){let Y=await E5(G,W);J={url:Y.url,source:"upload",fileName:L(b,"fileName")??Y.fileName,fileSizeBytes:Y.fileSizeBytes,mimeType:Y.mimeType}}else{J={url:X};let Y=L(b,"fileName");if(Y)J.fileName=Y}$=await D("PUT",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,J,W);break}case"remove_product_file":{let W=b.companyId,Q=Z("remove_product_file",b,"productId");$=await D("DELETE",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,void 0,W);break}case"sync_products":{let W=b.companyId,Q=new URLSearchParams;if(typeof b.integrationId==="string"&&b.integrationId)Q.set("integrationId",b.integrationId);let X=Q.toString();$=await D("POST",`/api/v1/products/sync${X?`?${X}`:""}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function Tj(w){let b=L(w,"campaignId"),$=L(w,"sequenceId"),W=L(w,"templateId"),Q=[b,$,W].filter((X)=>X!==void 0);if(Q.length===0)throw Error("render_email requires one of campaignId, sequenceId plus nodeId, or templateId.");if(Q.length>1)throw Error("render_email accepts exactly one of campaignId, sequenceId, or templateId.");if(b!==void 0)return`/api/v1/campaigns/${encodeURIComponent(b)}/render`;if($!==void 0){let X=Z("render_email",w,"nodeId");return`/api/v1/sequences/${encodeURIComponent($)}/nodes/${encodeURIComponent(X)}/render`}return`/api/v1/templates/${encodeURIComponent(W)}/render`}var Rj=["subscriberId","subscriber","variables","locale","variantId","tracking"];async function q3(w,b){if(w!=="render_email")return{handled:!1,result:void 0};let $=Tj(b),W={};for(let X of Rj)if(b[X]!==void 0)W[X]=b[X];return{handled:!0,result:await D("POST",$,W,L(b,"companyId"))}}var P3=80,I3=10;function Sj(w){if(!Array.isArray(w.recipients))throw Error("`recipients` must be an array when calling `send_sequence_test_email`.");if(w.recipients.length>I3)throw Error(`\`recipients\` must include no more than ${I3} email addresses when calling \`send_sequence_test_email\`.`);if(w.recipients.find((Q)=>typeof Q!=="string"||Q.trim().length===0)!==void 0)throw Error("Every `recipients` item must be a non-empty email address when calling `send_sequence_test_email`.");let $=Array.from(new Set(w.recipients.map((Q)=>typeof Q==="string"?Q.trim().toLowerCase():""))).filter(Boolean);if($.length===0)throw Error("`recipients` must include at least one email address when calling `send_sequence_test_email`.");let W=$.find((Q)=>!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Q));if(W)throw Error(`Invalid test recipient email address: \`${W}\`.`);return $}function vj(w){let b=w.trim().replace(/\s+/g," ");if(b.length<=P3)return b;return`${b.slice(0,P3-3).trimEnd()}...`}async function QW(w,b){let $;switch(w){case"generate_sequence":{let W=Z("generate_sequence",b,"goal"),Q=typeof b.name==="string"&&b.name.trim().length>0?b.name.trim():void 0,G=(await QW("create_sequence",{...b,goal:W,name:Q??vj(W),trigger:"contact_added",durationDays:b.durationDays??14})).result;return{handled:!0,result:typeof G==="object"&&G!==null?{...G,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:G}}case"list_sequences":{let W=b.companyId,Q=new URLSearchParams;for(let G of["status","search","limit","offset"])if(b[G]!==void 0)Q.set(G,String(b[G]));if(Array.isArray(b.labels)&&b.labels.length>0)Q.set("labels",b.labels.join(","));let X=Q.size>0?`?${Q.toString()}`:"";$=await D("GET",`/api/v1/sequences${X}`,void 0,W);break}case"get_sequence":{let W=b.companyId;$=await D("GET",`/api/v1/sequences/${b.sequenceId}`,void 0,W);break}case"list_sequence_enrollments":{let W=b.companyId,Q=Z(w,b,"sequenceId"),X=new URLSearchParams;for(let J of["currentNodeId","status","subscriberId"]){let Y=b[J];if(Array.isArray(Y)){if(Y.length>0)X.set(J,Y.join(","))}else if(Y!==void 0)X.set(J,String(Y))}for(let J of["email","sort","limit","offset"])if(b[J]!==void 0)X.set(J,String(b[J]));let G=X.size>0?`?${X.toString()}`:"";$=await D("GET",`/api/v1/sequences/${encodeURIComponent(Q)}/enrollments${G}`,void 0,W);break}case"send_sequence_test_email":{let W=b.companyId,Q=Z(w,b,"sequenceId"),X=Z(w,b,"nodeId"),G=Sj(b);$=await D("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/nodes/${encodeURIComponent(X)}/test`,{recipients:G},W);break}case"create_sequence":{let W=b.companyId;L1("create_sequence",b),F0("create_sequence",b);let Q=Array.isArray(b.steps),X=b.goal===void 0&&b.steps===void 0,G=await D("POST","/api/v1/sequences",b,W);if(!G.success){$=G;break}let J=G.sequence.id;if(Q||X){let A=await D("GET",`/api/v1/sequences/${J}`,void 0,W);if(A.success)$={...G,success:!0,sequence:A.sequence,message:`Sequence "${A.sequence.name}" created ${X?"as a blank draft":"with explicit steps"}. Review it before enabling.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=A;break}let Y=7,H=0,z="pending";while(z!=="complete"&&H<Y){let A=await D("GET",`/api/v1/sequences/${J}`,void 0,W);if(A.success)z=A.sequence.enrichmentStatus;if(H++,z!=="complete"&&H<Y)await new Promise((F)=>setTimeout(F,20000))}let B=await D("GET",`/api/v1/sequences/${J}`,void 0,W);if(B.success)$={...G,success:!0,sequence:B.sequence,message:B.sequence.enrichmentStatus==="complete"?`Sequence "${B.sequence.name}" created with ${B.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${B.sequence.name}" created. Email enrichment is still in progress (${B.sequence.enrichedCount}/${B.sequence.emailCount} emails generated). You can check status with get_sequence.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=B;break}case"update_sequence":{let W=b.companyId,Q=J5(b);$=await D("PUT",`/api/v1/sequences/${b.sequenceId}`,Q,W);break}case"update_sequence_node":{let W=b.companyId,Q=Z("update_sequence_node",b,"sequenceId"),X=B5(b);$=await D("PUT",`/api/v1/sequences/${Q}`,X,W);break}case"update_sequence_nodes":{let W=b.companyId,Q=Z("update_sequence_nodes",b,"sequenceId"),X=A5(b);$=await D("PUT",`/api/v1/sequences/${Q}`,X,W);break}case"edit_sequence_graph":{let W=b.companyId,Q=F5(b);$=await D("PUT",`/api/v1/sequences/${b.sequenceId}`,Q,W);break}case"insert_sequence_step":{let W=b.companyId,Q=L5(b),X=await D("PUT",`/api/v1/sequences/${b.sequenceId}`,Q,W);if(typeof X==="object"&&X!==null){let G=X,J=G.sequence;if(typeof J==="object"&&J!==null){let Y=J;$={...G,...Y.insertedNodeIds!==void 0?{insertedNodeIds:Y.insertedNodeIds}:{},...Y.insertedEmailIds!==void 0?{insertedEmailIds:Y.insertedEmailIds}:{},...Y.insertedEmailCount!==void 0?{insertedEmailCount:Y.insertedEmailCount}:{},...Y.addedBranchNodeId!==void 0?{addedBranchNodeId:Y.addedBranchNodeId}:{},...Y.addedBranchPathNodeIds!==void 0?{addedBranchPathNodeIds:Y.addedBranchPathNodeIds}:{}};break}}$=X;break}case"enable_sequence":{let W=b.companyId;$=await D("POST",`/api/v1/sequences/${b.sequenceId}/enable`,void 0,W);break}case"disable_sequence":{let W=b.companyId;$=await D("POST",`/api/v1/sequences/${b.sequenceId}/disable`,void 0,W);break}case"duplicate_sequence":{let W=b.companyId,Q=Z("duplicate_sequence",b,"sequenceId"),X=L(b,"name");$=await D("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/duplicate`,X===void 0?void 0:{name:X},W);break}case"archive_sequence":case"unarchive_sequence":{let W=b.companyId,Q=Z(w,b,"sequenceId"),X=w==="archive_sequence"?"archive":"unarchive";$=await D("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/${X}`,void 0,W);break}case"list_sequence_goals":{let W=b.companyId,Q=Z(w,b,"sequenceId");$=await D("GET",`/api/v1/sequences/${encodeURIComponent(Q)}/goals`,void 0,W);break}case"create_sequence_goal":case"update_sequence_goal":{let W=b.companyId,Q=Z(w,b,"sequenceId");if(w==="create_sequence_goal")Z(w,b,"name"),Y5(b);else H5(b);let X=w==="update_sequence_goal"?Z(w,b,"goalId"):void 0,G={...b};delete G.companyId,delete G.sequenceId,delete G.goalId,$=await D(w==="create_sequence_goal"?"POST":"PATCH",`/api/v1/sequences/${encodeURIComponent(Q)}/goals${X?`/${encodeURIComponent(X)}`:""}`,G,W);break}case"delete_sequence_goal":{let W=b.companyId,Q=Z(w,b,"sequenceId"),X=Z(w,b,"goalId");$=await D("DELETE",`/api/v1/sequences/${encodeURIComponent(Q)}/goals/${encodeURIComponent(X)}`,void 0,W);break}case"get_sequence_inbound_webhook":case"configure_sequence_inbound_webhook":case"rotate_sequence_inbound_webhook_secret":{let W=b.companyId,Q=Z(w,b,"sequenceId");if(b.clearFieldMapping===!0&&b.fieldMapping!==void 0)throw Error("Provide either `fieldMapping` or `clearFieldMapping`, not both.");if(b.clearSamplePayload===!0&&b.samplePayload!==void 0)throw Error("Provide either `samplePayload` or `clearSamplePayload`, not both.");let X=w==="configure_sequence_inbound_webhook",G=w==="rotate_sequence_inbound_webhook_secret",J=X?{...b.clearFieldMapping===!0?{fieldMapping:null}:b.fieldMapping!==void 0?{fieldMapping:b.fieldMapping}:{},...b.clearSamplePayload===!0?{samplePayload:null}:b.samplePayload!==void 0?{samplePayload:b.samplePayload}:{}}:void 0;$=await D(G?"POST":X?"PUT":"GET",`/api/v1/sequences/${encodeURIComponent(Q)}/inbound-webhook${G?"/rotate-secret":""}`,J,W);break}case"pause_sequence_enrollments":{let W=b.companyId;$=await D("POST",`/api/v1/sequences/${b.sequenceId}/pause-enrollments`,void 0,W);break}case"resume_sequence_enrollments":{let W=b.companyId;$=await D("POST",`/api/v1/sequences/${b.sequenceId}/resume-enrollments`,void 0,W);break}case"enroll_subscribers_in_sequence":{let W=b.companyId,Q=Z("enroll_subscribers_in_sequence",b,"sequenceId"),X=N5(b);$=await D("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/enroll`,X,W);break}case"cancel_sequence_enrollments":{let W=b.companyId,Q=U5(b);$=await D("POST",`/api/v1/sequences/${b.sequenceId}/enrollments/cancel`,Q,W);break}case"delete_sequence":{let W=b.companyId;$=await D("DELETE",`/api/v1/sequences/${b.sequenceId}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function H4(w,b,$){let W=b[$];if(W===void 0)return;if(!Array.isArray(W))throw Error(`\`${$}\` must be an array of strings when calling \`${w}\`.`);let Q=W.filter((X)=>typeof X==="string").map((X)=>X.trim()).filter((X)=>X.length>0);if(Q.length!==W.length)throw Error(`\`${$}\` must contain only non-empty strings when calling \`${w}\`.`);return Q}function Cj(w,b){let $=H4(w,b,"tags");if($===void 0||$.length===0)throw Error(`\`tags\` must contain at least one tag when calling \`${w}\`.`);let W=H4(w,b,"emails"),Q=H4(w,b,"externalIds"),X=H4(w,b,"subscriberIds");if((W?.length??0)+(Q?.length??0)+(X?.length??0)===0)throw Error(`Provide \`emails\`, \`externalIds\`, or \`subscriberIds\` when calling \`${w}\`.`);return{tags:$,...W?.length?{emails:W}:{},...Q?.length?{externalIds:Q}:{},...X?.length?{subscriberIds:X}:{},...w==="bulk_add_subscriber_tags"&&typeof b.triggerAutomations==="boolean"?{triggerAutomations:b.triggerAutomations}:{}}}async function N3(w,b){let $;switch(w){case"add_subscriber":{let W=b.companyId,Q=typeof b.phone==="string"&&b.phone.trim()!==""?b.phone.trim():void 0,X=Q?t9(b):ow("add_subscriber",b),G=n("add_subscriber",b,"status",["active","unsubscribed","bounced"]),J=n("add_subscriber",b,"optInMode",["default","confirmed","double_opt_in"]);if($=await D("POST","/api/v1/subscribers",{...X,...Q!==void 0&&{phone:Q},...typeof b.phoneCountry==="string"&&b.phoneCountry.trim()!==""&&{phoneCountry:b.phoneCountry.trim()},...typeof b.smsConsent==="boolean"&&{smsConsent:b.smsConsent},...b.firstName!==void 0&&{firstName:b.firstName},...b.lastName!==void 0&&{lastName:b.lastName},customAttributes:b.attributes,tags:b.tags,lists:b.listIds,...G!==void 0&&{status:G},...J!==void 0&&{optInMode:J},...b.createdAt!==void 0&&{createdAt:b.createdAt}},W),G!==void 0&&C($)&&C($.subscriber)&&$.subscriber.skipped===!0&&$.subscriber.status!==G)throw Error(`Existing subscriber was not changed to status '${G}'. Use update_subscriber to change an existing contact's status.`);break}case"create_subscriber_import":{let W=b.companyId;if(!Array.isArray(b.subscribers)||b.subscribers.length===0)throw Error("`subscribers` must be a non-empty array when calling `create_subscriber_import`.");if(b.subscribers.length>5000)throw Error("`create_subscriber_import` accepts at most 5000 subscriber records per call.");for(let G=0;G<b.subscribers.length;G+=1){let J=b.subscribers[G],Y=C(J)&&typeof J.email==="string"&&J.email.trim()!=="",H=C(J)&&typeof J.phone==="string"&&J.phone.trim()!=="";if(!Y&&!H)throw Error(`Subscriber record ${G} must include an email or a phone number.`)}let Q=n("create_subscriber_import",b,"duplicateStrategy",["skip","merge","overwrite"]),X=n("create_subscriber_import",b,"optInMode",["default","confirmed","double_opt_in"]);$=await D("POST","/api/v1/subscribers/imports",{subscribers:b.subscribers,...Q!==void 0&&{duplicateStrategy:Q},...b.fileName!==void 0&&{fileName:b.fileName},...b.listIds!==void 0&&{listIds:b.listIds},...b.enrollInSequences!==void 0&&{enrollInSequences:b.enrollInSequences},...b.defaultPhoneCountry!==void 0&&{defaultPhoneCountry:b.defaultPhoneCountry},...b.smsConsent!==void 0&&{smsConsent:b.smsConsent},...X!==void 0&&{optInMode:X}},W);break}case"get_subscriber_import":{let W=b.companyId,Q=Z("get_subscriber_import",b,"importId");$=await D("GET",`/api/v1/subscribers/imports/${encodeURIComponent(Q)}`,void 0,W);break}case"update_subscriber":{let W=b.companyId,Q=ow("update_subscriber",b),X=n("update_subscriber",b,"status",["active","unsubscribed","bounced"]),J=C(b.attributes)||b.addTags!==void 0||b.removeTags!==void 0?await Mb(Q,W):null,Y=Array.isArray(J?.subscriber.tags)?J.subscriber.tags.filter((F)=>typeof F==="string"):[],H=Array.isArray(b.addTags)?b.addTags.filter((F)=>typeof F==="string"&&F.trim()!=="").map(o9):[],z=new Set(Array.isArray(b.removeTags)?b.removeTags.filter((F)=>typeof F==="string"&&F.trim()!=="").map(o9):[]),B=Y.filter((F)=>!z.has(F));for(let F of H)if(!B.includes(F))B.push(F);let A={};if(Q.email&&Q.externalId)A.externalId=Q.externalId;if(b.firstName!==void 0)A.firstName=b.firstName;if(b.lastName!==void 0)A.lastName=b.lastName;if(typeof b.phone==="string"||b.phone===null)A.phone=b.phone;if(typeof b.phoneCountry==="string")A.phoneCountry=b.phoneCountry;if(typeof b.smsConsent==="boolean")A.smsConsent=b.smsConsent;if(X!==void 0)A.status=X;if(C(b.attributes))A.customAttributes={...C(J?.subscriber.customAttributes)?J.subscriber.customAttributes:{},...b.attributes};if(b.addTags||b.removeTags)A.tags=B;$=await D("PATCH",W4(Q),A,W);break}case"remove_subscriber":{let W=b.companyId,Q=ow("remove_subscriber",b),X=W4(Q);if(b.hardDelete===!0)$=await D("DELETE",X,void 0,W);else $=await D("PATCH",X,{status:"unsubscribed"},W);break}case"get_subscriber":{let W=b.companyId,Q=ow("get_subscriber",b);$=await Mb(Q,W,{includeMachineEngagement:b.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let W=b.companyId,Q=ow("list_subscriber_notes",b);$=await D("GET",r9(Q),void 0,W);break}case"add_subscriber_note":{let W=b.companyId,Q=ow("add_subscriber_note",b),X=typeof b.body==="string"?b.body.trim():void 0;if(!X)throw Error("`body` is required when calling `add_subscriber_note`.");if(X.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");$=await D("POST",r9(Q),{body:X},W);break}case"delete_subscriber_note":{let W=b.companyId,Q=typeof b.noteId==="string"?b.noteId.trim():"";if(!Q)throw Error("`noteId` is required when calling `delete_subscriber_note`.");$=await D("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(Q)}`,void 0,W);break}case"trigger_subscriber_event":{let W=b.companyId,Q=ow("trigger_subscriber_event",b),X=Z("trigger_subscriber_event",b,"event");if(b.properties!==void 0&&!C(b.properties))throw Error("`properties` must be an object when calling `trigger_subscriber_event`.");$=await D("POST","/api/v1/subscribers/events",{...Q,event:X,...b.properties!==void 0&&{properties:b.properties},...b.firstName!==void 0&&{firstName:b.firstName},...b.lastName!==void 0&&{lastName:b.lastName},...b.attributes!==void 0&&{customAttributes:b.attributes},...b.occurredAt!==void 0&&{occurredAt:b.occurredAt},...b.eventId!==void 0&&{eventId:b.eventId}},W);break}case"trigger_subscriber_events":{let W=b.companyId,Q=ow("trigger_subscriber_events",b);if(!Array.isArray(b.events)||b.events.length===0)throw Error("`events` must be a non-empty array when calling `trigger_subscriber_events`.");if(b.events.length>500)throw Error("`trigger_subscriber_events` accepts at most 500 events per call. Split a larger history import into several calls.");for(let X=0;X<b.events.length;X+=1){let G=b.events[X];if(!C(G)||typeof G.name!=="string"||G.name.trim()==="")throw Error(`Event ${X} must include a non-empty \`name\` string.`)}$=await D("POST","/api/v1/subscribers/events/bulk",{...Q,events:b.events,...b.firstName!==void 0&&{firstName:b.firstName},...b.lastName!==void 0&&{lastName:b.lastName},...b.attributes!==void 0&&{customAttributes:b.attributes}},W);break}case"bulk_add_subscriber_tags":case"bulk_remove_subscriber_tags":{let W=b.companyId,Q=Cj(w,b);$=await D("POST",`/api/v1/subscribers/bulk/tags/${w==="bulk_add_subscriber_tags"?"add":"remove"}`,Q,W);break}case"search_subscribers":{let W=b.companyId;$=await I5(b,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function E3(w,b){if(w!=="get_recipient_suppression"&&w!=="remove_recipient_suppression")return{handled:!1,result:void 0};let $=L(b,"companyId"),W=Z(w,b,"email"),Q=L(b,"region"),X=new URLSearchParams;if(Q)X.set("region",Q);let G=`/api/v1/suppressions/${encodeURIComponent(W)}${X.size>0?`?${X}`:""}`;return{handled:!0,result:await D(w==="get_recipient_suppression"?"GET":"DELETE",G,void 0,$)}}async function T3(w,b){let $;switch(w){case"list_team_members":{let W=b.companyId;$=await D("GET","/api/v1/team",void 0,W);break}case"invite_team_member":{let W=b.companyId,Q=Z("invite_team_member",b,"email"),X=Vb("invite_team_member",b,"role",["admin","viewer","restricted"]);if(b.canManageBilling!==void 0&&typeof b.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");$=await D("POST","/api/v1/team/invitations",{email:Q,role:X,...b.canManageBilling!==void 0&&{canManageBilling:b.canManageBilling}},W);break}case"cancel_team_invitation":{let W=b.companyId,Q=Z("cancel_team_invitation",b,"invitationId");$=await D("DELETE",`/api/v1/team/invitations/${encodeURIComponent(Q)}`,void 0,W);break}case"list_conversations":{let W=b.companyId,Q=new URLSearchParams,X=n("list_conversations",b,"status",["open","closed","all"]);if(X)Q.set("status",X);let G=L(b,"search");if(G)Q.set("search",G);if(b.unread!==void 0){if(typeof b.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(b.unread)Q.set("unread","true")}if(b.page!==void 0){if(typeof b.page!=="number"||!Number.isInteger(b.page)||b.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");Q.set("page",String(b.page))}let J=Bw("list_conversations",b,"limit",1,100);if(J!==void 0)Q.set("limit",String(J));$=await D("GET",`/api/v1/conversations${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_conversation":{let W=b.companyId,Q=Z("get_conversation",b,"conversationId");$=await D("GET",`/api/v1/conversations/${encodeURIComponent(Q)}`,void 0,W);break}case"reply_to_conversation":{let W=b.companyId,Q=Z("reply_to_conversation",b,"conversationId"),X=n("reply_to_conversation",b,"type",["outbound","note"])??"outbound",G=L(b,"subject"),J=L(b,"bodyText"),Y=L(b,"bodyHtml");if(X==="outbound"&&J===void 0&&Y===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");$=await D("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/messages`,{type:X,...G!==void 0&&{subject:G},...J!==void 0&&{bodyText:J},...Y!==void 0&&{bodyHtml:Y}},W);break}case"update_conversation_status":{let W=b.companyId,Q=Z("update_conversation_status",b,"conversationId"),X=Vb("update_conversation_status",b,"status",["open","closed"]);$=await D("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/status`,{status:X},W);break}case"mark_conversation_read":{let W=b.companyId,Q=Z("mark_conversation_read",b,"conversationId");$=await D("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/read`,void 0,W);break}case"list_webhooks":{let W=b.companyId;$=await D("GET","/api/v1/webhooks",void 0,W);break}case"create_webhook":{let W=b.companyId,Q=Z("create_webhook",b,"name"),X=Z("create_webhook",b,"url"),G=e9("create_webhook",b);$=await D("POST","/api/v1/webhooks",{name:Q,url:X,...G!==void 0&&{events:G}},W);break}case"update_webhook":{let W=b.companyId,Q=Z("update_webhook",b,"webhookId"),X=L(b,"name"),G=L(b,"url"),J=e9("update_webhook",b),Y=n("update_webhook",b,"status",["enabled","disabled"]);if(X===void 0&&G===void 0&&J===void 0&&Y===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");$=await D("PATCH",`/api/v1/webhooks/${encodeURIComponent(Q)}`,{...X!==void 0&&{name:X},...G!==void 0&&{url:G},...J!==void 0&&{events:J},...Y!==void 0&&{status:Y}},W);break}case"delete_webhook":{let W=b.companyId,Q=Z("delete_webhook",b,"webhookId");$=await D("DELETE",`/api/v1/webhooks/${encodeURIComponent(Q)}`,void 0,W);break}case"test_webhook":{let W=b.companyId,Q=Z("test_webhook",b,"webhookId");$=await D("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/test`,void 0,W);break}case"list_webhook_deliveries":{let W=b.companyId,Q=Z("list_webhook_deliveries",b,"webhookId"),X=Bw("list_webhook_deliveries",b,"limit",1,100),G=new URLSearchParams;if(X!==void 0)G.set("limit",String(X));$=await D("GET",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries${G.size>0?`?${G}`:""}`,void 0,W);break}case"replay_webhook_delivery":{let W=b.companyId,Q=Z("replay_webhook_delivery",b,"webhookId"),X=Z("replay_webhook_delivery",b,"deliveryId");$=await D("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries/${encodeURIComponent(X)}/replay`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var R3=[A3,M3,N3,E3,j3,U3,K3,q3,O3,V3,Z3,QW,L3,T3,F3];var kj=new Set(["create_campaign","update_campaign","create_template","update_template","set_template_localization","create_transactional_email","update_transactional_email","create_sequence","update_sequence","update_sequence_node","update_sequence_nodes","insert_sequence_step","update_ab_test_variant","create_ab_test"]);function S3(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}function XW(w){if(Array.isArray(w))return w.some(XW);if(!S3(w))return!1;for(let[b,$]of Object.entries(w)){if((b==="html"||b==="htmlContent")&&typeof $==="string"&&$.trim().length>0)return!0;if(XW($))return!0}return!1}function v3(w,b,$){if(!kj.has(w)||!XW(b)||!S3($))return $;let W=Array.isArray($.warnings)?$.warnings.filter((Q)=>typeof Q==="string"):[];return{...$,warnings:[...new Set([...W,Yw])]}}var C3=B3.map(y5).map(sH);async function k3(w,b){try{let $,W=!1;for(let X of R3){let G=await X(w,b);if(G.handled){$=G.result,W=!0;break}}if(!W)throw Error(`Unknown tool: ${w}`);let Q=j5($);if(Q)throw Q;return $=v3(w,b,$),$=await R5(w,b,$),{structuredContent:u5($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:U1($)}]}}}async function _3(w,b,$){let W=b.getRequestContext?.(w)??{};try{return await F4(W,$)}finally{await b.onRequestContextUpdated?.(W,w)}}function GW(w={}){let b=new N9({name:"sequenzy",version:nH.version},{capabilities:{tools:{},resources:{}},instructions:["Sequenzy email marketing MCP server: manage subscribers, campaigns, sequences, templates, and delivery stats.","If you have access to multiple companies, call get_account and then select_company (or pass companyId per call) before other tools.","IMPORTANT: whenever the user wanted to accomplish something and these tools did not expose functionality for it (missing tool, missing argument, unsupported workflow, or broken behavior), call submit_feedback describing the gap before finishing the task. The Sequenzy team reads every submission and uses it to decide what to build next."].join(`
52
- `)});return b.setRequestHandler(A$,async()=>{return{tools:C3}}),b.setRequestHandler(g0,async($,W)=>{let{name:Q,arguments:X}=$.params;return _3(W,w,()=>k3(Q,X??{}))}),b.setRequestHandler(G$,async()=>{return{resources:oH}}),b.setRequestHandler(Y$,async($,W)=>{let{uri:Q}=$.params;return _3(W,w,()=>tH(Q))}),b}import h3 from"node:process";class JW{append(w){this._buffer=this._buffer?Buffer.concat([this._buffer,w]):w}readMessage(){if(!this._buffer)return null;let w=this._buffer.indexOf(`
53
- `);if(w===-1)return null;let b=this._buffer.toString("utf8",0,w).replace(/\r$/,"");return this._buffer=this._buffer.subarray(w+1),_j(b)}clear(){this._buffer=void 0}}function _j(w){return wG.parse(JSON.parse(w))}function x3(w){return JSON.stringify(w)+`
54
- `}class YW{constructor(w=h3.stdin,b=h3.stdout){this._stdin=w,this._stdout=b,this._readBuffer=new JW,this._started=!1,this._ondata=($)=>{this._readBuffer.append($),this.processReadBuffer()},this._onerror=($)=>{this.onerror?.($)}}async start(){if(this._started)throw 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(){while(!0)try{let w=this._readBuffer.readMessage();if(w===null)break;this.onmessage?.(w)}catch(w){this.onerror?.(w)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(w){return new Promise((b)=>{let $=x3(w);if(this._stdout.write($))b();else this._stdout.once("drain",b)})}}async function xj(){ZW(),FW();let w=GW(),b=new YW;await w.connect(b),console.error("Sequenzy MCP server running on stdio")}xj().catch((w)=>{console.error(U1(w)),process.exit(1)});export{F4 as withMcpRequestContext,Ib as setSelectedCompanyId,K1 as getSelectedCompanyId,GW as createSequenzyMcpServer,D as apiRequest};
51
+ Before protected server-side API work, use create_api_key and save the key to .env as SEQUENZY_API_KEY. Static-site saved forms are the exception: use list_forms/create_form/get_form_embed and never place a secret key in browser code.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration), 'ecommerce' (connecting a custom e-commerce platform via the Commerce API)"}}}}];var l5=[{name:"generate_email",description:"Generate email blocks from a prompt. Generated blocks include the company's branding chrome (logo, footer with company name/address/unsubscribe) by default, matching emails created in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"},applyBranding:{type:"boolean",description:"Wrap the generated content with company branding (logo + footer). Defaults to true; set false to get raw content blocks only."},emailType:{type:"string",enum:["marketing","transactional"],description:"Email type. Transactional emails get a footer without the unsubscribe link. Defaults to marketing."}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED compatibility alias - use create_sequence] Create and persist a disabled AI-generated email sequence draft from a goal. The saved draft appears in list_sequences. The name defaults to the goal and the trigger defaults to contact_added; optionally pass listId to scope it. Review before enabling.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},name:{type:"string",description:"Optional sequence name. Defaults to the goal."},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"},listId:{type:"string",description:"Optional list ID. When provided, only contacts added to this list trigger the sequence."}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}},{name:"generate_sms",description:"Generate SMS marketing message variants from a prompt. Returns plain-text messages with per-message encoding and segment counts. Use the results as the 'text' of an SMS sequence step (insert_sequence_step with type 'sms' or a create_sequence sms step). Messages exclude opt-out footers and brand prefixes - the platform adds those automatically at send time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the SMS to generate (e.g., 'cart reminder with a free-shipping hook')"},count:{type:"number",description:"Number of message variants to generate (default: 3, max: 10)"}},required:["prompt"]}},{name:"get_sms_settings",description:"Get the company's SMS add-on status: whether SMS is enabled, plan eligibility, credit balance, brand prefix, phone numbers, and whether SMS steps will actually send. Check this before adding SMS steps to sequences so you can warn the user when SMS is not ready.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"send_test_sms",description:"Send a test SMS to a phone number. IMPORTANT: sends a real text message and charges SMS credits - only call when the user explicitly asks for a test send. Requires the SMS add-on with a verified number (check get_sms_settings). Limited to 5 test sends per hour; bypasses quiet hours; excluded from step stats.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Destination phone number in international E.164 format, e.g. +15550100123."},text:{type:"string",description:"Plain-text message body. Merge tags are not resolved for test sends to arbitrary numbers. Provide text or blocks."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable image URLs sent as MMS media (US/CA only)."},blocks:{type:"array",items:{type:"object"},description:"SMS content blocks (text + image subset). Provide text or blocks, not both."}},required:["to"]}}];var g5=[{name:"get_stats",description:"Get overview statistics for a time period, including reply count and reply rate. Counts form a funnel over the sends made inside the period: opened and clicked are unique per email send (not total open events) and include engagement that arrives after the period ends, so they never exceed sent. Rates divide by rateDenominator (delivered, falling back to sent), reported alongside rateDenominatorBasis. Set emailType to transactional for Send API and transactional SMTP open/click rates, including both direct and saved-template sends. When no emailType filter is used and a background-computed snapshot is available, the response also includes a top-level commerceForecast with predicted AOV, 12-month customer value, 90-day revenue, confidence, and data-eligibility reasons.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},period:{type:"string",description:"Time period: 7d, 30d, or 90d (default: 7d)"},emailType:{type:"string",description:"Optional structural email type filter: campaign, transactional, or sequence. Use transactional for Send API and transactional SMTP traffic."},includeMachineEngagement:kw}}},{name:"get_transactional_stats",description:"Get aggregate sends, deliveries, bounces, opens, clicks, and rates for one saved transactional email selected by ID or slug. Results are all-time by default; pass period or start/end for a window. For direct-content Send API messages, use get_stats with emailType transactional and list_email_sends/get_email_send for delivery-level detail.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Saved transactional email ID or API slug."},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days."},includeMachineEngagement:kw},required:["idOrSlug"]}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including replies and reply rate, attributed conversions, revenue (revenueCents), product recommendation funnel metrics, a per-link click breakdown in the top-level clickedLinks array, and any Poll or NPS survey summaries in the top-level polls array",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},period:{type:"string",description:"Time period: 1h, 24h, 7d, 30d, or 90d"},start:{type:"string",description:"Custom range start as an ISO 8601 timestamp; provide end too"},end:{type:"string",description:"Custom range end as an ISO 8601 timestamp; provide start too"},includeMachineEngagement:kw},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence. The steps array is the per-step breakdown: one entry per email step in graph order with its step number, automation nodeId, subject, and its own sent, delivered, bounced, opened, clicked, replies, and unsubscribed counts plus rates - so this is where you read how many of Email 4 went out, without reconstructing anything from list_sequence_events. Step counts come from the retained event stream, not the 14-day delivery history behind list_email_sends, so they stay answerable for old sends. Also returns the aggregate funnel across every step, attributed conversions and revenue (revenueCents), product recommendation funnel metrics, per-step failed subscribers and failure reasons, and enrollmentSkipped counts for trigger matches where the contact could not be enrolled (unsubscribed/bounced). Pass period or start/end to use one explicit window for every historical metric; without them, step and aggregate counts are all-time and enrollmentSkipped defaults to the last 30 days. The enrollmentCounts field is a live snapshot of active and waiting enrollments grouped by current node, so it is not limited by period or start/end. To compare the same step across many sequences in one call, use list_email_metrics instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days."},includeMachineEngagement:kw},required:["sequenceId"]}},{name:"list_campaign_events",description:"List paginated raw email events for a campaign. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},eventType:{type:"string",description:`Optional single event type. Supported values: ${Ob}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${Ob}. Defaults to delivery.`,items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:kw},required:["campaignId"]}},{name:"list_sequence_events",description:"List paginated raw email events for every email step in a sequence, or for one step via automationNodeId. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays. This is the per-recipient event stream - do not page it to count sends. Per-step and per-sequence totals already exist as get_sequence_stats steps[], and list_email_metrics gives the same per-step totals across many sequences at once.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},automationNodeId:{type:"string",description:"Optional email step to scope the stream to, taken from get_sequence_stats steps[].nodeId or get_sequence nodes. Must be an email step of this sequence. Defaults to every email step."},eventType:{type:"string",description:`Optional single event type. Supported values: ${Ob}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${Ob}. Defaults to delivery.`,items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:kw},required:["sequenceId"]}},{name:"list_email_metrics",description:"List per-email metrics across the account: one row per campaign and per sequence email step, each with its own delivery funnel, attributed conversions, and revenueCents. This is the tool for cross-sequence questions - 'how many Email 4s went out across these sequences' is one call with step=4 plus the returned totals, instead of one get_sequence_stats per sequence. Sequence rows carry sequenceId, sequenceName, automationNodeId, and step, so you can group or compare steps yourself. Counts come from the retained event stream (not the 14-day list_email_sends history) and match get_sequence_stats steps[] for the same step. Filter by emailType, sequenceId, campaignId, and step; sort with sort/order; page with page/limit. totals covers every matching email, not just the current page.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailType:{type:"string",description:"Optional email type: campaign or sequence. Defaults to both. Implied as sequence when sequenceId or step is set."},sequenceId:{type:"array",description:"Optional sequence IDs to restrict the breakdown to. Omit for every sequence in the account. Cannot be combined with campaignId.",items:{type:"string"}},campaignId:{type:"array",description:"Optional campaign IDs to restrict the breakdown to. Cannot be combined with sequenceId, step, or emailType sequence.",items:{type:"string"}},step:{type:"number",description:"Optional 1-based email step position to keep, counted in graph order per sequence. step 4 keeps only the fourth email of each sequence. Sequence emails only."},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided. Omit for all-time counts."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days. Omit start and end for all-time counts over the full retained window."},sort:{type:"string",description:"Sort field: sent, delivered, opened, clicked, openRate, clickRate, unsubscribed, conversions, revenue, step, or name. Defaults to sent."},order:{type:"string",description:"Sort order: asc or desc. Defaults to desc."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Emails per page. Defaults to 50; maximum 500."},includeMachineEngagement:kw}}},{name:"get_subscriber_activity",description:"Get recent activity, email stats, and current sequence enrollments for a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:kw},required:[]}}];var i5=[{name:"list_audience_syncs",description:"List Meta custom audience syncs (segment -> ad audience mappings) with their schedule and last sync status. Requires the Meta Ads integration to be connected in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_ad_accounts",description:"List the Meta ad accounts available through the connected Meta Ads integration. Use the returned account id as `adAccountId` when creating an audience sync.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_audience_sync",description:'Push a segment to a Meta custom audience and keep it synced on a schedule. Provide `segmentId` for an existing segment OR `predefinedSegmentId` for a ready-made template (for example "zero-ltv", "no-purchase-1y", "recent-buyers", "high-spenders-ecom", "non-buyers", "engaged") - the template segment is created automatically on first use. The first upload runs immediately. Note: audiences are add-only; subscribers who later leave the segment stay in the Meta audience.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Existing segment ID to sync. Mutually exclusive with `predefinedSegmentId`."},predefinedSegmentId:{type:"string",description:'Predefined segment template ID (for example "zero-ltv", "no-purchase-1y", "recent-buyers"). The segment is created automatically if it does not exist. Mutually exclusive with `segmentId`.'},adAccountId:{type:"string",description:"Meta ad account ID (act_...) from `list_ad_accounts`."},audienceName:{type:"string",description:"Name for the custom audience in Meta Ads Manager."},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"How often to re-upload the segment. Default: daily."}},required:["adAccountId","audienceName"]}},{name:"update_audience_sync",description:"Update an audience sync's frequency or pause/resume it (`isActive`).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID"},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"New sync frequency."},isActive:{type:"boolean",description:"Set false to pause the sync, true to resume it."}},required:["syncId"]}},{name:"delete_audience_sync",description:"Remove an audience sync mapping. The Meta audience itself is kept (running ads are not disrupted) - only future syncs stop.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to remove."}},required:["syncId"]}},{name:"sync_audience_now",description:"Trigger an immediate upload of the segment's subscribers to its Meta custom audience, outside the regular schedule.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to run."}},required:["syncId"]}}];var n5=[{name:"list_campaigns",description:"List campaigns. Results are paginated: the default page size is 50 and limit is capped at 100. Always read the returned `pagination` object (`limit`, `offset`, `count`, `total`, `hasMore`) and keep paging with `offset` while `hasMore` is true - a single call does not necessarily return every campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent, sending, cancelled, paused, waiting_approval, or rejected). Rejected campaign results include rejectionComment feedback when provided."},label:{type:"string",description:"Optional label name filter. Only campaigns assigned this label are returned."},limit:{type:"number",description:"Page size from 1 to 100. Defaults to 50."},offset:{type:"number",description:"Zero-based result offset. Defaults to 0."}}}},{name:"get_campaign",description:"Get campaign details and stats, including rejectionComment reviewer feedback for rejected campaigns. `emailId` is the campaign's linked email body - the same record returned by the templates tools - and can be passed as templateId to create_campaign to reuse the design; it is null for SMS campaigns. `targetLists` holds the raw audience targeting (IDs only); call get_campaign_audience for resolved list/segment names and a recipient count. Note that `computedLists` is email personalization (product lists rendered inside the email), not audience targeting.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_campaign_audience",description:"Resolve exactly who a campaign will reach. Returns the targeting kind, resolved list and segment names (flagging references that no longer exist), filter conditions, individual include/exclude adjustments, a plain-language summary, and a live recipient count. Critically, it reports whether targeting is unset - an unset campaign falls back to every active subscriber when scheduled. Use this to verify a scheduled campaign's audience before it sends.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"list_email_sends",description:"List and filter the recent sent-email delivery history shown in the dashboard. Search subject/title or recipient, filter by delivery status, email type, bounce type, or source ID, then pass a returned emailSendId to get_email_send for exact open/click timestamps and the complete event timeline. Each row carries recipientEmail, subscriberId, automationNodeId, abTestVariantId, and sent/delivered/opened/clicked timestamps, so rows join into a recipient-level delivery matrix without re-reading the raw event stream. Pass automationNodeId to list only the recipients of one sequence step. Delivery rows are retained for 14 days, so this is the wrong tool for send totals: read get_sequence_stats steps[] or list_email_metrics, which cover the full retained event window.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},search:{type:"string",description:"Case-insensitive search across subject and recipient email."},subject:{type:"string",description:"Case-insensitive subject/title filter."},recipient:{type:"string",description:"Case-insensitive recipient email filter."},status:{type:"string",description:"Delivery status: pending, sent, delivered, opened, clicked, bounced, complained, failed, or suppressed. Opened includes clicked deliveries, matching the dashboard."},emailType:{type:"string",description:"Email type: campaign, transactional, or sequence."},bounceType:{type:"string",description:"Bounce type: Permanent or Transient."},campaignId:{type:"string",description:"Filter deliveries from one campaign."},transactionalEmailId:{type:"string",description:"Filter deliveries from one saved transactional email."},automationId:{type:"string",description:"Filter deliveries from one sequence/automation."},automationNodeId:{type:"string",description:"Filter deliveries from one email step of a sequence, using the nodeId from get_sequence_stats steps[] or get_sequence nodes."},days:{type:"number",description:"History window in days, from 1 to 14. Defaults to 14."},page:{type:"number",description:"Page number starting at 1. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."},sortField:{type:"string",description:"Sort field: recipientEmail, subject, status, eventAt, sentAt, or createdAt. Defaults to createdAt."},sortOrder:{type:"string",description:"Sort order: asc or desc. Defaults to desc."}}}},{name:"get_email_send",description:"Get an email delivery by emailSendId, including queued and test sends, delivery status, provider failure reason, stored HTML, effective Reply-To, copied-recipient identity and primary email send ID, and the ClickHouse event timeline. `type` is the legacy source category; use `emailType` on the send and `deliveryPolicy` on events for the actual marketing or transactional policy when known. Queue jobs are internal execution details and are not exposed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Durable email delivery ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign. Omit all content fields to create an empty draft. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup. Defaults to draft; status 'sent' only archives an already-sent campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text. Optional when `prompt` is provided because the generated preview text will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider campaigns. ${Hw}`},blocks:{type:"array",description:A1,items:{type:"object"}},prompt:{type:"string",description:"Generate campaign blocks from a prompt. Generated blocks include the company's logo and footer, and the created campaign inherits the company brand font. Mutually exclusive with `html`, `blocks`, and `templateId`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},templateId:{type:"string",description:"Use a template instead of html"},segmentId:{type:"string",description:"Shorthand for targeting one saved segment. Equivalent to targetLists {type:'segment', segmentId}. Mutually exclusive with `targetLists`."},targetLists:{type:"object",description:"Campaign audience, saved on the draft. Omit to leave targeting unset and set it later with `update_campaign` or `schedule_campaign`. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Use this to send straight to a list without creating a segment first. Mutually exclusive with `segmentId`.",additionalProperties:!0},fromEmail:{type:"string",description:"From address for this campaign. Its domain must be configured and verified; a sender profile is created when needed."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail; omit it when using senderProfileId, which already carries its own display name."},senderProfileId:{type:"string",description:"Existing sender profile ID (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Reply-To address for this campaign. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},replyProfileId:{type:"string",description:"Existing reply profile ID (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},campaignData:{type:"object",description:"Optional campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Optional computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_campaign",description:"Update a draft campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line"},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested. Send an empty string to clear it."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider campaigns. ${Hw}`},blocks:{type:"array",description:A1,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail; omit it when using senderProfileId, which already carries its own display name."},senderProfileId:{type:"string",description:"Set an existing sender profile (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},ccEmails:{type:["array","null"],description:"Addresses CC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},bccEmails:{type:["array","null"],description:"Addresses BCC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},targetLists:{type:["object","null"],description:"Replace the draft's saved audience, using the same shapes as `create_campaign`. Send null to clear it and choose the audience in `schedule_campaign` instead; omit to leave it unchanged. Mutually exclusive with `segmentId`.",additionalProperties:!0},segmentId:{type:"string",description:"Shorthand for retargeting the draft at one saved segment. Equivalent to targetLists {type:'segment', segmentId}. Mutually exclusive with `targetLists`."},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign, as a one-off send or on a repeating weekly/monthly cadence via `recurringInterval`. Use `recurringInterval` for newsletters that go out on a fixed schedule instead of creating one campaign per issue. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:{type:"object",description:"Optional campaign targeting object. Omit to use saved targeting or all active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule.",additionalProperties:!0},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Queue a campaign test email to a single address. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"unschedule_campaign",description:"Return a scheduled campaign to an editable draft. Removes its pending send and recurrence without permanently cancelling it, so it can be edited and scheduled again.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Scheduled campaign ID to return to draft."}},required:["campaignId"],additionalProperties:!1}},{name:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"resend_campaign_to_non_openers",description:"Create a draft that resends a sent campaign to everyone in the same audience who didn't open it. Copies the campaign email and reuses the original audience with a 'didn't open this campaign' rule added. Only available 6 hours after the campaign finishes sending. The draft must be scheduled or sent separately. Returns the new draft and an estimate of how many subscribers haven't opened the original.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"ID of the sent campaign to resend to non-openers."}},required:["campaignId"]}}];var p5=[{name:"submit_feedback",description:"Send product feedback about Sequenzy itself to the Sequenzy team. IMPORTANT: call this tool whenever the user wanted to accomplish something and Sequenzy did not expose functionality for it - a missing tool or argument, an unsupported workflow, a confusing behavior, or a bug. Briefly tell the user you reported the gap. This feedback goes straight to the team and shapes what gets built next. Do not use it for questions about the user's own account or data, and never include secrets or API keys. Submitting feedback never changes account data.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},message:{type:"string",description:"The feedback itself. Be specific: what was needed, what was missing or wrong, and what you did instead (workaround, gave up, used the dashboard)."},category:{type:"string",enum:["missing_capability","bug","docs","ux","praise","other"],description:"Feedback category. Use missing_capability when the user wanted something these tools do not support (default: other)."},context:{type:"string",description:"Optional: what the user was trying to accomplish, in their words, plus any relevant tool names or arguments you tried."}},required:["message"]}}];var d5=[{name:"list_forms",description:"List saved signup forms for a company, including their server-managed audience settings and public action URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list forms for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"create_form",description:"Create and publish a saved signup form whose opaque formId is a client-safe public capability. The selected lists, tags, duplicate behavior, and success action stay server-side; no API key is needed in the deployed form. This creates the email/name fields only - add typed custom fields (select, textarea, hidden, ...) afterwards with update_form's blocks argument.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the form in. If not provided, uses the currently selected company."},name:{type:"string",description:"Internal saved-form name."},listIds:{type:"array",description:"One or more list IDs that every public submission will be added to. Use list_lists to resolve IDs.",items:{type:"string"}},tagIds:{type:"array",description:"Optional existing tag IDs applied by the saved form. Use list_tags to resolve IDs.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber. Defaults to skip."},buttonText:{type:"string",description:"Optional submit button label."},headline:{type:"string",description:"Optional form headline."},description:{type:"string",description:"Optional supporting form copy."},successMessage:{type:"string",description:"Confirmation shown after a successful submission when redirectUrl is omitted."},redirectUrl:{type:"string",description:"Optional HTTP or HTTPS URL for successful submissions. Omit it to show the saved confirmation message."},showFirstName:{type:"boolean",description:"Whether the generated form also collects first name."},showLastName:{type:"boolean",description:"Whether the generated form also collects last name."},theme:{type:"object",description:"Optional visual theme overrides so the form matches the brand instead of the default accent. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0}},required:["name","listIds"],additionalProperties:!1}},{name:"update_form",description:"Update a saved signup form: rename it, retarget its audience, edit its copy, restyle its theme, or replace its content blocks (for example to remove unwanted blocks that render publicly). Read the current content via list_forms first when editing blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."},name:{type:"string",description:"New internal saved-form name."},listIds:{type:"array",description:"Replacement list targeting. Every public submission will be added to these lists.",items:{type:"string"}},tagIds:{type:"array",description:"Replacement tag IDs applied by the saved form. Pass an empty array to clear tags.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber."},headline:{type:"string",description:"New text for the form's first heading block. Fails if the form has no heading block; edit blocks instead."},description:{type:"string",description:"New text for the form's first paragraph block. Fails if the form has no paragraph block; edit blocks instead."},buttonText:{type:"string",description:"New submit button label."},successMessage:{type:"string",description:"New confirmation message on the success screen."},redirectUrl:{type:"string",description:"HTTP or HTTPS URL for successful submissions. Pass an empty string to switch back to the confirmation message."},theme:{type:"object",description:"Visual theme overrides merged into the current theme. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0},blocks:{type:"array",description:`Full replacement for the form's content blocks. Fetch the current blocks from list_forms, modify them, and send the complete array - the form must keep exactly one required email field and one submit button. Blocks render in array order; every block needs a unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Input blocks are kind "form-field": { id, kind: "form-field", fieldType, name, label, placeholder, required, defaultValue, showLabel, width ("full" | "half"), mapsTo, options }. fieldType is one of text, email, phone, number, textarea, select, radio, checkbox, consent, hidden. mapsTo is one of email, firstName, lastName, phone, customAttribute and defaults to customAttribute, which stores the answer under the block's "name" as a subscriber custom attribute (name must start with a letter and may contain letters, digits, "_", ".", "-"). select, radio, and checkbox fields require options: [{ value, label, id }] - label and id default to value when omitted. A hidden field with a defaultValue always stores that server-owned value and ignores whatever the page posts; a hidden field with an empty defaultValue stores the value the page submits. Other kinds: heading, text, image, button, divider, spacer, custom-html, feature-grid, testimonial, countdown, form-step, submit-button, success-screen, error-state. Validation errors name the offending property, for example "blocks[3].options[0].value".`,items:{type:"object",additionalProperties:!0}}},required:["formId"],additionalProperties:!1}},{name:"get_form_embed",description:"Get a published saved form's action URL, one-line JavaScript embed, minimal native form action, and fetch example. Use this for Astro, Hugo, Jekyll, Cloudflare Pages, Netlify, GitHub Pages, or any browser integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."}},required:["formId"],additionalProperties:!1}}];var o5=[{name:"upload_image_asset",description:"Upload an image to the selected company's shared media library and return a hosted URL plus a ready-to-insert Sequenzy image block. Call this before create/update campaign, sequence, template, or transactional tools, then place the returned imageBlock in the target blocks array. Provide either filePath (local stdio MCP only) or imageBase64 (works with remote MCP when the client can supply attachment bytes), not both. PNG, JPEG, GIF, and WebP are supported up to 5MB. cropHeight with objectFit:'cover' provides a precise centered screenshot crop while displayWidthPercent keeps the image responsive.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},filePath:{type:"string",description:"Local path to a PNG, JPEG, GIF, or WebP image. Available only when the MCP server runs locally. Provide filePath or imageBase64, not both."},imageBase64:{type:"string",description:"Raw base64 image bytes or a base64 data URL. Use this for remote MCP clients that can access attachment bytes. Provide imageBase64 or filePath, not both."},filename:{type:"string",description:"File name including extension. Required with imageBase64; optional override with filePath."},contentType:{type:"string",description:"Image MIME type when it cannot be inferred from filename, such as image/png."},altText:{type:"string",description:"Accessible description stored with the asset and returned as imageBlock.alt. Use an empty string only for a decorative image."},sourceWidth:{type:"integer",minimum:1,maximum:20000,description:"Optional intrinsic source width in pixels. Provide sourceWidth and sourceHeight together when known."},sourceHeight:{type:"integer",minimum:1,maximum:20000,description:"Optional intrinsic source height in pixels. Provide sourceWidth and sourceHeight together when known."},displayWidthPercent:{type:"number",minimum:1,maximum:100,description:"Responsive image width as a percentage of the email content area. Defaults to 100."},cropHeight:{type:"integer",minimum:1,maximum:2000,description:"Optional fixed display height in pixels. With objectFit:'cover', the image is centered and cropped to this height."},objectFit:{type:"string",enum:["cover","contain"],description:"How the image fits cropHeight. Defaults to cover when cropHeight is provided. Only valid with cropHeight."},align:{type:"string",enum:["left","center","right"],description:"Image alignment. Defaults to center."}},additionalProperties:!1}}];var t5=[{name:"list_conversations",description:"List inbox conversations (email replies from subscribers). Filter by status, free-text search, or unread state, with pagination.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},status:{type:"string",enum:["open","closed","all"],description:"Filter by conversation status. Defaults to all."},search:{type:"string",description:"Free-text search across conversation subjects and participants."},unread:{type:"boolean",description:"Set true to only return conversations with unread messages."},page:{type:"number",description:"Page number. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."}}}},{name:"get_conversation",description:"Get a conversation with its full message history, subscriber details, and context.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}},{name:"reply_to_conversation",description:"Send a reply in a conversation, or add an internal note. type 'outbound' (default) emails the subscriber and requires bodyText or bodyHtml; type 'note' adds a private team-only note. Replying to a closed conversation reopens it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID to reply in."},type:{type:"string",enum:["outbound","note"],description:"Message type: outbound emails the subscriber, note is internal-only. Defaults to outbound."},subject:{type:"string",description:"Optional subject override. Defaults to the conversation subject."},bodyText:{type:"string",description:"Plain-text message body."},bodyHtml:{type:"string",description:"HTML message body."}},required:["conversationId"]}},{name:"update_conversation_status",description:"Open or close a conversation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."},status:{type:"string",enum:["open","closed"],description:"New conversation status."}},required:["conversationId","status"]}},{name:"mark_conversation_read",description:"Mark all unread inbound messages in a conversation as read.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}}];var r5=[{name:"connect_integration",description:"Connect an API-key / webhook-secret integration: polar, paddle, dodo, whop, creem, chargebee, clerk, posthog, or affonso. Check list_integration_capabilities first - each connectable provider lists its exact connectFields there. Credentials are validated against the provider where possible, stored encrypted, and never returned; payment providers queue their initial revenue backfill automatically. The response includes the webhookUrl the user must configure at the provider with the same secret - always relay it. Reconnecting an already-connected provider replaces its stored credentials. OAuth and app-install providers (Stripe, Shopify, Supabase, GitHub, WooCommerce, Meta) are rejected with guidance: their flows need a human in the dashboard. SECURITY: only pass credentials the user explicitly provided for this purpose; suggest the CLI (`sequenzy integrations connect`) or dashboard when the user prefers keeping secrets out of the conversation.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Provider to connect: polar, paddle, dodo, whop, creem, chargebee, clerk, posthog, or affonso.",enum:["polar","paddle","dodo","whop","creem","chargebee","clerk","posthog","affonso"]},apiKey:{type:"string",description:"Provider API key. Required for every provider except clerk and posthog."},webhookSecret:{type:"string",description:"Signing secret of the webhook you create at the provider, pointed at the returned webhookUrl. Required for every provider. For Chargebee, pass the webhook's basic-auth credentials as username:password."},providerAccountId:{type:"string",description:"Provider account id, required for paddle (seller ID), dodo (business ID), whop (company ID, biz_...), creem (store ID), and chargebee (site name). Polar resolves it from the API key; clerk, posthog, and affonso do not use one."},settings:{type:"object",description:"PostHog only: event delivery scope. Defaults to syncing all non-internal events.",properties:{syncAllEvents:{type:"boolean",description:"Sync every event PostHog delivers."},eventAllowlist:{type:"array",items:{type:"string"},description:"Only sync these PostHog event names. Set syncAllEvents to false when using this."}}},historyImport:{type:"object",description:"PostHog only: import the project's event history after connecting. Needs a personal API key with query read access.",properties:{region:{type:"string",enum:["us","eu"],description:"PostHog Cloud region hosting the project."},projectId:{type:"string",description:"Numeric PostHog project ID."},personalApiKey:{type:"string",description:"PostHog personal API key (phx_...)."}},required:["region","projectId","personalApiKey"]},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["provider","webhookSecret"]}},{name:"get_integration",description:"Inspect one connected integration in depth: what the provider syncs, every event it can emit and when, every matching tag rule, which sequences trigger on those events, recent integration-specific activity, and prioritized recommendations. `observedByAccount` and `accountLastSeenAt` are account-wide because event definitions can also be updated by another integration or the public events API; use the retained activity log for connection-specific delivery diagnosis. Read-only; credentials are never returned. Get the id from list_integrations.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"list_integration_capabilities",description:"Describe what Sequenzy's integration providers do, whether or not they are connected. For each provider: category, how it connects, what it syncs, every event it emits with the real-world moment that triggers it, the subscriber attributes it writes, supported actions, availability, and caveats. Use this to answer 'what would connecting Stripe give me?', to compare providers before recommending one, or to check whether an event a sequence needs actually exists for that provider. Coverage differs sharply between providers - only Shopify has storefront browse tracking, and only Stripe and Chargebee cover the full trial lifecycle - so check here rather than assuming.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Only return this provider, for example `stripe`, `shopify`, `clerk`. Omit to list every provider."},category:{type:"string",description:"Filter by category: payments, ecommerce, auth, analytics, ads, affiliate, cms, developer."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_integration_activity",description:"Read recent integration webhook and sync activity, newest first. This is the log to check when an integration reports connected but contacts or events are not appearing: each row carries the action, status, event type, matched contact, and error. Payloads are sanitized at write time, so no credentials or secrets appear here. Activity is retained for 24 hours only.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Only show activity for this integration."},provider:{type:"string",description:"Only show activity for this provider, for example `stripe`."},status:{type:"string",description:"Filter by status: received, queued, processed, skipped, or failed. Use `failed` to triage a broken integration.",enum:["received","queued","processed","skipped","failed"]},limit:{type:"number",description:"Rows to return, 1-100. Defaults to 25."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"set_integration_sync_enabled",description:"Turn a supported payment integration's future bulk imports and backfills on or off. Check get_integration.availableActions first; providers without enable_sync or disable_sync are dashboard-managed. Disabling keeps the connection, credentials, and live webhook delivery active, and requires any in-flight sync to finish first. It does not disconnect the integration. Idempotent: setting the current state succeeds with `changed: false`.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},syncEnabled:{type:"boolean",description:"True to enable sync, false to pause it."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId","syncEnabled"]}},{name:"get_integration_pixel",description:"Check whether a Shopify store's storefront tracking pixel is installed and reporting to this account. Read live from Shopify on every call, because a merchant can remove the pixel without Sequenzy hearing about it. ALWAYS check this before promising that browse abandonment, cart recovery, product views, collection views, or storefront search will work: without a live pixel those events never arrive, the sequences built on them never fire, and nothing anywhere reports an error. Returns `pixel.healthy`, the endpoint and signed configuration state, and `dependentEvents` - the event names that rely on this pixel. When `pixel.error` is null and `pixel.healthy` is false, those events are confirmed dark; an error means Shopify could not confirm their state. Fix a confirmed unhealthy state with activate_integration_pixel. Shopify only; other providers return a clear error.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Shopify integration ID from list_integrations or get_integration."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"activate_integration_pixel",description:"Install the Shopify storefront tracking pixel on the connected store, or repoint an existing one at this account. This is what turns on product views, cart activity, and browse abandonment - the data every browse-abandonment and cart-recovery sequence depends on. Idempotent: an already-live pixel returns `changed: false`. Events start flowing on the next storefront visit and nothing is backfilled for the period the pixel was off, so run it before, not after, building the sequence. If the store granted an older permission set, this fails with a message naming the reconnect step rather than silently doing nothing. Shopify only.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Shopify integration ID from list_integrations or get_integration."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"sync_integration",description:"Queue a manual re-sync of customers and revenue for a payment provider integration (Stripe, Polar, Paddle, Dodo, Creem, Chargebee, Whop). Returns immediately - poll get_integration to watch `syncStatus` and `lastSyncAt`. Fails with a conflict if a sync is already running, and with a clear error naming the dashboard for providers whose backfill is not API-triggerable (Shopify products, Supabase users, PostHog history, Affonso affiliates). Check `availableActions` on get_integration to see whether this is supported before calling.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}}];var s5=[{name:"list_landing_pages",description:"List all landing pages for a company",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list landing pages for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"get_landing_page",description:"Get landing page details, content, metrics, and URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"create_landing_page",description:"Create a draft landing page. Provide content for an exact page, or a template for generated starter content.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the landing page in. If not provided, uses the currently selected company."},name:{type:"string",description:"Landing page name. Optional; defaults to a template-specific name."},slug:{type:"string",description:"Optional URL slug. It will be normalized and made unique within the company."},template:{type:"string",description:sH},content:{type:"object",description:Ub,additionalProperties:!0}},additionalProperties:!1}},{name:"update_landing_page",description:"Edit a landing page's name, slug, or full content. Provide at least one update field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Landing page name."},slug:{type:"string",description:"Landing page URL slug. It will be normalized and made unique within the company."},content:{type:"object",description:Ub,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"duplicate_landing_page",description:"Duplicate a landing page. The copy is created as a draft with its own slug and stats, so the original keeps its published URL.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID to duplicate."},name:{type:"string",description:"Optional name for the copy. Defaults to the original name with a (copy) suffix."},slug:{type:"string",description:"Optional slug for the copy. It will be normalized and made unique within the company."}},required:["landingPageId"],additionalProperties:!1}},{name:"delete_landing_page",description:"Delete a landing page",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"publish_landing_page",description:"Publish a landing page. Optional name, slug, or content updates are saved before publishing.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before publishing."},content:{type:"object",description:Ub,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"unpublish_landing_page",description:"Unpublish a landing page and return it to draft status. Optional name, slug, or content updates are saved first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before unpublishing."},content:{type:"object",description:Ub,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"connect_landing_page_domain",description:"Connect a custom domain for published landing pages. Returns the DNS target and verification records.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Custom domain, for example pages.example.com."}},required:["domain"],additionalProperties:!1}},{name:"update_landing_page_domain_settings",description:"Update landing page domain settings. Provide domain to replace the custom domain, verify true to refresh verification, or both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Replacement custom domain."},verify:{type:"boolean",description:"Refresh domain verification after any domain update."}},additionalProperties:!1}}];var e5=[{name:"list_products",description:"List synced products (Stripe, Shopify, WooCommerce) including any attached digital delivery file. Useful before attaching a file or building a purchase sequence for a specific product. Returns one page: check pagination.total and pagination.hasMore, and page with offset to read the whole catalog.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list products for. If not provided, uses the currently selected company."},provider:{type:"string",description:"Filter by provider: stripe, shopify, woocommerce, or manual."},search:{type:"string",description:"Filter products by title."},limit:{type:"number",description:"Maximum products to return (1-100). Defaults to 50. Compare pagination.total against the products returned to detect truncation."},offset:{type:"number",description:"Number of products to skip. Defaults to 0. Use with limit to page through catalogs larger than 100."}}}},{name:"upsert_products",description:"Create or update products in the catalog (Commerce API, keyed by your productId, stored under the api provider). Use this to add products that are not synced from Stripe/Shopify/WooCommerce, then attach a deliverable file with attach_product_file and build a purchase sequence for them.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},products:{type:"array",description:"Products to create or update (max 100).",items:{type:"object",properties:{productId:{type:"string",description:"Your stable product identifier (used for upserts and order line items)."},title:{type:"string",description:"Product title."},description:{type:"string",description:"Product description."},imageUrl:{type:"string",description:"Product image URL."},url:{type:"string",description:"Product page URL."},priceCents:{type:"number",description:"Price in the smallest currency unit."},currency:{type:"string",description:"ISO currency code, e.g. USD."},inStock:{type:"boolean",description:"Whether the product is in stock."},providerCreatedAt:{type:["string","null"],description:"ISO 8601 creation time from the source catalog. Omit to preserve the stored value; pass null to clear it. Used for newest-product ranking."}},required:["productId","title"]}}},required:["products"]}},{name:"delete_product",description:"Delete a product previously pushed via upsert_products (Commerce API products only), identified by your productId.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Your productId used when upserting the product."}},required:["productId"]}},{name:"attach_product_file",description:"Attach a distributable file to a product, either by public URL or by uploading a local file (filePath, local MCP server only). After a purchase of the product, sequence emails can link to it with {{event.download.url}} and {{event.download.name}}.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."},url:{type:"string",description:"Public http(s) URL of the file to deliver. Provide url or filePath, not both."},filePath:{type:"string",description:"Local path of a file to upload and attach (PDF, ePub, ZIP, image, audio, video, or text, up to 100MB). Only available when the MCP server runs locally on this machine."},fileName:{type:"string",description:"Display name for the file (e.g. guide.pdf). Used as {{event.download.name}}."}},required:["productId"]}},{name:"remove_product_file",description:"Remove the attached distributable file from a product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."}},required:["productId"]}},{name:"sync_products",description:"Queue a sync of the Stripe product catalog into the products list. Requires an active Stripe integration with bulk sync enabled. Pass integrationId when more than one Stripe account is connected; otherwise the most recently connected enabled account is used.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},integrationId:{type:"string",description:"Stripe integration ID from list_integrations. Recommended when multiple Stripe accounts are connected."}}}}];var a5=[{name:"render_email",description:"Render a campaign, sequence email step, or template to the exact email-safe HTML that would be sent, for embedding a visual preview in an external builder or dashboard, or for checking merge tags before anyone is enrolled. Pass exactly one target: campaignId, sequenceId plus nodeId, or templateId. Without a subscriber the email renders for a sample contact, so contact-specific merge tags resolve to empty values. Check unresolvedMergeTags in the response to tell an unrecognized tag apart from one that is merely blank for this contact - both render as an empty string, so the HTML alone cannot distinguish them. Only names this render could check are called unknown. Nothing is checkable without the contact's attributes, because a bare {{plan}} reads the same attribute map as {{subscriber.plan}}, so pass subscriberId (or an inline subscriber with customAttributes) to catch typos at all. On top of that, {{event.*}} needs sample event properties in variables, since a real send fills those from the enrolling event, and {{recommendedProducts.*}} is only checkable when a stored subscriberId returns recommendations. Rendering a transactional email is checkable only when variables is passed, since its tags come from the variables of each send call and nothing marks them as such. An optional attribute this contact never had set is kept out of unknown by checking the names other contacts in the account carry, which needs the subscribers:read scope. A sequence step downstream of a create_discount step renders {{discount.*}} with that step's real terms and a clearly fake sample code; when the step is reachable by paths that do not all run the same discount step, or when a template is rendered on its own, {{discount.*}} is reported as no_value rather than as a typo. Links stay clean unless tracking is true. Per-send click redirects and the open pixel are added at send time against a real email send record, so they never appear here.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to render."},sequenceId:{type:"string",description:"Sequence ID. Requires nodeId."},nodeId:{type:"string",description:"Email step node ID from get_sequence. Requires sequenceId."},templateId:{type:"string",description:"Template ID to render."},subscriberId:{type:"string",description:"Personalize as this stored subscriber. Mutually exclusive with subscriber. The rendered HTML then carries that subscriber's details, so this needs the subscribers:read scope as well."},subscriber:{type:"object",description:"Personalize as an ad-hoc contact that need not exist in the account. Mutually exclusive with subscriberId.",properties:{email:{type:"string",description:"Contact email address."},firstName:{type:"string",description:"Contact first name."},lastName:{type:"string",description:"Contact last name."},customAttributes:{type:"object",description:"Custom attributes used by merge tags and blocks.",additionalProperties:!0}},required:["email"]},variables:{type:"object",description:"Extra merge variables layered over the contact's attributes.",additionalProperties:!0},locale:{type:"string",description:"Force a localization locale instead of deriving it from the contact."},variantId:{type:"string",description:"Render a specific A/B test variant of the campaign or sequence step."},tracking:{type:"boolean",description:"Apply the company's auto-UTM link decoration as a real send would. Defaults to false so the preview shows the author's clean URLs."}},required:[]}}];var J4={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."}},w3={name:{type:"string",description:"Goal name."},description:{type:["string","null"],description:"Optional goal description."},triggerType:{type:"string",enum:["event","attribute_change"],description:"Conversion signal type. Defaults to event when creating."},triggerEventName:{type:["string","null"],description:"Required event name for event goals."},attributePath:{type:["string","null"],description:"Subscriber attribute path required for attribute_change goals."},attributeCondition:{type:["string","null"],enum:["changed","changed_to","changed_from_to",null],description:"How the subscriber attribute must change."},attributeValue:{type:["string","null"],description:"Target value for changed_to or changed_from_to."},attributePreviousValue:{type:["string","null"],description:"Previous value required for changed_from_to."},eventPropertyName:{type:["string","null"],description:"Optional event property whose numeric value is tracked."},eventPropertyLabel:{type:["string","null"],description:"Display label for the tracked event property."},attributionWindowHours:{type:"integer",minimum:1,maximum:720,description:"Attribution window in whole hours."},isActive:{type:"boolean",description:"Whether conversion tracking is active for this goal. Defaults to true when creating."}},b3=[{name:"list_sequence_goals",description:"List persisted conversion goals attached to one sequence in the dashboard.",inputSchema:{type:"object",properties:J4,required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence_goal",description:"Create a persisted event or subscriber-attribute conversion goal for one sequence. Event goals (the default triggerType) require triggerEventName; attribute_change goals require attributePath. This is distinct from create_sequence.goal, which is only an AI content prompt.",inputSchema:{type:"object",properties:{...J4,...w3},required:["sequenceId","name"],additionalProperties:!1}},{name:"update_sequence_goal",description:"Update a persisted sequence conversion goal, including its signal, attribution window, or active state.",inputSchema:{type:"object",properties:{...J4,goalId:{type:"string",description:"Sequence goal ID."},...w3},required:["sequenceId","goalId"],additionalProperties:!1}},{name:"delete_sequence_goal",description:"Delete one persisted sequence conversion goal.",inputSchema:{type:"object",properties:{...J4,goalId:{type:"string",description:"Sequence goal ID."}},required:["sequenceId","goalId"],additionalProperties:!1}}];var QW={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence with an inbound_webhook trigger."}},$3=[{name:"get_sequence_inbound_webhook",description:"Read the usable URL, mapping, sample payload, and setup status for a sequence inbound webhook.",inputSchema:{type:"object",properties:QW,required:["sequenceId"],additionalProperties:!1}},{name:"configure_sequence_inbound_webhook",description:"Create or update the secret endpoint attached to a sequence inbound_webhook trigger. On first setup, omitted mapping/sample inputs apply the selected catalog or custom integration defaults; on later calls, omitted inputs keep the saved values, so a captured sample survives mapping-only updates. Use clearFieldMapping to return to pending setup and clearSamplePayload to drop the saved sample.",inputSchema:{type:"object",properties:{...QW,fieldMapping:{type:"object",properties:{email:{type:"string"},firstName:{type:"string"},lastName:{type:"string"},properties:{type:"object",additionalProperties:{type:"string"}}},required:["email"],additionalProperties:!1},samplePayload:{type:"object",description:"Representative raw webhook payload for mapping setup.",additionalProperties:!0},clearFieldMapping:{type:"boolean",description:"Set true to clear the saved mapping and return the endpoint to pending_setup."},clearSamplePayload:{type:"boolean",description:"Set true to clear the saved sample payload."}},required:["sequenceId"],additionalProperties:!1}},{name:"rotate_sequence_inbound_webhook_secret",description:"Rotate the inbound webhook secret and return a new URL. The previous URL stops working immediately.",inputSchema:{type:"object",properties:QW,required:["sequenceId"],additionalProperties:!1}}];var W3=[{name:"list_sequences",description:"List all email sequences (automations). Read effectiveStatus (draft, live, enrollment_paused, paused, archived) to know whether a sequence is running: status alone reads `active` even when new enrollments are paused, and the legacy triggerConfig.active flag is not used by the runtime.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."},status:{type:"string",enum:["draft","active","paused","archived"],description:"Optional dashboard status filter."},search:{type:"string",description:"Case-insensitive search across sequence name and description."},labels:{type:"array",items:{type:"string"},description:"Return sequences assigned any of these dashboard label names."},limit:{type:"number",description:"Page size from 1 to 100. When limit and offset are both omitted, every sequence is returned."},offset:{type:"number",description:"Zero-based result offset."}}}},{name:"get_sequence",description:"Get sequence details, editable step content, and graph topology. Read effectiveStatus (draft, live, enrollment_paused, paused, archived) to know whether a sequence is running: status alone reads `active` even when new enrollments are paused, and the legacy triggerConfig.active flag is not used by the runtime. Each sequence.nodes item includes id, nodeType, current config, updatedAt, and updateHints with its editable/managed fields and ready-to-return expectedUpdatedAt token for update_sequence_node/update_sequence_nodes. The response also includes sequence.edges and graphRevision for safe edit_sequence_graph calls, plus sequence.emails with each email step's nodeId, linked emailId, subject, previewText, emailPreset (the per-email Style > Format for native blocks, including emails with supported custom HTML blocks; null when the entire email is standalone raw HTML), and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"],additionalProperties:!1}},{name:"list_sequence_enrollments",description:"List the individual contacts currently enrolled in a sequence, with the node each one is sitting on. Use this when get_sequence_stats gives you enrollmentCounts and you need the actual subscribers behind a number, such as everyone waiting at one step. Filter by currentNodeId (take the ID from get_sequence_stats enrollmentCounts.byCurrentNode or get_sequence nodes), status, subscriberId, or email, and page with limit/offset to export the full list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be listed."},currentNodeId:{type:"array",items:{type:"string"},description:"Only return enrollments currently sitting on these sequence node IDs."},status:{type:"array",items:{type:"string",enum:["active","waiting","completed","failed","cancelled"]},description:"Enrollment statuses to include. Defaults to active and waiting, which is every contact still moving through the sequence."},subscriberId:{type:"array",items:{type:"string"},description:"Only return enrollments for these subscriber IDs. Useful for checking where specific contacts stand."},email:{type:"string",description:"Only return enrollments for this exact email address (case-insensitive)."},sort:{type:"string",enum:["enrolled_at_desc","enrolled_at_asc","wait_until_asc","wait_until_desc"],description:"Result order. Defaults to enrolled_at_desc (most recently enrolled first). Use wait_until_asc to see who resumes next."},limit:{type:"number",description:"Enrollments per page, 1-500. Defaults to 50. Use the maximum when exporting."},offset:{type:"number",description:"Number of enrollments to skip. Page until pagination.hasMore is false."}},required:["sequenceId"],additionalProperties:!1}},{name:"send_sequence_test_email",description:"Queue a real test send for one saved email step in a sequence. Call get_sequence first and pass the target email step's nodeId. Accepts 1-10 reviewer email addresses and returns one durable emailSendId per recipient for get_email_send delivery inspection. The sequence is not enabled and no subscribers are enrolled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID containing the saved email step."},nodeId:{type:"string",description:"Email step nodeId from get_sequence. The node must belong to sequenceId."},recipients:{type:"array",minItems:1,maxItems:10,items:{type:"string",format:"email"},description:"One to ten internal reviewer email addresses. Duplicate addresses are sent only once."}},required:["sequenceId","nodeId","recipients"],additionalProperties:!1}},{name:"create_sequence",description:"Create and persist a disabled draft email sequence, follow-up series, drip campaign, nurture flow, or automation workflow. For natural-language content, provide goal and emailCount. Use explicit steps for finished caller-supplied content, exact workflows, or migrations. Configure trigger plus its relevant field, such as listId, tagName, segmentId, or eventName. Supports email and SMS steps, delays and date waits, actions that dynamically create a provider discount/code (later emails print it with {{discount.code}}), subscriber updates, event filters, enrollment rules, sending windows, and stop conditions. The saved draft appears in list_sequences. Never call enable_sequence unless the user explicitly asks to activate it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail; omit it when using senderProfileId, which already carries its own display name."},senderProfileId:{type:"string",description:"Existing sender profile ID (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},replyProfileId:{type:"string",description:"Existing reply profile ID (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},description:{type:"string",description:"Optional sequence description shown in the dashboard."},userCancellable:{type:"boolean",description:"Whether subscribers may cancel their own active enrollment."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses blind-copied on every email in the sequence (max 10)."},labels:{type:"array",items:{type:"string"},description:"Dashboard label names to assign. Missing labels are created."},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inbound_webhook","inactivity","frequency"],description:"Trigger type: contact_added, tag_added, segment_entered, event_received, inbound_webhook, inactivity, or frequency. Defaults to contact_added for a blank dashboard-compatible draft."},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},stopOnSegmentExit:{type:"boolean",description:"For segment_entered triggers, cancel active enrollments when the contact leaves the segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inbound_webhook, inactivity, and frequency triggers)"},integrationSlug:{type:"string",description:"Catalog integration slug for inbound_webhook, for example cal-com."},integrationEventKey:{type:"string",description:"Catalog integration event key for inbound_webhook."},customIntegration:{type:"object",description:"Custom inbound webhook integration descriptor with name, setupInstructions, samplePayload, and fieldMapping.",properties:{name:{type:"string"},setupInstructions:{type:"string"},samplePayload:{type:"object",additionalProperties:!0},fieldMapping:{type:"object",additionalProperties:!0},docsUrl:{type:"string"},suggestedProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},path:{type:"string"},description:{type:"string"}},required:["name","path","description"]}}},required:["name","setupInstructions","samplePayload","fieldMapping"]},propertyFilters:{type:"array",description:"Optional filters for event_received or inbound_webhook triggers. The sequence starts only when all filters match. Max 10.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},emailStyle:{type:"string",enum:["visual","plain"],description:"Style for AI-generated emails: 'visual' (designed, with heroes/imagery/rich sections) or 'plain' (personal, text-first notes with a single button). Only applies to goal-based AI generation. Defaults to the company's saved preference when omitted."},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Defaults to 'unlimited', which re-enrolls a subscriber every time the trigger fires again - for a tag_added drip that means re-applying the tag sends the whole series a second time, so set 'one_time' unless repeat runs are wanted. Exception: ecommerce.back_in_stock and ecommerce.replenishment_due triggers default to 'matching_field' so each product is notified separately; leave those alone unless the user asks otherwise. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value. Changeable later with update_sequence."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},sendingWindow:r6,stopCondition:{type:"object",description:"Optional explicit auto-stop condition, re-evaluated before every step including the first one. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'added_to_list', value: 'list_123' } when they join a list, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop. The negative forms are audience guards rather than lifecycle stops: { type: 'does_not_have_tag', value: 'allowlist' } and { type: 'removed_from_list', value: 'list_123' } cancel the run before any step sends unless the subscriber carries that tag or list membership. That is how you restrict a live event or segment trigger to a chosen set of contacts without editing the graph, for example for a first pass on a production trigger or a phased rollout. Guarded-out contacts still enroll and are then cancelled at the trigger node, so they appear as cancellations there rather than in the active or waiting enrollment counts. Clearing the guard does not retry them: nothing re-enrolls them, so they only receive the sequence if the trigger fires for them again, which one-shot triggers never do, and on the one_time enrollment mode a repeated trigger is ignored too because enrollment is blocked by the existence of any earlier run rather than by its outcome. Guard a duplicate sequence and leave the real one ungated, or enroll the missed contacts afterwards with enroll_subscribers_in_sequence, which skips the one_time check.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type. has_tag, added_to_list, entered_segment, field_changed, and event_received stop the run once the thing happens. does_not_have_tag and removed_from_list stop the run whenever the subscriber lacks that tag or list membership, so they act as a required-tag or required-list allowlist for everyone the trigger enrolls."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. For the does_not_have_tag and removed_from_list guards this is the tag or list a subscriber must have to keep receiving the sequence. Use null or omit for type 'none'."},matchConfig:{type:["object","null"],description:"Optional dashboard-compatible match config: event_property with rules[{entryFieldPath,eventFieldPath}] for event_received, or field_value with operator/value for field_changed.",additionalProperties:!0}},required:["type"]},steps:{type:"array",description:"Explicit sequence steps. Omit type for email steps, use type: 'sms' for SMS, type: 'create_discount' for a dynamic discount, or type: 'update_subscriber' with nodeType: 'action_update_attributes' and config to copy trigger-event values such as {{event.plan}} into subscriber data.",items:{type:"object",properties:{type:{type:"string",enum:["email","sms","create_discount","discount","update_subscriber"],description:"Step type. Omit or use 'email' for email content. Use 'sms' to send a text message, 'create_discount' to generate a code, or 'update_subscriber' to copy trigger data into the subscriber."},nodeType:{type:"string",enum:["action_email","action_sms","action_create_discount","action_update_attributes"],description:"Internal step type. Use action_update_attributes with config for Update Subscriber steps."},config:U0,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:z0,items:{type:"object"}},html:{type:"string",description:`HTML content for email steps. Use this for imported provider HTML. ${Hw}`},isTransactional:{type:"boolean",description:"Send this email as transactional and omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Addresses CC'd on this email step."},bccEmails:{type:"array",items:{type:"string"},description:"Addresses BCC'd on this email step in addition to sequence BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string",description:"Filename shown in the recipient's email client. Event merge tags are supported, for example file-{{event.order_id}}.pdf."},path:{type:"string",description:"Public HTTPS URL or event-backed URL template such as {{event.file_url}}; resolved per enrollment and fetched at send time."}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). Paths may use {{event.*}} values from the event that enrolled the subscriber; the resolved public URL is validated and fetched at send time."},...Zb,text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:B0,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:D0,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:`Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.${o6}`,properties:{label:{type:"string",description:"Builder label for the discount step."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use 'stripe' to dynamically create a Stripe coupon plus promotion code, or 'shopify' to dynamically create a Shopify Admin discount code. Defaults to 'stripe' when omitted."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional display name for each dynamically generated provider discount."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe","shopify"],description:"Legacy top-level discount provider. Prefer discount.provider. Supports 'stripe' and 'shopify'."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name"]}}];var Q3=[{name:"update_sequence",description:"Update an existing sequence: both its settings and its steps. Sequence-level settings live directly on this tool - name, description, labels, trigger (with its trigger-specific field), enrollmentMode plus enrollmentFieldPath, enrollmentPaused, userCancellable, stopCondition, sendingWindow, bccEmails, and the sender/reply identity. This is the only way to change enrollmentMode after create_sequence, so use it to move a tag- or event-triggered sequence off the default 'unlimited' re-entry to 'one_time' or 'matching_field'. To target a specific existing step, use IDs returned by get_sequence. The emails/steps arrays edit email steps, smsSteps edits SMS steps, and subscriberUpdateSteps replaces the config of action_update_attributes steps. To insert new linear steps, use insertSteps with an afterNodeId from get_sequence; omit afterNodeId only to append to an unambiguous linear tail. Deleting a step immediately moves parked recipients to its unique surviving successor, or completes them when no successor remains; inspect migratedRecipientCount and completedRecipientCount in the returned sequence. For active sequences, structural changes such as insertSteps or branch require confirmStructuralChange:true after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},description:{type:"string",description:"Sequence description shown in the dashboard."},userCancellable:{type:"boolean",description:"Whether subscribers may cancel their own active enrollment."},labels:{type:"array",items:{type:"string"},description:"Replace dashboard labels by name. Missing labels are created; [] clears labels."},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inbound_webhook","inactivity","frequency"],description:"Atomically replace the existing dashboard trigger. Include the fields required by the new trigger type. Active sequences also require confirmLiveChange:true."},listId:{type:"string",description:"List ID for a contact_added trigger replacement."},tagName:{type:"string",description:"Tag name required for a tag_added trigger replacement."},segmentId:{type:"string",description:"Saved segment ID required for a segment_entered trigger replacement."},stopOnSegmentExit:{type:"boolean",description:"For segment_entered, stop active enrollments when the subscriber leaves the segment."},eventName:{type:"string",description:"Event name required for event_received, inbound_webhook, inactivity, and frequency trigger replacements."},propertyFilters:{type:"array",description:"Optional event-property filters for event_received or inbound_webhook.",items:{type:"object",properties:{path:{type:"string"},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"]},value:{description:"Scalar comparison value, or an array for one_of."}},required:["path","operator"],additionalProperties:!1}},integrationSlug:{type:"string",description:"Catalog integration slug for inbound_webhook."},integrationEventKey:{type:"string",description:"Catalog integration event key for inbound_webhook."},customIntegration:{type:"object",description:"Typed custom inbound webhook descriptor used instead of a catalog integration.",properties:{name:{type:"string"},setupInstructions:{type:"string"},samplePayload:{type:"object",additionalProperties:!0},fieldMapping:{type:"object",properties:{email:{type:"string"},firstName:{type:"string"},lastName:{type:"string"},properties:{type:"object",additionalProperties:{type:"string"}}},required:["email"],additionalProperties:!1},docsUrl:{type:"string"},suggestedProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},path:{type:"string"},description:{type:"string"}},required:["name","path","description"],additionalProperties:!1}}},required:["name","setupInstructions","samplePayload","fieldMapping"],additionalProperties:!1},inactiveDays:{type:"number",description:"Days without event activity required for an inactivity trigger."},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"Baseline for subscribers who have never produced the inactivity event."},minCount:{type:"number",description:"Minimum event count for a frequency trigger."},timeWindowDays:{type:"number",description:"Frequency trigger lookback window in days."},fromEmail:{type:"string",description:"Set the From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:"Display name for a newly created sender profile. Requires fromEmail; omit it when using senderProfileId, which already carries its own display name."},senderProfileId:{type:"string",description:"Set an existing sender profile (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},replyProfileId:{type:"string",description:"Set an existing reply profile (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},enrollmentPaused:{type:"boolean",description:"Set true to stop new enrollments for an active sequence while current recipients continue. Set false to resume new enrollments. The sequence must already be active."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence. Required for insertSteps or branch when the sequence is active; not needed for content-only email edits."},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms replacing the trigger of an active sequence. Required with trigger when the sequence is active."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. Use this to move an existing sequence off the default 'unlimited', which re-enrolls a subscriber every time the trigger fires again. 'matching_field' is only valid for event-based sequence triggers."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Omit to leave unchanged. Use clearEnrollmentFieldPath to clear it."},clearEnrollmentFieldPath:{type:"boolean",description:"Set true to clear enrollmentFieldPath without sending a nullable schema value."},sendingWindow:r6,clearSendingWindow:{type:"boolean",description:"Set true to remove the sequence sending window. Do not provide this together with sendingWindow."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses that receive a blind copy of every email this sequence sends, such as a customer support inbox (max 10). Omit to leave unchanged. Use clearBccEmails to remove them."},clearBccEmails:{type:"boolean",description:"Set true to remove the sequence BCC addresses. Do not provide this together with bccEmails."},stopCondition:{type:"object",description:"Update the sequence auto-stop condition, which is re-evaluated before every step including the first one. Example: { type: 'has_tag', value: 'customer' } ends the sequence when the subscriber has that tag. Use { type: 'entered_segment', value: 'segment_123' } to stop when they enter a segment, { type: 'field_changed', value: 'plan' } to stop when a subscriber field changes, { type: 'added_to_list', value: 'list_123' } to stop when they join a list, or { type: 'none', value: null } to clear it. The negative forms are audience guards rather than lifecycle stops: { type: 'does_not_have_tag', value: 'allowlist' } and { type: 'removed_from_list', value: 'list_123' } cancel the run before any step sends unless the subscriber carries that tag or list membership. That is how you restrict a live event or segment trigger to a chosen set of contacts without editing the graph, for example for a first pass on a production trigger or a phased rollout. Guarded-out contacts still enroll and are then cancelled at the trigger node, so they appear as cancellations there rather than in the active or waiting enrollment counts. Clearing the guard does not retry them: nothing re-enrolls them, so they only receive the sequence if the trigger fires for them again, which one-shot triggers never do, and on the one_time enrollment mode a repeated trigger is ignored too because enrollment is blocked by the existence of any earlier run rather than by its outcome. Guard a duplicate sequence and leave the real one ungated, or enroll the missed contacts afterwards with enroll_subscribers_in_sequence, which skips the one_time check.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type. has_tag, added_to_list, entered_segment, field_changed, and event_received stop the run once the thing happens. does_not_have_tag and removed_from_list stop the run whenever the subscriber lacks that tag or list membership, so they act as a required-tag or required-list allowlist for everyone the trigger enrolls."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. For the does_not_have_tag and removed_from_list guards this is the tag or list a subscriber must have to keep receiving the sequence."},matchConfig:{type:["object","null"],description:"Optional event_property or field_value match config used by dashboard stop-condition matching.",additionalProperties:!0}},required:["type"]},branch:{type:"object",description:"Insert an if/else branch into an existing sequence. Use get_sequence first to choose afterNodeId and existing target nodes. Each conditional path can provide new steps, targetNodeId, or both; the else path uses elseSteps and/or elseTargetNodeId. A target may be the completion node. Empty paths require allowEmptyPaths:true. Conditions support tag presence/absence, lists, saved segments, events, clicked links, and field comparisons. Use activityScope for event_received and link_clicked checks.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert the branch after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails."},label:{type:"string",description:"Optional branch node label."},branches:{type:"array",description:"Conditional branches evaluated in order. Each path can create steps, route directly to an existing targetNodeId, or do both. An else fallback is created automatically.",items:o9},elseSteps:{type:"array",description:"Optional new steps inside the else fallback path.",items:Vb},elseTargetNodeId:{type:"string",description:"Optional existing node to route the else path to. Use a node ID from get_sequence, including the completion node. If elseSteps are also provided, they run before this target."},allowEmptyPaths:{type:"boolean",description:"Set true only when intentionally creating UI placeholders. A path with targetNodeId is already explicit and does not need this flag."}},required:["afterNodeId","branches"]},insertSteps:{type:"object",description:"Insert one or more new linear steps into an existing sequence. Use get_sequence first, then pass afterNodeId to insert after a specific node. If afterNodeId is omitted, the steps are appended only when the sequence has exactly one linear tail. Inserted email steps require subject plus blocks or html.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},steps:{type:"array",description:"New steps to insert. Supports emails, delays, create_discount actions, webhooks, and other supported sequence path node types.",items:Vb}},required:["steps"]},emails:{type:"array",description:"Updated existing sequence emails. If you omit emailId/nodeId, items are matched by existing step order. This field does not create new steps; use insertSteps for insertion and include delay on inserted email steps when a timer is needed.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:`Updated HTML content for imported provider markup. ${Hw}`},htmlContent:{type:"string",description:`Alias for html for imported provider markup. ${Hw}`},emailPreset:{type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks, including emails that contain supported custom HTML blocks. Minimal removes the company logo and uses the simple footer; branded restores the branded chrome. Does not change the company default. Not supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:`${F1}${t6}`,items:{type:"object"}},isTransactional:{type:"boolean"},ccEmails:{type:"array",items:{type:"string"}},bccEmails:{type:"array",items:{type:"string"}},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time. Pass [] to remove all attachments."},...Zb}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules, and only edits existing email steps. Use insertSteps to create new steps.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:`Updated HTML content for imported provider markup. ${Hw}`},htmlContent:{type:"string",description:`Alias for html. ${Hw}`},emailPreset:{type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks, including emails that contain supported custom HTML blocks. Minimal removes the company logo and uses the simple footer; branded restores the branded chrome. Does not change the company default. Not supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:`${F1}${t6}`,items:{type:"object"}},isTransactional:{type:"boolean"},ccEmails:{type:"array",items:{type:"string"}},bccEmails:{type:"array",items:{type:"string"}},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time. Pass [] to remove all attachments."},...Zb}}},smsSteps:{type:"array",description:"Content updates for existing SMS steps, targeted by nodeId (an action_sms node from get_sequence.sequence.nodes). Content-only edits - use insertSteps to create new SMS steps.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_sms node ID. Required."},text:{type:"string",description:"Replacement plain-text message body. Merge tags like {{FIRST_NAME}} work. Provide text or blocks, not both."},blocks:{type:"array",items:{type:"object"},description:"Replacement SMS content blocks (text + image subset)."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable MMS image URLs. Only valid together with text."},label:{type:"string",description:"Updated display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"Updated behavior when the contact can't receive SMS."}},required:["nodeId"]}},subscriberUpdateSteps:{type:"array",description:"Full config replacements for existing Update Subscriber steps, targeted by action_update_attributes nodeId.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_update_attributes node ID."},config:U0},required:["nodeId","config"]}}},required:["sequenceId"]}},{name:"update_sequence_node",description:"Patch one existing sequence node in place. Call get_sequence first, select sequence.nodes[].id, inspect nodeType/config, and pass that node's updatedAt as expectedUpdatedAt. This supports every stored sequence node type, including delays, email/SMS content, actions, conditions, branches without topology changes, webhooks, and trigger settings. Delay example: changes:{ delay:{ days:7 } }. For a direct text-forward email, use changes:{ emailPreset:'minimal' } on its action_email node; this changes only that linked email's Style > Format. The update is type-aware and preserves fields you omit. It cannot change nodeType, managed linked-resource IDs, or graph topology; use edit_sequence_graph for structural work. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamp; the new delay applies when recipients reach the node in the future.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},nodeId:s6.properties.nodeId,changes:x9,expectedUpdatedAt:s6.properties.expectedUpdatedAt,confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing a node in an active sequence."}},required:["sequenceId","nodeId","changes","expectedUpdatedAt"],additionalProperties:!1}},{name:"update_sequence_nodes",description:"Atomically patch multiple existing sequence nodes. Call get_sequence first and include each node's id plus its updatedAt as expectedUpdatedAt. Every patch follows update_sequence_node's type-aware rules. Either every node update commits or none do, making this the preferred tool for changes such as replacing all 5-minute delays with 7-day delays or setting several action_email nodes to changes:{ emailPreset:'minimal' } without changing the company theme. A node may appear only once. It cannot change node types or graph topology. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamps.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},updates:{type:"array",description:"Non-empty node patches. Each nodeId may appear only once.",items:s6},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing nodes in an active sequence."}},required:["sequenceId","updates"],additionalProperties:!1}},{name:"edit_sequence_graph",description:"Restructure an existing sequence graph using node IDs, edges, and graphRevision from get_sequence. move_node repositions one non-split step; duplicate_node creates an independent copy; delete_node safely splices a node and immediately moves parked recipients to its unique surviving successor (or completes them when none remains); replace_edges replaces the complete topology. The returned sequence reports migratedRecipientCount and completedRecipientCount. Always call get_sequence immediately before this tool and pass its graphRevision. Active sequences require confirmStructuralChange:true after the user confirms live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},action:{type:"string",enum:["move_node","delete_node","duplicate_node","replace_edges"],description:"Graph operation."},graphRevision:{type:"string",description:"Exact graphRevision returned by the latest get_sequence call. The edit is rejected if the graph changed since then."},nodeId:{type:"string",description:"Existing node to move, duplicate, or delete. Unused by replace_edges."},afterNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately after this node. The target must have at most one outgoing path. Provide exactly one of afterNodeId or beforeNodeId."},beforeNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately before this node. All incoming paths converge through the moved/copied node, which is useful for placing a step below a branch. Provide exactly one of beforeNodeId or afterNodeId."},edges:{type:"array",description:"Complete replacement topology from get_sequence.sequence.edges. The returned edge array is already normalized for this input and can be reused directly. Required for replace_edges and when deleting a split node. Preserve each branch edge's condition.branchId. Do not include edges that reference a deleted node.",items:{type:"object",properties:{sourceNodeId:{type:"string"},targetNodeId:{type:"string"},condition:{type:"object",description:"Optional edge routing condition. Preserve condition.branchId on edges leaving logic_branch nodes."}},required:["sourceNodeId","targetNodeId"],additionalProperties:!1}},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."}},required:["sequenceId","action","graphRevision"],additionalProperties:!1}},{name:"insert_sequence_step",description:"Insert one dashboard-compatible typed step into an existing sequence: email, SMS, delay/date wait, discount (later emails print the generated code with {{discount.code}}), subscriber update, tag/list action, outbound webhook, condition gate, wait-for-event, or wired If/Else branch. Use get_sequence first and pass afterNodeId. Branch paths can target existing nodes, including completion. For active sequences, confirm the structural change first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},type:{type:"string",enum:["email","sms","delay","create_discount","update_subscriber","add_tag","remove_tag","add_to_list","remove_from_list","webhook","condition","logic_wait_for_event","logic_branch"],description:"Dashboard step type. Defaults to email."},afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."},name:{type:"string",description:"Optional email template and step name."},subject:{type:"string",description:"Email subject for the new step. Required for email steps; not used for SMS steps."},previewText:{type:"string",description:"Optional email preview text for the new step."},blocks:{type:"array",description:z0,items:{type:"object"}},html:{type:"string",description:`HTML content for an imported provider step. Provide either html or blocks, not both. ${Hw}`},isTransactional:{type:"boolean",description:"Email only: omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses CC'd on this step."},bccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses BCC'd in addition to sequence-level BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"Email only: URL-backed file attachments (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time."},senderProfileId:{type:"string",description:"Email steps only: sender profile for the new step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"Email steps only: From address for the new step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Email steps only: display name override for the new step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Email steps only: reply profile for the new step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Email steps only: Reply-To address for the new step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Email steps only: display name for a newly created reply profile. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},label:{type:"string",description:"Display label for SMS, wait-for-event, or branch steps."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},config:{...U0,description:"update_subscriber only: typed subscriber profile/custom-attribute changes."},tagId:{type:"string",description:"Tag ID for tag actions or tag conditions."},tagName:{type:"string",description:"Tag name for tag actions or tag conditions; missing definitions are created."},listId:{type:"string",description:"List ID for list actions or in_list conditions."},listName:{type:"string",description:"Optional cached list display name for list actions."},url:{type:"string",description:"webhook only: destination HTTPS URL called when a subscriber reaches this step. Supports merge tags like {{email}} and {{event.order_id}}."},method:{type:"string",enum:["POST","GET","PUT","PATCH","DELETE"],description:"webhook only: HTTP method. Defaults to POST."},headers:{type:"object",description:"webhook only: optional string-valued request headers. Values support merge tags. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},body:{type:"string",description:'webhook only: optional JSON body template for POST/PUT/PATCH. Must be valid JSON as written, with merge tags inside quoted string values ({"email": "{{email}}"}); a tag in a bare value position is rejected. Tags are resolved at execution time; when omitted, the default payload with subscriber and sequence context is sent.'},resultKey:{type:"string",description:"webhook only: when set, the HTTP response is saved and later email steps can reference it via {{webhooks.KEY.data.field}} merge tags. Must start with a letter; letters, numbers, underscores; max 64 chars."},onError:{type:"string",enum:["continue","exit","fail"],description:"webhook only: behavior when the request fails. continue proceeds to the next step, exit ends the sequence for the subscriber, fail marks the enrollment failed (default)."},segmentId:{type:"string",description:"Segment ID for in_segment conditions."},segmentName:{type:"string",description:"Optional cached segment display name."},conditionType:{type:"string",enum:["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"condition only: condition evaluated before continuing."},linkUrl:{type:"string"},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"]},fieldName:{type:"string"},fieldValue:{type:"string"},delay:B0,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:D0,eventName:{type:"string",description:"logic_wait_for_event only: event to wait for, for example email.replied."},timeoutDays:{type:"number",description:"logic_wait_for_event only: maximum wait in whole days from 1 to 365. Defaults to 7."},timeoutAction:{type:"string",enum:["continue","exit"],description:"logic_wait_for_event only: continue to the next node or exit the sequence when the timeout is reached. Defaults to continue."},discount:{type:"object",description:"create_discount only: provider discount configuration.",additionalProperties:!0},provider:{type:"string",enum:["stripe","shopify"]},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"},branches:{type:"array",description:"logic_branch only: ordered conditional paths. Each path may provide targetNodeId, steps, or both.",items:o9},elseSteps:{type:"array",description:"logic_branch only: optional new steps for the else path.",items:Vb},elseTargetNodeId:{type:"string",description:"logic_branch only: existing node for the else path, such as the original follow-up node or completion node."},allowEmptyPaths:{type:"boolean",description:"logic_branch only: set true only to create empty dashboard placeholders. Explicit target nodes do not require it."}},required:["sequenceId"],additionalProperties:!1}},{name:"enable_sequence",description:"Enable/activate a sequence. IMPORTANT: Only call this when the user EXPLICITLY asks to enable or activate a sequence. Never enable sequences automatically after creation - the user must review the content first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"disable_sequence",description:"Disable/freeze a sequence. This blocks new enrollments and holds current recipients until the sequence is enabled again. To only stop new enrollments while current recipients continue, use pause_sequence_enrollments.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"duplicate_sequence",description:"Create an independent draft copy of a sequence, including its graph, email templates, and sequence A/B tests. The original is not changed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to copy."},name:{type:"string",description:"Optional name for the copy. Defaults to the original name plus (Copy)."}},required:["sequenceId"]}},{name:"archive_sequence",description:"Archive a sequence and stop new enrollments. Archived sequences remain available in the dashboard's archive.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to archive."}},required:["sequenceId"]}},{name:"unarchive_sequence",description:"Restore an archived sequence as a disabled draft so it can be reviewed before activation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Archived sequence ID to restore."}},required:["sequenceId"]}},{name:"pause_sequence_enrollments",description:"Stop new enrollments for an active sequence while current recipients continue through the sequence. This matches the dashboard 'Stop new enrollments' control and does not freeze current recipients.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"resume_sequence_enrollments",description:"Resume new enrollments for an active sequence whose enrollment gate was paused. Use enable_sequence instead for a fully disabled/frozen sequence.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"enroll_subscribers_in_sequence",description:"Manually enroll subscribers in a sequence by email address or subscriber ID. Maximum 500 total targets per call across emails and subscriberIds. Only active subscribers are enrolled: unknown emails are returned in `notFound`, while inactive, unavailable, and already actively enrolled subscribers are counted in `skipped`. By default enrollment starts at the first step after the trigger; pass targetNodeId to start at a specific step.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to enroll subscribers in."},emails:{type:"array",items:{type:"string"},description:"Email addresses of subscribers to enroll. Combined with subscriberIds, maximum 500 total targets per call."},subscriberIds:{type:"array",items:{type:"string"},description:"Subscriber IDs to enroll. Combined with emails, maximum 500 total targets per call."},targetNodeId:{type:"string",description:"Optional node ID to start enrollment at. Use a non-trigger nodeId from get_sequence. Defaults to the first step after the trigger."}},required:["sequenceId"]}},{name:"cancel_sequence_enrollments",description:"Cancel active/waiting enrollments in one sequence. Provide sequenceId and exactly one target: cancelAll to drain every active/waiting enrollment (use this to fully stop a live sequence instead of only freezing enrollment), subscriberIds for a specific batch, subscriberId for one subscriber, or fieldValues to match stored entry event properties. Every bulk target defaults to dryRun, so pass dryRun false to actually cancel. Bulk cancellation is capped per call: while the response reports remainingCount above zero, call again with the same arguments until it reaches zero.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be cancelled."},cancelAll:{type:"boolean",description:"Cancel every active/waiting enrollment in the sequence, regardless of how contacts entered it. Use this when segment-triggered enrollments expose no shared entry field value. Defaults to dryRun; pass dryRun false to apply."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide exactly one target."},subscriberIds:{type:"array",items:{type:"string"},description:"Up to 500 subscriber IDs to cancel in this sequence. IDs that do not resolve come back in target.notFoundSubscriberIds. Provide exactly one target."},fieldPath:{type:"string",description:"Dot-path inside the token's stored entry event properties, such as order.id or event.id. Optional when the sequence has enrollmentFieldPath configured."},fieldValues:{type:"array",items:{type:"string"},description:"Entry field values to match. Cancels all active/waiting enrollments in the sequence whose entry field value is in this list. Provide exactly one target."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. cancelAll, subscriberIds, and fieldValues default to dryRun unless explicitly false; a single subscriberId cancels immediately."},reason:{type:"string",description:"Optional cancellation reason stored on matched enrollment tokens."}},required:["sequenceId"],additionalProperties:!1}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}}];var Tj={type:"object",properties:{email:{type:"string",description:"Subscriber email address. Optional when the record has a phone - such rows import as phone-only (SMS) contacts."},externalId:{type:"string",description:"Customer-owned subscriber ID"},firstName:{type:"string"},lastName:{type:"string"},phone:{type:"string",description:"Phone number. National-format values use the batch defaultPhoneCountry."},status:{type:"string",enum:["active","unsubscribed","bounced"]},tags:{type:"array",items:{type:"string"}},customAttributes:{type:"object",description:"CRM fields and other custom attributes. Values may be strings, numbers, booleans, arrays of those scalar values, or null.",additionalProperties:!0},createdAt:{type:"string",description:"Original signup date (ISO 8601) from the source platform. Set this when migrating so date-relative segments are correct immediately rather than treating every imported contact as having joined today. An existing contact's date only ever moves earlier."}},required:[],additionalProperties:!1},X3=[{name:"add_subscriber",description:"Add one subscriber. Status is only applied when creating a new contact; use update_subscriber to change an existing contact's status. For multiple contacts or CRM records, use create_subscriber_import instead of looping this tool. For an email-only batch going into one list, add_subscribers_to_list is also available.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to add subscriber to. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Optional when phone is provided - a contact created with only a phone becomes a phone-only (SMS) contact."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},phone:{type:"string",description:"Phone number in E.164 or national format, stored as a native profile field. With no email, creates or matches a phone-only (SMS) contact."},phoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used to read a national-format phone number, such as IT or US. Defaults to US. Only send it together with phone; the stored country always comes from the parsed number."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for this phone number. Never inferred from phone presence."},firstName:{type:"string",description:"Subscriber first name, stored as a native profile field."},lastName:{type:"string",description:"Subscriber last name, stored as a native profile field."},attributes:{type:"object",description:"Custom attributes (plan, company, etc.). Use firstName/lastName for names instead of attributes."},tags:{type:"array",items:{type:"string"},description:"Tags to apply to the subscriber"},listIds:{type:"array",items:{type:"string"},description:"List IDs to add subscriber to"},status:{type:"string",enum:["active","unsubscribed","bounced"],description:"Initial subscriber status: active, unsubscribed, or bounced. Defaults to active and does not change an existing contact; use update_subscriber for existing contacts."},optInMode:{type:"string",enum:["default","confirmed","double_opt_in"],description:"Consent mode: confirmed creates active immediately when consent is verified, double_opt_in sends a confirmation email before activation, and default obeys company double opt-in settings."},createdAt:{type:"string",description:"Original signup date (ISO 8601) when importing a contact from another platform. Preserves their real history so date-relative segments like 'added in the last 30 days' are correct immediately instead of treating every imported contact as brand new. An existing contact's date only ever moves earlier. Supplying this also stops welcome sequences from firing, since it describes the past rather than a signup happening now."}},required:[]}},{name:"create_subscriber_import",description:"Queue one CRM-grade subscriber import with up to 5,000 full contact records. Supports names, external IDs, phones, statuses, tags, lists, and custom attributes. Prefer this over repeated add_subscriber calls. Returns an import ID for get_subscriber_import. Use optInMode='confirmed' only when the contacts already gave verified email consent.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},subscribers:{type:"array",minItems:1,maxItems:5000,items:Tj,description:"Full subscriber records to import in one batch."},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How existing contacts are handled. Defaults to skip. Merge fills missing fields; overwrite replaces public fields without reactivating unsubscribed contacts."},fileName:{type:"string",description:"Optional source label shown in import history, such as copper-export.csv."},listIds:{type:"array",items:{type:"string"},description:"Lists to add every successfully imported active subscriber to."},enrollInSequences:{type:"boolean",description:"Whether matching sequences may enroll imported contacts. Defaults to false and requires automations:trigger."},defaultPhoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used for national-format phone numbers, such as SG or US."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for every imported phone number."},optInMode:{type:"string",enum:["default","confirmed","double_opt_in"],description:"Email consent mode. Default follows workspace double opt-in settings. Confirmed creates active contacts immediately and must only be used for verified consent. Double_opt_in may send confirmation email and requires automations:trigger."}},required:["subscribers"]}},{name:"get_subscriber_import",description:"Get progress, counts, skipped reasons, and failure summaries for a queued subscriber import.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},importId:{type:"string",description:"Import ID or batch ID returned by create_subscriber_import."}},required:["importId"]}},{name:"update_subscriber",description:"Update an existing subscriber's profile, phone, status, attributes, or tags. Names and phones are native profile fields - set them here rather than as custom attributes. Setting status to unsubscribed suppresses the contact from all marketing, deactivates list memberships, and cancels active sequence enrollments while preserving the record and suppression history.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},firstName:{type:"string",description:"New first name, stored as a native profile field. Pass an empty string to clear it."},lastName:{type:"string",description:"New last name, stored as a native profile field. Pass an empty string to clear it."},phone:{type:"string",description:"New phone number in E.164 or national format, stored as a native profile field. Pass an empty string to clear it, which is rejected for a phone-only (SMS) contact that has no email. Changing the number resets SMS consent unless smsConsent is sent in the same call."},phoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used to read a national-format phone number, such as IT or US. Defaults to US. Only send it together with phone; the stored country always comes from the parsed number."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for this phone number; false unsubscribes them from SMS. Omitting this leaves consent unchanged unless phone changes, which resets consent because it belonged to the old number. Consent is never inferred from phone presence."},status:{type:"string",enum:["active","unsubscribed","bounced"],description:"New global subscriber status. Use unsubscribed for compliance-grade suppression without deleting the record. Use active only when the contact has valid consent to be resubscribed."},attributes:{type:"object",description:"Custom attributes to update. Use firstName/lastName for names instead of attributes."},addTags:{type:"array",items:{type:"string"},description:"Tags to add"},removeTags:{type:"array",items:{type:"string"},description:"Tags to remove"}},required:[]}},{name:"remove_subscriber",description:"Unsubscribe a subscriber while preserving the record and suppression history. Only permanently deletes when hardDelete is true.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},hardDelete:{type:"boolean",description:"If true, permanently deletes the subscriber and suppression history. Defaults to false, which globally unsubscribes the contact, deactivates list memberships, and cancels active sequence enrollments."}},required:[]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, notes, list memberships, sequence enrollments, email stats, and recent activity. For commerce customers, customAttributes include nightly predictive analytics: predictedLtv (next-12-month spend), churnRisk (percent), expectedNextOrderAt, avgDaysBetweenOrders, and predictionConfidence.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:kw},required:[]}},{name:"list_subscriber_notes",description:"List internal notes for a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"add_subscriber_note",description:"Add an internal note to a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},body:{type:"string",description:"Internal note body, up to 5000 characters."}},required:["body"]}},{name:"delete_subscriber_note",description:"Delete one internal subscriber note by note ID.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},noteId:{type:"string",description:"Subscriber note ID to delete."}},required:["noteId"]}},{name:"trigger_subscriber_event",description:"Emit a custom event for one subscriber, exactly as an integration or the public API would. This is the supported way to exercise event triggers, matching-field idempotency, branch conditions, and stop conditions end to end without waiting for real traffic. The event is recorded, sync rules apply, and matching event_received sequences enroll. Creates the subscriber if they do not exist. Use trigger_subscriber_events for several events on the same contact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},event:{type:"string",description:"Event name, such as saas.purchase or invoice.paid. The event definition is created if it does not exist."},properties:{type:"object",description:"Event properties. Include the sequence's matching field (for example order.id or invoice.id) when testing idempotency or cancellation by field value.",additionalProperties:!0},firstName:{type:"string",description:"First name applied to the subscriber profile."},lastName:{type:"string",description:"Last name applied to the subscriber profile."},attributes:{type:"object",description:"Custom attributes to set on the subscriber.",additionalProperties:!0},occurredAt:{type:"string",description:"When the event actually happened (ISO 8601). Omit for live events. If this is more than an hour in the past the event is recorded as history: it is stored with its real timestamp and counts for segments and the timeline, but no sequences enroll, no sync rules apply, no waiting steps resume, and no webhooks fire. A historical event also moves the contact's signup date back to when it occurred (never later), so imported contacts do not read as added today. Use this when backfilling from another platform - never to fake a live event, since the side effects you are testing will not run."},eventId:{type:"string",description:"Your own id for this event. Makes a historical import idempotent: re-sending the same eventId writes nothing new."}},required:["event"]}},{name:"trigger_subscriber_events",description:"Emit several custom events for one subscriber in order. Events are processed independently and sequentially, so a partial failure can still leave earlier events recorded.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},events:{type:"array",minItems:1,maxItems:500,items:{type:"object",properties:{name:{type:"string",description:"Event name"},properties:{type:"object",description:"Event properties",additionalProperties:!0},occurredAt:{type:"string",description:"When the event actually happened (ISO 8601). When every event in the batch is more than an hour old the batch is imported as history in one idempotent write, with no sequences, sync rules, waiting steps or webhooks; the contact's signup date also moves back to the earliest event in the batch (never later)."},eventId:{type:"string",description:"Your own id for this event, making a re-run idempotent."}},required:["name"],additionalProperties:!1},description:"Events to trigger, in order, for this subscriber."},firstName:{type:"string"},lastName:{type:"string"},attributes:{type:"object",description:"Custom attributes to set on the subscriber.",additionalProperties:!0}},required:["events"]}},{name:"bulk_add_subscriber_tags",description:"Add tags to up to 500 existing subscribers in one call, identified by emails, externalIds, or subscriberIds. Built for reconciling historical or derived tags: subscribers that do not exist are reported in notFound instead of being created, and tag automations do NOT run unless triggerAutomations is true. Needs the subscribers:tag scope, which the agent_safe key preset includes; a tag name that does not exist yet also needs tags:write. Use add_subscriber or update_subscriber for single-contact changes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tags:{type:"array",minItems:1,items:{type:"string"},description:"Tag names to add to every matched subscriber."},emails:{type:"array",items:{type:"string"},description:"Subscriber emails to tag. Combine with externalIds/subscriberIds as needed; at least one identifier list is required."},externalIds:{type:"array",items:{type:"string"},description:"Customer-owned subscriber IDs to tag."},subscriberIds:{type:"array",items:{type:"string"},description:"Sequenzy subscriber IDs to tag."},triggerAutomations:{type:"boolean",description:"Whether tag_added sequences may enroll these contacts. Defaults to false, which is what backfills want. Requires the automations:trigger scope."}},required:["tags"]}},{name:"bulk_remove_subscriber_tags",description:"Remove tags from up to 500 existing subscribers in one call, identified by emails, externalIds, or subscriberIds. Subscribers that do not exist are reported in notFound. Needs the subscribers:tag scope; the broader subscribers:write scope also satisfies it. Use this to roll back or reconcile a derived-tag backfill.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tags:{type:"array",minItems:1,items:{type:"string"},description:"Tag names to remove from every matched subscriber."},emails:{type:"array",items:{type:"string"},description:"Subscriber emails to untag."},externalIds:{type:"array",items:{type:"string"},description:"Customer-owned subscriber IDs to untag."},subscriberIds:{type:"array",items:{type:"string"},description:"Sequenzy subscriber IDs to untag."}},required:["tags"]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, list, or segment. If you omit limit, the tool fetches all pages and returns every match.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query (email or name)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},list:{type:"string",description:"Filter by subscriber list ID or exact list name. Prefer listId when known."},listId:{type:"string",description:"Filter by subscriber list ID."},listName:{type:"string",description:"Filter by exact subscriber list name when the list ID is not known."},segmentId:{type:"string",description:"Filter by segment ID"},status:{type:"string",description:"Filter by subscriber status: active, unsubscribed, or bounced."},limit:{type:"number",description:"Maximum results to return. If omitted, the tool returns all matches across pages."}}}}];var G3={companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Exact recipient email address to inspect or clean up."},region:{type:"string",description:"Optional AWS SES region such as us-east-1. Omit to check every SES region currently used by the company."}},J3=[{name:"get_recipient_suppression",description:"Check whether one recipient is suppressed by Sequenzy's bounce/complaint safeguards or the regional Amazon SES account-level suppression list. This exact-address lookup never exposes other recipients from the shared SES account.",inputSchema:{type:"object",properties:G3,required:["email"],additionalProperties:!1}},{name:"remove_recipient_suppression",description:"Remove stale bounce suppression for an exact recipient associated with the company. Clears matching Amazon SES bounce entries and Sequenzy's local bounce block, then reactivates bounced company subscribers. Complaint and unsubscribe protections are never removed.",inputSchema:{type:"object",properties:G3,required:["email"],additionalProperties:!1}}];var Y3=[{name:"list_tags",description:"List all tags in the account",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list tags for. If not provided, uses the currently selected company."}}}},{name:"create_tag",description:"Create a new tag definition. The name is normalized to lowercase with hyphens (e.g. 'VIP Customer' becomes 'vip-customer'). Color defaults to gray.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Tag name. Normalized to lowercase with hyphens."},color:{type:"string",enum:[...A0],description:"Tag color. Defaults to gray."}},required:["name"]}},{name:"update_tag",description:"Update a tag's color. System tags cannot be updated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."},color:{type:"string",enum:[...A0],description:"New tag color."}},required:["tagId","color"]}},{name:"delete_tag",description:"Permanently delete a tag and remove it from all subscribers. This cannot be undone. System tags and tags used by sequences cannot be deleted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."}},required:["tagId"]}},{name:"list_lists",description:"List all subscriber lists",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list lists for. If not provided, uses the currently selected company."}}}},{name:"create_list",description:"Create a new subscriber list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the list in. If not provided, uses the currently selected company."},name:{type:"string",description:"List name"},description:{type:"string",description:"List description"}},required:["name"]}},{name:"update_list",description:"Update a subscriber list's name, description, or privacy. Only the provided fields are changed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to update."},name:{type:"string",description:"New list name."},description:{type:["string","null"],description:"New list description. Pass null to clear it."},isPrivate:{type:"boolean",description:"Whether the list is private."}},required:["listId"]}},{name:"delete_list",description:"Permanently delete a subscriber list and remove all of its memberships. Subscribers themselves are kept. This cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to delete."}},required:["listId"]}},{name:"add_subscribers_to_list",description:"Bulk add existing or new subscribers to a subscriber list from an email array. Existing subscribers are added to the list without requiring a per-subscriber update call.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to add subscribers to."},emails:{type:"array",items:{type:"string"},description:"Email addresses to add to the list. Maximum 500 per call."},duplicateStrategy:{type:"string",description:"Duplicate strategy for existing subscribers: skip, merge, or overwrite. Defaults to skip."},enrollInSequences:{type:"boolean",description:"Whether newly created subscribers should enroll in matching sequences. Defaults to false."},optInMode:{type:"string",description:"Consent mode for newly created subscribers: default, confirmed, or double_opt_in. Defaults to default."}},required:["listId","emails"]}},{name:"remove_subscribers_from_list",description:"Remove subscribers from a list by email address. Maximum 500 emails per call. Subscribers stay in the account; only the list membership is removed. Returns the removed count plus a notFound array of emails that did not match a subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to remove subscribers from."},emails:{type:"array",items:{type:"string"},description:"Email addresses to remove from the list. Maximum 500 per call."}},required:["listId","emails"]}},{name:"list_segments",description:"List all segments",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list segments for. If not provided, uses the currently selected company."}}}},{name:"create_segment",description:'Create a new segment from explicit filter rules. Use `filters` plus `filterJoinOperator` for flat legacy rules, or `root` for nested AND/OR groups such as `{ "kind": "group", "joinOperator": "and", "children": [{ "kind": "filter", "field": "attribute", "operator": "gte", "value": "mrr:50" }, { "kind": "group", "joinOperator": "or", "children": [{ "kind": "filter", "field": "tag", "operator": "contains", "value": "vip" }, { "kind": "filter", "field": "event", "operator": "is_not", "value": "saas.purchase:30d" }] }] }`. Supports `event` and `segment` fields, Stripe product purchase/current/trial/date filters, and campaign-specific engagement filters.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the segment in. If not provided, uses the currently selected company."},name:{type:"string",description:"Segment name"},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:y9,minItems:1,description:'Array of segment filters. Example custom attribute empty check: [{"id":"filter-1","field":"attribute","operator":"is_empty","value":"last_logged_in:"}]. Example Stripe purchase filter: [{"id":"filter-1","field":"stripeProduct","operator":"is","value":"prod_123"}]. Example threshold filter: [{"id":"filter-1","field":"stripeProduct","operator":"at_least","value":"prod_123:3"}]. Example commerce product purchase filter (value is provider:productId since product ids are provider-scoped): [{"id":"filter-1","field":"commerceProduct","operator":"is","value":"api:prod-starter-kit"}]. Example repeat-buyer filter: [{"id":"filter-1","field":"commerceProduct","operator":"at_least","value":"shopify:42:2"}]. Example commerce collection filter (anyone who bought any product in the collection; value is a collection id or handle): [{"id":"filter-1","field":"commerceCollection","operator":"is","value":"skincare"}]. Example trial cancellation filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:is_canceled"}]. Example trial end filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:end_at:2026-05-26"}]. Example campaign-specific engagement combo: [{"id":"filter-1","field":"emailBounced","operator":"is","value":"campaign:cmp_abc"},{"id":"filter-2","field":"emailBounced","operator":"is_not","value":"campaign:cmp_xyz"}]. Combine them with `filterJoinOperator: "or"` to match any filter.'},root:{...f9,description:"Nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["name"]}},{name:"update_segment",description:"Update a segment's name and/or filter rules. Use the same `filters` plus `filterJoinOperator` or nested `root` shapes as create_segment; providing `filters` or `root` replaces the segment's existing rules.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to update."},name:{type:"string",description:"New segment name."},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:y9,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...f9,description:"Replacement nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["segmentId"]}},{name:"delete_segment",description:"Permanently delete a segment. This cannot be undone. Subscribers are not affected.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to delete."}},required:["segmentId"]}},{name:"get_segment_count",description:"Get the number of subscribers in a segment",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID"}},required:["segmentId"]}}];var H3=[{name:"list_team_members",description:"List team members for the company, including the owner, members with their roles, and pending or expired invitations.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"invite_team_member",description:"Invite a team member by email with role admin, viewer, or restricted. Existing Sequenzy users are added to the team immediately; others receive an email invitation. Billing access (canManageBilling) can only be granted by the company owner and is not available for restricted members.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Email address of the person to invite."},role:{type:"string",enum:["admin","viewer","restricted"],description:"Team role. Admins can manage the workspace; viewers have read-only access; restricted members can open direct campaign links only."},canManageBilling:{type:"boolean",description:"Whether the member can manage billing. Only the company owner can grant billing access. Defaults to false."}},required:["email","role"]}},{name:"cancel_team_invitation",description:"Cancel a pending team invitation. Invitations that have already been accepted cannot be cancelled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},invitationId:{type:"string",description:"Invitation ID to cancel. Use list_team_members to find pending invitations."}},required:["invitationId"]}}];var z3=[{name:"list_templates",description:"List the company's 50 most recently created email bodies, including per-locale localization sync status. Results include standalone templates plus recent bodies behind campaigns and transactional emails. To retrieve a specific campaign body even when it is not among these 50 results, pass the campaign's emailId to get_template. Bodies are kept when their campaign or transactional email is deleted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"create_template",description:"Create a new email template. For net-new email content requested in natural language, use `prompt`; do not write HTML or construct blocks yourself. Use `blocks` only for finished caller-supplied Sequenzy content and `html` only for supplied or explicitly requested preserved HTML.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line. Optional with `prompt`."},previewText:{type:["string","null"],description:"Optional preview text override."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider templates. ${Hw}`},blocks:{type:"array",description:A1,items:{type:"object"}},prompt:{type:"string",description:"Natural-language request for Sequenzy to generate branded native template blocks."},style:{type:"string",description:"Generation style; valid only with `prompt`."},tone:{type:"string",description:"Generation tone; valid only with `prompt`."},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `previewText`, `html`, `blocks`, or `labels` is required, and only those update fields are accepted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},previewText:{type:["string","null"],description:"Inbox preview text. Send null to clear the existing preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider templates. ${Hw}`},blocks:{type:"array",description:A1,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"set_template_localization",description:"Create or replace one caller-supplied localized variant of a template. The locale must be enabled for the company and cannot be its primary locale. Provide exactly one of `html` or `blocks`.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locale:{type:"string",description:"Enabled non-primary locale code such as es, fr, or pt-BR."},subject:{type:"string",description:"Localized email subject line."},previewText:{type:["string","null"],description:"Optional localized inbox preview text."},html:{type:"string",description:`Localized email HTML. Mutually exclusive with \`blocks\`. ${Hw}`},blocks:{type:"array",description:A1,items:{type:"object"}}},required:["templateId","locale","subject"],additionalProperties:!1}},{name:"sync_template_localizations",description:"Queue AI translation for selected template locales. Omit `locales` to sync every enabled non-primary locale. This works even when automatic on-save localization is disabled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locales:{type:"array",description:"Optional enabled non-primary locale codes to sync. Omit to sync all enabled non-primary locales.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}}];var D3=[{name:"list_transactional_emails",description:"List transactional email templates with subjects, delivery metrics, API slugs, and dashboard URLs. Search by name, slug, or email title; filter active state; and sort by sends, opens, open rate, clicks, or CTR.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},search:{type:"string",description:"Case-insensitive search across template name, API slug, and linked email subject/title."},status:{type:"string",description:"Template status: all, active, or disabled."},sort:{type:"string",description:"Sort field: date, sends, opens, open-rate, clicks, or ctr. Defaults to date."},order:{type:"string",description:"Sort order: asc or desc. Defaults to desc."},includeMachineEngagement:{type:"boolean",description:"Include bot, scanner, and privacy-proxy engagement in open and click metrics. Defaults to false."}},additionalProperties:!1}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"]}},{name:"create_transactional_email",description:"Create a saved transactional email template with an API slug. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Transactional email name."},slug:{type:"string",description:"Optional API slug used when sending by slug, for example `password-reset`. If omitted, Sequenzy generates one from the name."},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. ${Hw}`},blocks:{type:"array",description:`${A1} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Generated blocks include the company's branding (logo and a footer without an unsubscribe link). Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Prompt-created templates default to false; explicit HTML/blocks retain the compatibility default of true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. ${Hw}`},blocks:{type:"array",description:`${F1} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"delete_transactional_email",description:"Permanently delete a saved transactional email template by ID or slug. Use this to retire an obsolete template: the slug stops sending and becomes free to reuse. Already-sent deliveries and their stats are kept, so history and analytics survive the delete. The linked email content stays as a reusable template and comes back as `deleted.emailId`; pass that to `delete_template` to remove the content too. To stop sends without losing the template, call `update_transactional_email` with `enabled` set to false instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Queue one email using either a saved transactional email API slug (`templateId`) or direct `subject` and `html` content. The default delivery policy is transactional. When the recipient matches a subscriber, saved first and last names fill omitted name variables; explicit variables take precedence. Set `emailType` to `marketing` to add subscriber suppression, a marketing footer, and RFC 8058 one-click unsubscribe. Company Reply-To defaults are inherited when no override is provided, and `{{viewInBrowserUrl}}` is replaced with a hosted copy URL. Use `trackingSettings` with `clickTracking` or `openTracking` set to `false` to disable click-link rewriting or the open-tracking pixel for this send only; these opt-out fields cannot enable tracking the account has disabled. Returns a durable emailSendId and the accepted emailType; pass the ID to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line. Required with `html` when `templateId` is omitted."},html:{type:"string",description:"Direct-send HTML body. Required with `subject` when `templateId` is omitted; the MCP server maps this to the transactional API `body` field. Use `{{viewInBrowserUrl}}` for a hosted copy link generated at send time."},templateId:{type:"string",description:"Saved transactional email API slug, for example `welcome-email`. The field name is retained for MCP compatibility and is mapped to the transactional API `slug` field."},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }. When the recipient matches a subscriber, saved first and last names fill omitted name variables; explicit values, including blanks, take precedence. Variables are HTML-escaped; a template can prefix a tag with 'html.' ({{html.prerenderedHtml}}) to insert a trusted, sanitized HTML value unescaped."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics, localization, and saved-name personalization on single-recipient sends. Maximum length: 255 characters."},emailType:{type:"string",description:"Delivery policy: `transactional` (default) or `marketing`. Marketing mode supports exactly one recipient and automatically applies subscriber suppression, the standard unsubscribe footer, and RFC 8058 headers."},replyTo:{type:"string",description:"Optional Reply-To address, formatted as `email@example.com` or `Name <email@example.com>`. When omitted, the saved template or company default is used."},trackingSettings:{type:"object",description:"Per-send tracking opt-outs. Each field defaults to `true`, meaning the account tracking settings apply; set a field to `false` to disable that tracking for this send only. These fields cannot enable tracking the account has disabled.",properties:{clickTracking:{type:"boolean",description:"Set to `false` to skip click-link rewriting for this send only, which helps when tracking redirects break universal or deep links."},openTracking:{type:"boolean",description:"Set to `false` to skip the open-tracking pixel for this send only."}},additionalProperties:!1}},required:["to"],additionalProperties:!1}}];var B3=[{name:"list_webhooks",description:"List outbound webhook endpoints and their subscribed event types.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_webhook",description:"Create an outbound webhook endpoint. IMPORTANT: the response includes a signingSecret that is returned only once - show it to the user immediately so they can store it and verify webhook signatures. If events is omitted, a default set of event types is subscribed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Webhook endpoint name."},url:{type:"string",description:"HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...F0]},description:"Event types to subscribe to. If omitted, a default set is used."}},required:["name","url"]}},{name:"update_webhook",description:"Update an outbound webhook endpoint's name, URL, subscribed events, or status (enabled/disabled). Providing events replaces the existing event list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},name:{type:"string",description:"New webhook endpoint name."},url:{type:"string",description:"New HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...F0]},description:"Replacement event type subscriptions."},status:{type:"string",enum:["enabled","disabled"],description:"Enable or disable deliveries to this endpoint."}},required:["webhookId"]}},{name:"delete_webhook",description:"Permanently delete an outbound webhook endpoint along with its delivery history. This cannot be undone. To keep the endpoint but stop deliveries, use update_webhook with status disabled instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to delete."}},required:["webhookId"]}},{name:"test_webhook",description:"Send a test event to an outbound webhook endpoint to verify it is reachable and signatures can be validated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to test."}},required:["webhookId"]}},{name:"list_webhook_deliveries",description:"List recent delivery attempts for an outbound webhook endpoint, including status and response codes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},limit:{type:"number",description:"Maximum number of deliveries to return, from 1 to 100. Defaults to 20."}},required:["webhookId"]}},{name:"replay_webhook_delivery",description:"Replay a previous webhook delivery, re-sending the same event payload to the endpoint.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},deliveryId:{type:"string",description:"Delivery ID to replay. Use list_webhook_deliveries to find delivery IDs."}},required:["webhookId","deliveryId"]}}];var A3=[...m5,...r5,...X3,...J3,...e5,...Y3,...i5,...z3,...c5,...n5,...a5,...d5,...s5,...o5,...W3,...Q3,...b3,...$3,...D3,...g5,...H3,...t5,...B3,...l5,...p5];async function F3(w,b){let $;switch(w){case"get_account":{let W=await D("GET","/api/v1/account"),Q=O1();$={...W,selectedCompanyId:Q??W.currentCompanyId};break}case"select_company":{let W=b.companyId,Q=await D("GET","/api/v1/account"),X=Q.companies?.find((G)=>G.id===W);if(!X)throw Error(`Company not found. Available companies: ${Q.companies?.map((G)=>`${G.name} (${G.id})`).join(", ")??"none"}`);Nb(W),$={success:!0,message:`Switched to company: ${X.name}`,companyId:X.id,companyName:X.name};break}case"get_app_urls":{let W=await X4(b);$={...B1({companyId:W,campaignId:L(b,"campaignId"),landingPageId:L(b,"landingPageId"),sequenceId:L(b,"sequenceId"),emailId:L(b,"emailId")??L(b,"templateId"),transactionalId:L(b,"transactionalId"),emailSendId:L(b,"emailSendId"),domainId:L(b,"domainId"),status:L(b,"status"),settingsTab:L(b,"settingsTab")}),...W===void 0&&{note:"No company ID is selected. Call get_account, select_company, or pass companyId to get concrete dashboard URLs."}};break}case"create_company":{let W=await D("POST","/api/v1/companies",{name:b.name,domain:b.domain});if(!W.success)throw Error("Failed to create company");let Q=W.company.id,X=6,G=0,J=W.company.status;while(J==="processing"&&G<X){await new Promise((z)=>setTimeout(z,20000)),G++;let H=await D("GET",`/api/v1/companies/${Q}`);if(H.success)J=H.company.status}Nb(Q);let Y=await D("GET",`/api/v1/companies/${Q}`);$={success:!0,company:Y.company,message:J==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${Y.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let W=b.companyId;$=await D("GET",`/api/v1/companies/${W}`);break}case"update_company":{let W=await qb("update_company",b),Q=X5(b);$=await D("PATCH",`/api/v1/companies/${W}`,Q);break}case"get_sync_rules":{let W=b.companyId;$=await D("GET","/api/v1/sync-rules",void 0,W);break}case"update_sync_rules":{let W=b.companyId;if(b.syncRules!==null&&!Array.isArray(b.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");$=await D("PUT","/api/v1/sync-rules",{syncRules:b.syncRules},W);break}case"get_shopify_automation_settings":{let W=b.companyId;$=await D("GET","/api/v1/shopify/automation-settings",void 0,W);break}case"update_shopify_automation_settings":{let W=b.companyId,Q={};if(b.browseAbandonment!==void 0)Q.browseAbandonment=b.browseAbandonment;if(b.cartAbandonment!==void 0)Q.cartAbandonment=b.cartAbandonment;if(b.priceDrop!==void 0)Q.priceDrop=b.priceDrop;if(Object.keys(Q).length===0)throw Error("Provide `browseAbandonment`, `cartAbandonment`, and/or `priceDrop` when calling `update_shopify_automation_settings`.");$=await D("PUT","/api/v1/shopify/automation-settings",Q,W);break}case"create_api_key":{let W=b.companyId,Q={};if(typeof b.name==="string")Q.name=b.name;if(typeof b.preset==="string")Q.preset=b.preset;if(Array.isArray(b.scopes))Q.scopes=b.scopes;$=await D("POST","/api/v1/api-keys",Q,W);break}case"list_api_keys":{let W=await qb(w,b);$=await D("GET","/api/v1/api-keys",void 0,W);break}case"update_api_key":{let W=await qb(w,b),Q={};if(typeof b.name==="string")Q.name=b.name;if(typeof b.preset==="string")Q.preset=b.preset;if(Array.isArray(b.scopes))Q.scopes=b.scopes;if(Object.keys(Q).length===0)throw Error("Provide at least one of `name`, `preset`, or `scopes` when calling `update_api_key`.");$=await D("PATCH",`/api/v1/api-keys/${encodeURIComponent(String(b.apiKeyId))}`,Q,W);break}case"revoke_api_key":case"delete_api_key":{let W=await qb(w,b);$=await D("DELETE",`/api/v1/api-keys/${encodeURIComponent(String(b.apiKeyId))}`,void 0,W);break}case"list_websites":{let W=b.companyId;$=await D("GET","/api/v1/websites",void 0,W);break}case"add_sending_domain":case"add_website":{let W=b.companyId;$=await D("POST","/api/v1/websites",{domain:b.domain},W);break}case"check_website":{let W=b.companyId;$=await D("GET",`/api/v1/websites/${encodeURIComponent(String(b.domain))}`,void 0,W);break}case"verify_sending_domain":{let W=b.companyId;$=await D("POST",`/api/v1/websites/${encodeURIComponent(String(b.domain))}/verify`,void 0,W);break}case"list_integrations":{let W=b.companyId,Q=new URLSearchParams;if(b.includeInactive===!0)Q.set("includeInactive","true");let X=Q.toString();$=await D("GET",`/api/v1/integrations${X?`?${X}`:""}`,void 0,W);break}case"list_sender_profiles":{let W=b.companyId;$=await D("GET","/api/v1/sender-profiles",void 0,W);break}case"update_sender_profile":{let{companyId:W,profileId:Q}=b,X=b.type==="reply"?`/api/v1/reply-profiles/${encodeURIComponent(Q)}`:`/api/v1/sender-profiles/${encodeURIComponent(Q)}`;$=await D("PATCH",X,{name:b.name},W);break}case"get_tracking_settings":{let W=b.companyId;$=await D("GET","/api/v1/tracking-settings",void 0,W);break}case"update_tracking_settings":{let W=b.companyId,Q=G5(b);$=await D("PATCH","/api/v1/tracking-settings",Q,W);break}case"get_notification_preferences":{let W=b.companyId;$=await D("GET","/api/v1/notification-preferences",void 0,W);break}case"update_notification_preferences":{let W=b.companyId;$=await D("PATCH","/api/v1/notification-preferences",{notificationPreferences:b.notificationPreferences},W);break}case"get_integration_guide":$=await D("POST","/api/v1/integration-guide",b);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function L3(w,b){let $;switch(w){case"generate_email":{let W=b.companyId;$=await D("POST","/api/v1/generate/email",b,W);break}case"generate_subject_lines":{let W=b.companyId;$=await D("POST","/api/v1/generate/subjects",b,W);break}case"generate_sms":{let W=b.companyId;$=await D("POST","/api/v1/generate/sms",b,W);break}case"get_sms_settings":{let W=b.companyId;$=await D("GET","/api/v1/sms/settings",void 0,W);break}case"send_test_sms":{let W=b.companyId,Q={to:V("send_test_sms",b,"to")};for(let X of["text","imageUrls","blocks"])if(b[X]!==void 0)Q[X]=b[X];$=await D("POST","/api/v1/sms/test",Q,W);break}case"submit_feedback":{let W=b.companyId,Q={message:V("submit_feedback",b,"message"),source:"mcp"};for(let X of["category","context"])if(b[X]!==void 0)Q[X]=b[X];$=await D("POST","/api/v1/feedback",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function U3(w,b){let $;switch(w){case"list_transactional_emails":{let W=b.companyId,Q=new URLSearchParams,X=L(b,"search"),G=m("list_transactional_emails",b,"status",["all","active","disabled"]),J=m("list_transactional_emails",b,"sort",["date","sends","opens","open-rate","clicks","ctr"]),Y=m("list_transactional_emails",b,"order",["asc","desc"]);if(X)Q.set("search",X);if(G)Q.set("status",G);if(J)Q.set("sort",J);if(Y)Q.set("order",Y);if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let H=Q.toString();$=await D("GET",`/api/v1/transactional${H?`?${H}`:""}`,void 0,W);break}case"get_transactional_email":{let W=b.companyId;$=await D("GET",`/api/v1/transactional/${b.idOrSlug}`,void 0,W);break}case"create_transactional_email":{let W=b.companyId,Q=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),X=Object.keys(b).filter((J)=>!Q.has(J));if(X.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);j5(b);let G=Object.fromEntries(Object.entries(b).filter(([J])=>J!=="companyId"));$=await D("POST","/api/v1/transactional",G,W);break}case"update_transactional_email":{let W=b.companyId,Q=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),X=Object.keys(b).filter((J)=>!Q.has(J));if(X.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);if(_w("update_transactional_email",b),b.name===void 0&&b.enabled===void 0&&b.subject===void 0&&b.previewText===void 0&&b.html===void 0&&b.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let G=Object.fromEntries(Object.entries(b).filter(([J])=>J!=="companyId"&&J!=="idOrSlug"));$=await D("PATCH",`/api/v1/transactional/${b.idOrSlug}`,G,W);break}case"delete_transactional_email":{let W=b.companyId,Q=V("delete_transactional_email",b,"idOrSlug");$=await D("DELETE",`/api/v1/transactional/${encodeURIComponent(Q)}`,void 0,W);break}case"send_email":{let W=b.companyId,Q=V("send_email",b,"to"),X=b.templateId===void 0?void 0:V("send_email",b,"templateId"),G=b.subject===void 0?void 0:V("send_email",b,"subject"),J=b.html===void 0?void 0:V("send_email",b,"html"),Y=b.emailType===void 0?void 0:V("send_email",b,"emailType"),H=b.replyTo===void 0?void 0:V("send_email",b,"replyTo");if(Y!==void 0&&Y!=="marketing"&&Y!=="transactional")throw Error("`emailType` must be `marketing` or `transactional` when calling `send_email`.");if(X!==void 0&&(G!==void 0||J!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(X===void 0&&(G===void 0||J===void 0))throw Error("Provide either `templateId` or both `subject` and `html` when calling `send_email`.");let z;if(b.trackingSettings!==void 0){if(typeof b.trackingSettings!=="object"||b.trackingSettings===null||Array.isArray(b.trackingSettings))throw Error("`trackingSettings` must be an object with optional boolean `clickTracking` and `openTracking` fields when calling `send_email`.");let A=b.trackingSettings;z={};for(let F of["clickTracking","openTracking"]){let U=A[F];if(U===void 0)continue;if(typeof U!=="boolean")throw Error(`\`trackingSettings.${F}\` must be a boolean when calling \`send_email\`.`);z[F]=U}}let B=Object.fromEntries(Object.entries({to:Q,slug:X,subject:G,body:J,variables:b.variables,subscriberExternalId:b.subscriberExternalId,emailType:Y,replyTo:H,trackingSettings:z}).filter(([,A])=>A!==void 0));$=await D("POST","/api/v1/transactional/send",B,W);break}case"get_stats":{let W=b.companyId,Q=b.period??"7d",X=new URLSearchParams({period:String(Q)}),G=b.emailType===void 0?void 0:V("get_stats",b,"emailType");if(G!==void 0&&!["campaign","transactional","sequence"].includes(G))throw Error("`emailType` must be `campaign`, `transactional`, or `sequence` when calling `get_stats`.");if(G)X.set("emailType",G);if(b.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");$=await D("GET",`/api/v1/metrics?${X.toString()}`,void 0,W);break}case"get_campaign_stats":{let W=b.companyId,Q=new URLSearchParams;if(typeof b.period==="string")Q.set("period",b.period);if(typeof b.start==="string")Q.set("start",b.start);if(typeof b.end==="string")Q.set("end",b.end);if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let X=Q.toString();$=await D("GET",`/api/v1/metrics/campaigns/${b.campaignId}${X?`?${X}`:""}`,void 0,W);break}case"get_transactional_stats":{let W=b.companyId,Q=V("get_transactional_stats",b,"idOrSlug"),X=new URLSearchParams;for(let J of["period","start","end"])if(typeof b[J]==="string"&&b[J].trim())X.set(J,b[J].trim());if(b.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");let G=X.toString();$=await D("GET",`/api/v1/metrics/transactional/${encodeURIComponent(Q)}${G?`?${G}`:""}`,void 0,W);break}case"get_sequence_stats":{let W=b.companyId,Q=new URLSearchParams;for(let G of["period","start","end"])if(typeof b[G]==="string"&&b[G].trim())Q.set(G,b[G].trim());if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let X=Q.toString();$=await D("GET",`/api/v1/metrics/sequences/${b.sequenceId}${X?`?${X}`:""}`,void 0,W);break}case"list_campaign_events":{let W=b.companyId,Q=V("list_campaign_events",b,"campaignId"),G=e9("list_campaign_events",b).toString();$=await D("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(Q)}/events${G?`?${G}`:""}`,void 0,W);break}case"list_sequence_events":{let W=b.companyId,Q=V("list_sequence_events",b,"sequenceId"),X=e9("list_sequence_events",b),G=L(b,"automationNodeId");if(G)X.set("automationNodeId",G);let J=X.toString();$=await D("GET",`/api/v1/metrics/sequences/${encodeURIComponent(Q)}/events${J?`?${J}`:""}`,void 0,W);break}case"list_email_metrics":{let W=b.companyId,Q=new URLSearchParams,X=m("list_email_metrics",b,"emailType",["campaign","sequence"]);if(X)Q.set("emailType",X);let G=T9("list_email_metrics",b,"sequenceId"),J=T9("list_email_metrics",b,"campaignId"),Y=Yw("list_email_metrics",b,"step",1,1000);if(J.length>0&&(G.length>0||Y))throw Error("`campaignId` cannot be combined with `sequenceId` or `step` when calling `list_email_metrics`.");if(X==="campaign"&&(G.length>0||Y!==void 0))throw Error("`emailType` campaign cannot be combined with `sequenceId` or `step` when calling `list_email_metrics`.");if(X==="sequence"&&J.length>0)throw Error("`emailType` sequence cannot be combined with `campaignId` when calling `list_email_metrics`.");if(G.length>0)Q.set("sequenceId",G.join(","));if(J.length>0)Q.set("campaignId",J.join(","));if(Y!==void 0)Q.set("step",String(Y));let H=m("list_email_metrics",b,"period",["1h","24h","7d","30d","90d"]);if(H)Q.set("period",H);for(let M of["start","end"]){let q=L(b,M);if(q)Q.set(M,q)}let z=m("list_email_metrics",b,"sort",["sent","delivered","opened","clicked","openRate","clickRate","unsubscribed","conversions","revenue","step","name"]);if(z)Q.set("sort",z);let B=m("list_email_metrics",b,"order",["asc","desc"]);if(B)Q.set("order",B);let A=Yw("list_email_metrics",b,"page",1,1e6);if(A!==void 0)Q.set("page",String(A));let F=Yw("list_email_metrics",b,"limit",1,500);if(F!==void 0)Q.set("limit",String(F));if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let U=Q.toString();$=await D("GET",`/api/v1/metrics/emails${U?`?${U}`:""}`,void 0,W);break}case"get_subscriber_activity":{let W=b.companyId,Q=tw("get_subscriber_activity",b),X=await Mb(Q,W,{includeMachineEngagement:b.includeMachineEngagement===!0});$={success:X.success,email:X.subscriber.email,emailStats:X.subscriber.emailStats??null,activity:X.subscriber.activity??[],sequenceEnrollments:X.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function K3(w,b){let $;switch(w){case"list_tags":{let W=b.companyId;$=await D("GET","/api/v1/tags",void 0,W);break}case"create_tag":{let W=b.companyId,Q=V("create_tag",b,"name"),X=m("create_tag",b,"color",A0);$=await D("POST","/api/v1/tags",{name:Q,...X!==void 0&&{color:X}},W);break}case"update_tag":{let W=b.companyId,Q=V("update_tag",b,"tagId"),X=jb("update_tag",b,"color",A0);$=await D("PATCH",`/api/v1/tags/${encodeURIComponent(Q)}`,{color:X},W);break}case"delete_tag":{let W=b.companyId,Q=V("delete_tag",b,"tagId");$=await D("DELETE",`/api/v1/tags/${encodeURIComponent(Q)}`,void 0,W);break}case"list_lists":{let W=b.companyId;$=await D("GET","/api/v1/lists",void 0,W);break}case"create_list":{let W=b.companyId;$=await D("POST","/api/v1/lists",b,W);break}case"update_list":{let W=b.companyId,Q=V("update_list",b,"listId");if(b.name===void 0&&b.description===void 0&&b.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(b.name!==void 0&&L(b,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(b.description!==void 0&&b.description!==null&&typeof b.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(b.isPrivate!==void 0&&typeof b.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");$=await D("PATCH",`/api/v1/lists/${encodeURIComponent(Q)}`,{...b.name!==void 0&&{name:L(b,"name")},...b.description!==void 0&&{description:b.description},...b.isPrivate!==void 0&&{isPrivate:b.isPrivate}},W);break}case"delete_list":{let W=b.companyId,Q=V("delete_list",b,"listId");$=await D("DELETE",`/api/v1/lists/${encodeURIComponent(Q)}`,void 0,W);break}case"add_subscribers_to_list":{let W=b.companyId,Q=V("add_subscribers_to_list",b,"listId"),X=wW("add_subscribers_to_list",b),G=m("add_subscribers_to_list",b,"duplicateStrategy",["skip","merge","overwrite"])??"skip",J=m("add_subscribers_to_list",b,"optInMode",["default","confirmed","double_opt_in"])??"default";$=await D("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers`,{emails:X,duplicateStrategy:G,enrollInSequences:b.enrollInSequences===!0,optInMode:J},W);break}case"remove_subscribers_from_list":{let W=b.companyId,Q=V("remove_subscribers_from_list",b,"listId"),X=wW("remove_subscribers_from_list",b);$=await D("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers/remove`,{emails:X},W);break}case"list_segments":{let W=b.companyId;$=await D("GET","/api/v1/segments",void 0,W);break}case"create_segment":{W5(b);let W=b.companyId;$=await D("POST","/api/v1/segments",{...b,...b.filters!==void 0?{filters:e6(b.filters)}:{},...b.root!==void 0?{root:a6(b.root)}:{}},W);break}case"update_segment":{Q5(b);let W=b.companyId,Q=V("update_segment",b,"segmentId"),X=L(b,"name"),G=m("update_segment",b,"filterJoinOperator",["and","or"]);$=await D("PATCH",`/api/v1/segments/${encodeURIComponent(Q)}`,{...X!==void 0&&{name:X},...G!==void 0&&{filterJoinOperator:G},...b.filters!==void 0?{filters:e6(b.filters)}:{},...b.root!==void 0?{root:a6(b.root)}:{}},W);break}case"delete_segment":{let W=b.companyId,Q=V("delete_segment",b,"segmentId");$=await D("DELETE",`/api/v1/segments/${encodeURIComponent(Q)}`,void 0,W);break}case"get_segment_count":{let W=b.companyId;$=await D("GET",`/api/v1/segments/${b.segmentId}/count`,void 0,W);break}case"list_audience_syncs":{let W=b.companyId;$=await D("GET","/api/v1/audience-syncs",void 0,W);break}case"list_ad_accounts":{let W=b.companyId;$=await D("GET","/api/v1/ad-accounts",void 0,W);break}case"create_audience_sync":{let W=b.companyId,Q=L(b,"segmentId"),X=L(b,"predefinedSegmentId");if(Q&&X)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!Q&&!X)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");$=await D("POST","/api/v1/audience-syncs",{segmentId:Q,predefinedSegmentId:X,adAccountId:V("create_audience_sync",b,"adAccountId"),audienceName:V("create_audience_sync",b,"audienceName"),...b.frequency!==void 0?{frequency:b.frequency}:{}},W);break}case"update_audience_sync":{let W=b.companyId,Q=V("update_audience_sync",b,"syncId");$=await D("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,{...b.frequency!==void 0?{frequency:b.frequency}:{},...b.isActive!==void 0?{isActive:b.isActive}:{}},W);break}case"delete_audience_sync":{let W=b.companyId,Q=V("delete_audience_sync",b,"syncId");$=await D("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,void 0,W);break}case"sync_audience_now":{let W=b.companyId,Q=V("sync_audience_now",b,"syncId");$=await D("POST",`/api/v1/audience-syncs/${encodeURIComponent(Q)}/sync`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function O3(w,b){let $;switch(w){case"list_templates":{let W=b.companyId,Q=new URLSearchParams,X=L(b,"label");if(X)Q.set("label",X);$=await D("GET",`/api/v1/templates${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_template":{let W=b.companyId;$=await D("GET",`/api/v1/templates/${b.templateId}`,void 0,W);break}case"create_template":{let W=b.companyId;Z5(b);let Q=Object.fromEntries(Object.entries(b).filter(([X])=>X!=="companyId"));$=await D("POST","/api/v1/templates",Q,W);break}case"update_template":{let W=b.companyId,Q=new Set(["companyId","templateId","name","subject","previewText","html","blocks","labels"]),X=Object.keys(b).filter((G)=>!Q.has(G));if(X.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);if(_w("update_template",b),L1("update_template",b),b.name===void 0&&b.subject===void 0&&b.previewText===void 0&&b.html===void 0&&b.blocks===void 0&&b.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `previewText`, `html`, `blocks`, or `labels` when calling `update_template`.");$=await D("PUT",`/api/v1/templates/${b.templateId}`,b,W);break}case"set_template_localization":{let W=b.companyId,Q=V("set_template_localization",b,"templateId"),X=V("set_template_localization",b,"locale"),G=V("set_template_localization",b,"subject"),J=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),Y=Object.keys(b).filter((z)=>!J.has(z));if(Y.length>0)throw Error(`\`set_template_localization\` received unsupported field${Y.length===1?"":"s"}: ${Y.map((z)=>`\`${z}\``).join(", ")}.`);_w("set_template_localization",b,{requireContent:!0});let H={subject:G};if(b.previewText!==void 0)H.previewText=b.previewText;if(b.html!==void 0)H.html=b.html;if(b.blocks!==void 0)H.blocks=b.blocks;$=await D("PUT",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/${encodeURIComponent(X)}`,H,W);break}case"sync_template_localizations":{let W=b.companyId,Q=V("sync_template_localizations",b,"templateId"),X=new Set(["companyId","templateId","locales"]),G=Object.keys(b).filter((Y)=>!X.has(Y));if(G.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${G.length===1?"":"s"}: ${G.map((Y)=>`\`${Y}\``).join(", ")}.`);let J;if(b.locales!==void 0){if(!Array.isArray(b.locales)||b.locales.length===0||b.locales.some((Y)=>typeof Y!=="string"||Y.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");J=b.locales.map((Y)=>Y.trim())}$=await D("POST",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/sync`,J===void 0?{}:{locales:J},W);break}case"delete_template":{let W=b.companyId;$=await D("DELETE",`/api/v1/templates/${b.templateId}`,void 0,W);break}case"list_ab_tests":{let W=b.companyId,Q=new URLSearchParams,X=L(b,"sequenceId");if(X)Q.set("sequenceId",X);$=await D("GET",`/api/v1/ab-tests${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_ab_test":{let W=b.companyId;$=await D("GET",`/api/v1/ab-tests/${b.abTestId}`,void 0,W);break}case"get_ab_test_stats":{let W=b.companyId,Q=new URLSearchParams,X=L(b,"period"),G=L(b,"start"),J=L(b,"end");if(X)Q.set("period",X);if(G)Q.set("start",G);if(J)Q.set("end",J);if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");$=await D("GET",`/api/v1/ab-tests/${b.abTestId}/stats${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"restart_ab_test":{let W=b.companyId,Q=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),X=Object.keys(b).filter((H)=>!Q.has(H));if(X.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${X.length===1?"":"s"}: ${X.map((H)=>`\`${H}\``).join(", ")}.`);let G=L(b,"testType");if(G!==void 0&&G!=="subject"&&G!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let J=b.winnerThreshold===void 0?void 0:Number(b.winnerThreshold);if(J!==void 0&&(!Number.isInteger(J)||J<10||J>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let Y=b.variantCount===void 0?void 0:Number(b.variantCount);if(Y!==void 0&&(!Number.isInteger(Y)||Y<2||Y>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");$=await D("POST",`/api/v1/ab-tests/${b.abTestId}/restart`,{sourceVariantId:L(b,"sourceVariantId"),testType:G,winnerThreshold:J,variantCount:Y},W);break}case"update_ab_test_variant":{let W=b.companyId,Q=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks","confirmLiveChange"]),X=Object.keys(b).filter((G)=>!Q.has(G));if(X.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`confirmLiveChange\` fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);if(_w("update_ab_test_variant",b),b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test_variant`.");if(b.subject===void 0&&b.previewText===void 0&&b.html===void 0&&b.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");$=await D("PATCH",`/api/v1/ab-tests/${b.abTestId}/variants/${b.variantId}`,b,W);break}case"update_ab_test":{let W=b.companyId,Q=V("update_ab_test",b,"abTestId"),X=new Set(["companyId","abTestId","name","testPercentage","testDurationMinutes","winnerCriteria","testType","winnerThreshold","confirmLiveChange"]),G=Object.keys(b).filter((F)=>!X.has(F));if(G.length>0)throw Error(`\`update_ab_test\` received unsupported field${G.length===1?"":"s"}: ${G.map((F)=>`\`${F}\``).join(", ")}.`);if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test`.");let J=L(b,"name"),Y=Yw("update_ab_test",b,"testPercentage",5,50),H=Yw("update_ab_test",b,"testDurationMinutes",15,1440),z=m("update_ab_test",b,"winnerCriteria",["open_rate","click_rate"]),B=m("update_ab_test",b,"testType",["subject","content"]),A=Yw("update_ab_test",b,"winnerThreshold",10,1000);if(J===void 0&&Y===void 0&&H===void 0&&z===void 0&&B===void 0&&A===void 0)throw Error("Provide at least one of `name`, `testPercentage`, `testDurationMinutes`, `winnerCriteria`, `testType`, or `winnerThreshold` when calling `update_ab_test`.");$=await D("PATCH",`/api/v1/ab-tests/${encodeURIComponent(Q)}`,{...J!==void 0&&{name:J},...Y!==void 0&&{testPercentage:Y},...H!==void 0&&{testDurationMinutes:H},...z!==void 0&&{winnerCriteria:z},...B!==void 0&&{testType:B},...A!==void 0&&{winnerThreshold:A},...b.confirmLiveChange===!0&&{confirmLiveChange:!0}},W);break}case"create_ab_test":{let W=b.companyId,Q=L(b,"campaignId"),X=L(b,"automationNodeId");if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `create_ab_test`.");if(Boolean(Q)===Boolean(X))throw Error("Provide exactly one of `campaignId` or `automationNodeId` when calling `create_ab_test`.");let G=L(b,"name"),J=Yw("create_ab_test",b,"testPercentage",5,50),Y=Yw("create_ab_test",b,"testDurationMinutes",15,1440),H=m("create_ab_test",b,"winnerCriteria",["open_rate","click_rate"]),z=m("create_ab_test",b,"testType",["subject","content"]),B=Yw("create_ab_test",b,"winnerThreshold",10,1000);if(b.variants!==void 0){if(!Array.isArray(b.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");b.variants.forEach((F,U)=>{if(!C(F)||typeof F.subject!=="string"||F.subject.trim()==="")throw Error(`\`variants\` item ${U+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(F.blocks!==void 0&&!Array.isArray(F.blocks))throw Error(`\`variants\` item ${U+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}let A=Array.isArray(b.variants)?b.variants:void 0;if(X!==void 0&&(!A||A.length<1))throw Error("`variants` must include at least one competing variant when calling `create_ab_test` with `automationNodeId`.");if(A&&A.length>4)throw Error("`variants` supports at most four extra variants when calling `create_ab_test`.");$=await D("POST","/api/v1/ab-tests",{...Q!==void 0&&{campaignId:Q},...X!==void 0&&{automationNodeId:X},...b.confirmLiveChange===!0&&{confirmLiveChange:!0},...G!==void 0&&{name:G},...J!==void 0&&{testPercentage:J},...Y!==void 0&&{testDurationMinutes:Y},...H!==void 0&&{winnerCriteria:H},...z!==void 0&&{testType:z},...B!==void 0&&{winnerThreshold:B},...b.variants!==void 0&&{variants:b.variants}},W);break}case"add_ab_test_variant":{let W=b.companyId,Q=V("add_ab_test_variant",b,"abTestId"),X=V("add_ab_test_variant",b,"subject"),G=L(b,"previewText");if(b.blocks!==void 0&&!Array.isArray(b.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `add_ab_test_variant`.");$=await D("POST",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants`,{subject:X,...G!==void 0&&{previewText:G},...b.blocks!==void 0&&{blocks:b.blocks},...b.confirmLiveChange===!0&&{confirmLiveChange:!0}},W);break}case"delete_ab_test_variant":{let W=b.companyId,Q=V("delete_ab_test_variant",b,"abTestId"),X=V("delete_ab_test_variant",b,"variantId");if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `delete_ab_test_variant`.");$=await D("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants/${encodeURIComponent(X)}${b.confirmLiveChange===!0?"?confirmLiveChange=true":""}`,void 0,W);break}case"delete_ab_test":{let W=b.companyId,Q=V("delete_ab_test",b,"abTestId");$=await D("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}`,void 0,W);break}case"list_campaigns":{let W=b.companyId,Q=new URLSearchParams;if(b.status)Q.set("status",String(b.status));let X=L(b,"label");if(X)Q.set("label",X);for(let G of["limit","offset"])if(b[G]!==void 0)Q.set(G,String(b[G]));$=await D("GET",`/api/v1/campaigns?${Q}`,void 0,W);break}case"get_campaign":{let W=b.companyId;$=await D("GET",`/api/v1/campaigns/${b.campaignId}`,void 0,W);break}case"get_campaign_audience":{let W=b.companyId;$=await D("GET",`/api/v1/campaigns/${encodeURIComponent(String(b.campaignId))}/audience`,void 0,W);break}case"get_email_send":{let W=b.companyId;$=await D("GET",`/api/v1/email-sends/${encodeURIComponent(String(b.emailSendId))}`,void 0,W);break}case"list_email_sends":{let W=b.companyId,Q=new URLSearchParams,X=["search","subject","recipient","campaignId","transactionalEmailId","automationId","automationNodeId"];for(let q of X){let P=L(b,q);if(P)Q.set(q,P)}let G=m("list_email_sends",b,"status",["pending","sent","delivered","opened","clicked","bounced","complained","failed","suppressed"]),J=m("list_email_sends",b,"emailType",["campaign","transactional","sequence"]),Y=m("list_email_sends",b,"bounceType",["Permanent","Transient"]),H=m("list_email_sends",b,"sortField",["recipientEmail","subject","status","eventAt","sentAt","createdAt"]),z=m("list_email_sends",b,"sortOrder",["asc","desc"]),B=Yw("list_email_sends",b,"days",1,14),A=Yw("list_email_sends",b,"page",1,Number.MAX_SAFE_INTEGER),F=Yw("list_email_sends",b,"limit",1,100),U=[["status",G],["emailType",J],["bounceType",Y],["sortField",H],["sortOrder",z],["days",B],["page",A],["limit",F]];for(let[q,P]of U)if(P!==void 0)Q.set(q,String(P));let M=Q.toString();$=await D("GET",`/api/v1/email-sends${M?`?${M}`:""}`,void 0,W);break}case"create_campaign":{let W=b.companyId;O5(b),L0("create_campaign",b);let Q=Object.fromEntries(Object.entries(b).filter(([X])=>X!=="companyId"));$=await D("POST","/api/v1/campaigns",Q,W);break}case"update_campaign":{let W=b.companyId,Q=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","ccEmails","bccEmails","campaignData","computedLists","targetLists","segmentId","labels"]),X=Object.keys(b).filter((G)=>!Q.has(G));if(X.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, audience, and label update fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);if(_w("update_campaign",b),L1("update_campaign",b),L0("update_campaign",b,{replyFirst:!0}),b.segmentId!==void 0&&b.targetLists!==void 0)throw Error("Provide either `segmentId` or `targetLists` when calling `update_campaign`, not both.");if(b.name===void 0&&b.subject===void 0&&b.trackingCode===void 0&&b.html===void 0&&b.blocks===void 0&&b.fromEmail===void 0&&b.senderProfileId===void 0&&b.replyTo===void 0&&b.replyProfileId===void 0&&b.ccEmails===void 0&&b.bccEmails===void 0&&b.campaignData===void 0&&b.computedLists===void 0&&b.targetLists===void 0&&b.segmentId===void 0&&b.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, audience, or label field when calling `update_campaign`.");$=await D("PUT",`/api/v1/campaigns/${b.campaignId}`,b,W);break}case"schedule_campaign":{let W=b.companyId,Q=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),X=Object.keys(b).filter((G)=>!Q.has(G));if(X.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);V5(b),$=await D("POST",`/api/v1/campaigns/${b.campaignId}/schedule`,{scheduledAt:b.scheduledAt,...b.targetLists!==void 0&&{targetLists:b.targetLists},...b.sendTimeOptimization!==void 0&&{sendTimeOptimization:b.sendTimeOptimization},...b.spreadOverHours!==void 0&&{spreadOverHours:b.spreadOverHours},...b.recurringInterval!==void 0&&{recurringInterval:b.recurringInterval}},W);break}case"send_test_email":{let W=b.companyId;$=await D("POST",`/api/v1/campaigns/${b.campaignId}/test`,{to:b.to},W);break}case"cancel_campaign":{let W=b.companyId,Q=V("cancel_campaign",b,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/cancel`,void 0,W);break}case"unschedule_campaign":{let W=b.companyId,Q=V("unschedule_campaign",b,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/unschedule`,void 0,W);break}case"pause_campaign":{let W=b.companyId,Q=V("pause_campaign",b,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/pause`,void 0,W);break}case"resume_campaign":{let W=b.companyId,Q=V("resume_campaign",b,"campaignId"),X=Yw("resume_campaign",b,"spreadOverHours",1,72);$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resume`,{...X!==void 0&&{spreadOverHours:X}},W);break}case"delete_campaign":{let W=b.companyId,Q=V("delete_campaign",b,"campaignId");$=await D("DELETE",`/api/v1/campaigns/${encodeURIComponent(Q)}`,void 0,W);break}case"duplicate_campaign":{let W=b.companyId,Q=V("duplicate_campaign",b,"campaignId"),X=m("duplicate_campaign",b,"mode",["campaign","ab_test","variant"]),G=L(b,"variantId");if(X==="variant"&&G===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/duplicate`,{...X!==void 0&&{mode:X},...G!==void 0&&{variantId:G}},W);break}case"resend_campaign_to_non_openers":{let W=b.companyId,Q=V("resend_campaign_to_non_openers",b,"campaignId");$=await D("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resend-to-non-openers`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Z3(w,b){let $;switch(w){case"list_forms":{let W=b.companyId;$=await D("GET","/api/v1/forms",void 0,W);break}case"create_form":{let W=b.companyId,Q=V("create_form",b,"name"),X=Array.isArray(b.listIds)?b.listIds.filter((Y)=>typeof Y==="string").map((Y)=>Y.trim()).filter(Boolean):[];if(X.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let G=m("create_form",b,"duplicateStrategy",["skip","merge","overwrite"]),J={name:Q,listIds:X};for(let Y of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName","theme"])if(b[Y]!==void 0)J[Y]=b[Y];if(G!==void 0)J.duplicateStrategy=G;$=await D("POST","/api/v1/forms",J,W);break}case"update_form":{let W=b.companyId,Q=V("update_form",b,"formId"),X=m("update_form",b,"duplicateStrategy",["skip","merge","overwrite"]),G={};for(let J of["name","listIds","tagIds","buttonText","headline","description","successMessage","redirectUrl","theme","blocks"])if(b[J]!==void 0)G[J]=b[J];if(X!==void 0)G.duplicateStrategy=X;if(Object.keys(G).length===0)throw Error("Provide at least one field to change when calling `update_form`.");$=await D("PATCH",`/api/v1/forms/${encodeURIComponent(Q)}`,G,W);break}case"get_form_embed":{let W=b.companyId,Q=V("get_form_embed",b,"formId");$=await D("GET",`/api/v1/forms/embed/${encodeURIComponent(Q)}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function Y4(w,b,$,W,Q){let X=w[b];if(X===void 0)return;if(typeof X!=="number"||!Number.isFinite(X)||X<$||X>W||Q&&!Number.isInteger(X))throw Error(`\`${b}\` must be a ${Q?"integer":"number"} between ${$} and ${W} when calling \`upload_image_asset\`.`);return X}async function V3(w,b){if(w!=="upload_image_asset")return{handled:!1,result:void 0};let $=L(b,"filePath"),W=L(b,"imageBase64");if($===void 0===(W===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let Q=L(b,"filename");if(W!==void 0&&Q===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let X=Y4(b,"sourceWidth",1,20000,!0),G=Y4(b,"sourceHeight",1,20000,!0);if(X===void 0!==(G===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let J=Y4(b,"displayWidthPercent",1,100,!1)??100,Y=Y4(b,"cropHeight",1,2000,!0),H=L(b,"objectFit");if(H!==void 0&&H!=="cover"&&H!=="contain")throw Error("`objectFit` must be 'cover' or 'contain' when calling `upload_image_asset`.");if(H!==void 0&&Y===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let z=L(b,"align");if(z!==void 0&&!["left","center","right"].includes(z))throw Error("`align` must be 'left', 'center', or 'right' when calling `upload_image_asset`.");let B=typeof b.altText==="string"?b.altText.trim():void 0;if(B!==void 0&&B.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let A=await _5({companyId:L(b,"companyId"),filePath:$,imageBase64:W,filename:Q,contentType:L(b,"contentType"),altText:B,sourceWidth:X,sourceHeight:G}),F={type:"image",src:A.url,alt:A.altText??"",width:J,widthType:"percent",...Y!==void 0&&{height:Y,objectFit:H??"cover"},...z!==void 0&&{align:z}};return{handled:!0,result:{success:!0,asset:A,imageBlock:F,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}async function M3(w,b){let $=b.companyId,W;switch(w){case"connect_integration":{let Q=V("connect_integration",b,"provider"),X=V("connect_integration",b,"webhookSecret");W=await D("POST","/api/v1/integrations/connect",{provider:Q,webhookSecret:X,...typeof b.apiKey==="string"&&b.apiKey?{apiKey:b.apiKey}:{},...typeof b.providerAccountId==="string"&&b.providerAccountId?{providerAccountId:b.providerAccountId}:{},...b.settings!==void 0?{settings:b.settings}:{},...b.historyImport!==void 0?{historyImport:b.historyImport}:{}},$);break}case"get_integration":{let Q=V("get_integration",b,"integrationId");W=await D("GET",`/api/v1/integrations/${encodeURIComponent(Q)}`,void 0,$);break}case"list_integration_capabilities":{let Q=new URLSearchParams;if(typeof b.provider==="string"&&b.provider)Q.set("provider",b.provider);if(typeof b.category==="string"&&b.category)Q.set("category",b.category);let X=Q.toString();W=await D("GET",`/api/v1/integrations/catalog${X?`?${X}`:""}`,void 0,$);break}case"list_integration_activity":{let Q=new URLSearchParams;if(typeof b.integrationId==="string"&&b.integrationId)Q.set("integrationId",b.integrationId);if(typeof b.provider==="string"&&b.provider)Q.set("provider",b.provider);if(typeof b.status==="string"&&b.status)Q.set("status",b.status);if(typeof b.limit==="number")Q.set("limit",String(b.limit));let X=Q.toString();W=await D("GET",`/api/v1/integrations/activity${X?`?${X}`:""}`,void 0,$);break}case"set_integration_sync_enabled":{let Q=V("set_integration_sync_enabled",b,"integrationId");if(typeof b.syncEnabled!=="boolean")throw Error("`syncEnabled` must be a boolean when calling `set_integration_sync_enabled`.");W=await D("PATCH",`/api/v1/integrations/${encodeURIComponent(Q)}`,{syncEnabled:b.syncEnabled},$);break}case"get_integration_pixel":{let Q=V("get_integration_pixel",b,"integrationId");W=await D("GET",`/api/v1/integrations/${encodeURIComponent(Q)}/pixel`,void 0,$);break}case"activate_integration_pixel":{let Q=V("activate_integration_pixel",b,"integrationId");W=await D("POST",`/api/v1/integrations/${encodeURIComponent(Q)}/pixel`,void 0,$);break}case"sync_integration":{let Q=V("sync_integration",b,"integrationId");W=await D("POST",`/api/v1/integrations/${encodeURIComponent(Q)}/sync`,void 0,$);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:W}}async function j3(w,b){let $;switch(w){case"list_landing_pages":{let W=b.companyId;$=await D("GET","/api/v1/landing-pages",void 0,W);break}case"get_landing_page":{let W=b.companyId;$=await D("GET",`/api/v1/landing-pages/${b.landingPageId}`,void 0,W);break}case"create_landing_page":{let W=b.companyId,Q=new Set(["companyId","name","slug","template","content"]),X=Object.keys(b).filter((G)=>!Q.has(G));if(X.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${X.length===1?"":"s"}: ${X.map((G)=>`\`${G}\``).join(", ")}.`);$=await D("POST","/api/v1/landing-pages",{...b.name!==void 0&&{name:b.name},...b.slug!==void 0&&{slug:b.slug},...b.template!==void 0&&{template:b.template},...b.content!==void 0&&{content:b.content}},W);break}case"update_landing_page":{let W=b.companyId,Q=W4("update_landing_page",b,{requireUpdate:!0});$=await D("PUT",`/api/v1/landing-pages/${b.landingPageId}`,Q,W);break}case"publish_landing_page":{let W=b.companyId,Q=W4("publish_landing_page",b,{requireUpdate:!1});$=await D("POST",`/api/v1/landing-pages/${b.landingPageId}/publish`,Q,W);break}case"unpublish_landing_page":{let W=b.companyId,Q=W4("unpublish_landing_page",b,{requireUpdate:!1});$=await D("POST",`/api/v1/landing-pages/${b.landingPageId}/unpublish`,Q,W);break}case"duplicate_landing_page":{let W=b.companyId;$=await D("POST",`/api/v1/landing-pages/${b.landingPageId}/duplicate`,{...b.name!==void 0&&{name:b.name},...b.slug!==void 0&&{slug:b.slug}},W);break}case"delete_landing_page":{let W=b.companyId;$=await D("DELETE",`/api/v1/landing-pages/${b.landingPageId}`,void 0,W);break}case"connect_landing_page_domain":{let W=b.companyId;$=await D("POST","/api/v1/landing-pages/domain",{domain:b.domain},W);break}case"update_landing_page_domain_settings":{let W=b.companyId,Q=M5(b);$=await D("PUT","/api/v1/landing-pages/domain",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function q3(w,b){let $;switch(w){case"list_products":{let W=b.companyId,Q=new URLSearchParams;if(typeof b.provider==="string"&&b.provider.trim())Q.set("provider",b.provider.trim());if(typeof b.search==="string"&&b.search.trim())Q.set("search",b.search.trim());let X=Yw("list_products",b,"limit",1,100);if(X!==void 0)Q.set("limit",String(X));let G=Yw("list_products",b,"offset",0,Number.MAX_SAFE_INTEGER);if(G!==void 0)Q.set("offset",String(G));let J=Q.size>0?`?${Q.toString()}`:"";$=await D("GET",`/api/v1/products${J}`,void 0,W);break}case"upsert_products":{let W=b.companyId;if(!Array.isArray(b.products)||b.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");$=await D("POST","/api/v1/products",{products:b.products},W);break}case"delete_product":{let W=b.companyId,Q=V("delete_product",b,"productId");$=await D("DELETE",`/api/v1/products/${encodeURIComponent(Q)}`,void 0,W);break}case"attach_product_file":{let W=b.companyId,Q=V("attach_product_file",b,"productId"),X=L(b,"url"),G=L(b,"filePath");if(X===void 0===(G===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let J;if(G!==void 0){let Y=await T5(G,W);J={url:Y.url,source:"upload",fileName:L(b,"fileName")??Y.fileName,fileSizeBytes:Y.fileSizeBytes,mimeType:Y.mimeType}}else{J={url:X};let Y=L(b,"fileName");if(Y)J.fileName=Y}$=await D("PUT",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,J,W);break}case"remove_product_file":{let W=b.companyId,Q=V("remove_product_file",b,"productId");$=await D("DELETE",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,void 0,W);break}case"sync_products":{let W=b.companyId,Q=new URLSearchParams;if(typeof b.integrationId==="string"&&b.integrationId)Q.set("integrationId",b.integrationId);let X=Q.toString();$=await D("POST",`/api/v1/products/sync${X?`?${X}`:""}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function Rj(w){let b=L(w,"campaignId"),$=L(w,"sequenceId"),W=L(w,"templateId"),Q=[b,$,W].filter((X)=>X!==void 0);if(Q.length===0)throw Error("render_email requires one of campaignId, sequenceId plus nodeId, or templateId.");if(Q.length>1)throw Error("render_email accepts exactly one of campaignId, sequenceId, or templateId.");if(b!==void 0)return`/api/v1/campaigns/${encodeURIComponent(b)}/render`;if($!==void 0){let X=V("render_email",w,"nodeId");return`/api/v1/sequences/${encodeURIComponent($)}/nodes/${encodeURIComponent(X)}/render`}return`/api/v1/templates/${encodeURIComponent(W)}/render`}var Sj=["subscriberId","subscriber","variables","locale","variantId","tracking"];async function P3(w,b){if(w!=="render_email")return{handled:!1,result:void 0};let $=Rj(b),W={};for(let X of Sj)if(b[X]!==void 0)W[X]=b[X];return{handled:!0,result:await D("POST",$,W,L(b,"companyId"))}}var I3=80,N3=10;function vj(w){if(!Array.isArray(w.recipients))throw Error("`recipients` must be an array when calling `send_sequence_test_email`.");if(w.recipients.length>N3)throw Error(`\`recipients\` must include no more than ${N3} email addresses when calling \`send_sequence_test_email\`.`);if(w.recipients.find((Q)=>typeof Q!=="string"||Q.trim().length===0)!==void 0)throw Error("Every `recipients` item must be a non-empty email address when calling `send_sequence_test_email`.");let $=Array.from(new Set(w.recipients.map((Q)=>typeof Q==="string"?Q.trim().toLowerCase():""))).filter(Boolean);if($.length===0)throw Error("`recipients` must include at least one email address when calling `send_sequence_test_email`.");let W=$.find((Q)=>!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Q));if(W)throw Error(`Invalid test recipient email address: \`${W}\`.`);return $}function Cj(w){let b=w.trim().replace(/\s+/g," ");if(b.length<=I3)return b;return`${b.slice(0,I3-3).trimEnd()}...`}async function XW(w,b){let $;switch(w){case"generate_sequence":{let W=V("generate_sequence",b,"goal"),Q=typeof b.name==="string"&&b.name.trim().length>0?b.name.trim():void 0,G=(await XW("create_sequence",{...b,goal:W,name:Q??Cj(W),trigger:"contact_added",durationDays:b.durationDays??14})).result;return{handled:!0,result:typeof G==="object"&&G!==null?{...G,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:G}}case"list_sequences":{let W=b.companyId,Q=new URLSearchParams;for(let G of["status","search","limit","offset"])if(b[G]!==void 0)Q.set(G,String(b[G]));if(Array.isArray(b.labels)&&b.labels.length>0)Q.set("labels",b.labels.join(","));let X=Q.size>0?`?${Q.toString()}`:"";$=await D("GET",`/api/v1/sequences${X}`,void 0,W);break}case"get_sequence":{let W=b.companyId;$=await D("GET",`/api/v1/sequences/${b.sequenceId}`,void 0,W);break}case"list_sequence_enrollments":{let W=b.companyId,Q=V(w,b,"sequenceId"),X=new URLSearchParams;for(let J of["currentNodeId","status","subscriberId"]){let Y=b[J];if(Array.isArray(Y)){if(Y.length>0)X.set(J,Y.join(","))}else if(Y!==void 0)X.set(J,String(Y))}for(let J of["email","sort","limit","offset"])if(b[J]!==void 0)X.set(J,String(b[J]));let G=X.size>0?`?${X.toString()}`:"";$=await D("GET",`/api/v1/sequences/${encodeURIComponent(Q)}/enrollments${G}`,void 0,W);break}case"send_sequence_test_email":{let W=b.companyId,Q=V(w,b,"sequenceId"),X=V(w,b,"nodeId"),G=vj(b);$=await D("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/nodes/${encodeURIComponent(X)}/test`,{recipients:G},W);break}case"create_sequence":{let W=b.companyId;L1("create_sequence",b),L0("create_sequence",b);let Q=Array.isArray(b.steps),X=b.goal===void 0&&b.steps===void 0,G=await D("POST","/api/v1/sequences",b,W);if(!G.success){$=G;break}let J=G.sequence.id;if(Q||X){let A=await D("GET",`/api/v1/sequences/${J}`,void 0,W);if(A.success)$={...G,success:!0,sequence:A.sequence,message:`Sequence "${A.sequence.name}" created ${X?"as a blank draft":"with explicit steps"}. Review it before enabling.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=A;break}let Y=7,H=0,z="pending";while(z!=="complete"&&H<Y){let A=await D("GET",`/api/v1/sequences/${J}`,void 0,W);if(A.success)z=A.sequence.enrichmentStatus;if(H++,z!=="complete"&&H<Y)await new Promise((F)=>setTimeout(F,20000))}let B=await D("GET",`/api/v1/sequences/${J}`,void 0,W);if(B.success)$={...G,success:!0,sequence:B.sequence,message:B.sequence.enrichmentStatus==="complete"?`Sequence "${B.sequence.name}" created with ${B.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${B.sequence.name}" created. Email enrichment is still in progress (${B.sequence.enrichedCount}/${B.sequence.emailCount} emails generated). You can check status with get_sequence.${G.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=B;break}case"update_sequence":{let W=b.companyId,Q=Y5(b);$=await D("PUT",`/api/v1/sequences/${b.sequenceId}`,Q,W);break}case"update_sequence_node":{let W=b.companyId,Q=V("update_sequence_node",b,"sequenceId"),X=A5(b);$=await D("PUT",`/api/v1/sequences/${Q}`,X,W);break}case"update_sequence_nodes":{let W=b.companyId,Q=V("update_sequence_nodes",b,"sequenceId"),X=F5(b);$=await D("PUT",`/api/v1/sequences/${Q}`,X,W);break}case"edit_sequence_graph":{let W=b.companyId,Q=L5(b);$=await D("PUT",`/api/v1/sequences/${b.sequenceId}`,Q,W);break}case"insert_sequence_step":{let W=b.companyId,Q=U5(b),X=await D("PUT",`/api/v1/sequences/${b.sequenceId}`,Q,W);if(typeof X==="object"&&X!==null){let G=X,J=G.sequence;if(typeof J==="object"&&J!==null){let Y=J;$={...G,...Y.insertedNodeIds!==void 0?{insertedNodeIds:Y.insertedNodeIds}:{},...Y.insertedEmailIds!==void 0?{insertedEmailIds:Y.insertedEmailIds}:{},...Y.insertedEmailCount!==void 0?{insertedEmailCount:Y.insertedEmailCount}:{},...Y.addedBranchNodeId!==void 0?{addedBranchNodeId:Y.addedBranchNodeId}:{},...Y.addedBranchPathNodeIds!==void 0?{addedBranchPathNodeIds:Y.addedBranchPathNodeIds}:{}};break}}$=X;break}case"enable_sequence":{let W=b.companyId;$=await D("POST",`/api/v1/sequences/${b.sequenceId}/enable`,void 0,W);break}case"disable_sequence":{let W=b.companyId;$=await D("POST",`/api/v1/sequences/${b.sequenceId}/disable`,void 0,W);break}case"duplicate_sequence":{let W=b.companyId,Q=V("duplicate_sequence",b,"sequenceId"),X=L(b,"name");$=await D("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/duplicate`,X===void 0?void 0:{name:X},W);break}case"archive_sequence":case"unarchive_sequence":{let W=b.companyId,Q=V(w,b,"sequenceId"),X=w==="archive_sequence"?"archive":"unarchive";$=await D("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/${X}`,void 0,W);break}case"list_sequence_goals":{let W=b.companyId,Q=V(w,b,"sequenceId");$=await D("GET",`/api/v1/sequences/${encodeURIComponent(Q)}/goals`,void 0,W);break}case"create_sequence_goal":case"update_sequence_goal":{let W=b.companyId,Q=V(w,b,"sequenceId");if(w==="create_sequence_goal")V(w,b,"name"),H5(b);else z5(b);let X=w==="update_sequence_goal"?V(w,b,"goalId"):void 0,G={...b};delete G.companyId,delete G.sequenceId,delete G.goalId,$=await D(w==="create_sequence_goal"?"POST":"PATCH",`/api/v1/sequences/${encodeURIComponent(Q)}/goals${X?`/${encodeURIComponent(X)}`:""}`,G,W);break}case"delete_sequence_goal":{let W=b.companyId,Q=V(w,b,"sequenceId"),X=V(w,b,"goalId");$=await D("DELETE",`/api/v1/sequences/${encodeURIComponent(Q)}/goals/${encodeURIComponent(X)}`,void 0,W);break}case"get_sequence_inbound_webhook":case"configure_sequence_inbound_webhook":case"rotate_sequence_inbound_webhook_secret":{let W=b.companyId,Q=V(w,b,"sequenceId");if(b.clearFieldMapping===!0&&b.fieldMapping!==void 0)throw Error("Provide either `fieldMapping` or `clearFieldMapping`, not both.");if(b.clearSamplePayload===!0&&b.samplePayload!==void 0)throw Error("Provide either `samplePayload` or `clearSamplePayload`, not both.");let X=w==="configure_sequence_inbound_webhook",G=w==="rotate_sequence_inbound_webhook_secret",J=X?{...b.clearFieldMapping===!0?{fieldMapping:null}:b.fieldMapping!==void 0?{fieldMapping:b.fieldMapping}:{},...b.clearSamplePayload===!0?{samplePayload:null}:b.samplePayload!==void 0?{samplePayload:b.samplePayload}:{}}:void 0;$=await D(G?"POST":X?"PUT":"GET",`/api/v1/sequences/${encodeURIComponent(Q)}/inbound-webhook${G?"/rotate-secret":""}`,J,W);break}case"pause_sequence_enrollments":{let W=b.companyId;$=await D("POST",`/api/v1/sequences/${b.sequenceId}/pause-enrollments`,void 0,W);break}case"resume_sequence_enrollments":{let W=b.companyId;$=await D("POST",`/api/v1/sequences/${b.sequenceId}/resume-enrollments`,void 0,W);break}case"enroll_subscribers_in_sequence":{let W=b.companyId,Q=V("enroll_subscribers_in_sequence",b,"sequenceId"),X=E5(b);$=await D("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/enroll`,X,W);break}case"cancel_sequence_enrollments":{let W=b.companyId,Q=K5(b);$=await D("POST",`/api/v1/sequences/${b.sequenceId}/enrollments/cancel`,Q,W);break}case"delete_sequence":{let W=b.companyId;$=await D("DELETE",`/api/v1/sequences/${b.sequenceId}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function H4(w,b,$){let W=b[$];if(W===void 0)return;if(!Array.isArray(W))throw Error(`\`${$}\` must be an array of strings when calling \`${w}\`.`);let Q=W.filter((X)=>typeof X==="string").map((X)=>X.trim()).filter((X)=>X.length>0);if(Q.length!==W.length)throw Error(`\`${$}\` must contain only non-empty strings when calling \`${w}\`.`);return Q}function kj(w,b){let $=H4(w,b,"tags");if($===void 0||$.length===0)throw Error(`\`tags\` must contain at least one tag when calling \`${w}\`.`);let W=H4(w,b,"emails"),Q=H4(w,b,"externalIds"),X=H4(w,b,"subscriberIds");if((W?.length??0)+(Q?.length??0)+(X?.length??0)===0)throw Error(`Provide \`emails\`, \`externalIds\`, or \`subscriberIds\` when calling \`${w}\`.`);return{tags:$,...W?.length?{emails:W}:{},...Q?.length?{externalIds:Q}:{},...X?.length?{subscriberIds:X}:{},...w==="bulk_add_subscriber_tags"&&typeof b.triggerAutomations==="boolean"?{triggerAutomations:b.triggerAutomations}:{}}}async function E3(w,b){let $;switch(w){case"add_subscriber":{let W=b.companyId,Q=typeof b.phone==="string"&&b.phone.trim()!==""?b.phone.trim():void 0,X=Q?r9(b):tw("add_subscriber",b),G=m("add_subscriber",b,"status",["active","unsubscribed","bounced"]),J=m("add_subscriber",b,"optInMode",["default","confirmed","double_opt_in"]);if($=await D("POST","/api/v1/subscribers",{...X,...Q!==void 0&&{phone:Q},...typeof b.phoneCountry==="string"&&b.phoneCountry.trim()!==""&&{phoneCountry:b.phoneCountry.trim()},...typeof b.smsConsent==="boolean"&&{smsConsent:b.smsConsent},...b.firstName!==void 0&&{firstName:b.firstName},...b.lastName!==void 0&&{lastName:b.lastName},customAttributes:b.attributes,tags:b.tags,lists:b.listIds,...G!==void 0&&{status:G},...J!==void 0&&{optInMode:J},...b.createdAt!==void 0&&{createdAt:b.createdAt}},W),G!==void 0&&C($)&&C($.subscriber)&&$.subscriber.skipped===!0&&$.subscriber.status!==G)throw Error(`Existing subscriber was not changed to status '${G}'. Use update_subscriber to change an existing contact's status.`);break}case"create_subscriber_import":{let W=b.companyId;if(!Array.isArray(b.subscribers)||b.subscribers.length===0)throw Error("`subscribers` must be a non-empty array when calling `create_subscriber_import`.");if(b.subscribers.length>5000)throw Error("`create_subscriber_import` accepts at most 5000 subscriber records per call.");for(let G=0;G<b.subscribers.length;G+=1){let J=b.subscribers[G],Y=C(J)&&typeof J.email==="string"&&J.email.trim()!=="",H=C(J)&&typeof J.phone==="string"&&J.phone.trim()!=="";if(!Y&&!H)throw Error(`Subscriber record ${G} must include an email or a phone number.`)}let Q=m("create_subscriber_import",b,"duplicateStrategy",["skip","merge","overwrite"]),X=m("create_subscriber_import",b,"optInMode",["default","confirmed","double_opt_in"]);$=await D("POST","/api/v1/subscribers/imports",{subscribers:b.subscribers,...Q!==void 0&&{duplicateStrategy:Q},...b.fileName!==void 0&&{fileName:b.fileName},...b.listIds!==void 0&&{listIds:b.listIds},...b.enrollInSequences!==void 0&&{enrollInSequences:b.enrollInSequences},...b.defaultPhoneCountry!==void 0&&{defaultPhoneCountry:b.defaultPhoneCountry},...b.smsConsent!==void 0&&{smsConsent:b.smsConsent},...X!==void 0&&{optInMode:X}},W);break}case"get_subscriber_import":{let W=b.companyId,Q=V("get_subscriber_import",b,"importId");$=await D("GET",`/api/v1/subscribers/imports/${encodeURIComponent(Q)}`,void 0,W);break}case"update_subscriber":{let W=b.companyId,Q=tw("update_subscriber",b),X=m("update_subscriber",b,"status",["active","unsubscribed","bounced"]),J=C(b.attributes)||b.addTags!==void 0||b.removeTags!==void 0?await Mb(Q,W):null,Y=Array.isArray(J?.subscriber.tags)?J.subscriber.tags.filter((F)=>typeof F==="string"):[],H=Array.isArray(b.addTags)?b.addTags.filter((F)=>typeof F==="string"&&F.trim()!=="").map(t9):[],z=new Set(Array.isArray(b.removeTags)?b.removeTags.filter((F)=>typeof F==="string"&&F.trim()!=="").map(t9):[]),B=Y.filter((F)=>!z.has(F));for(let F of H)if(!B.includes(F))B.push(F);let A={};if(Q.email&&Q.externalId)A.externalId=Q.externalId;if(b.firstName!==void 0)A.firstName=b.firstName;if(b.lastName!==void 0)A.lastName=b.lastName;if(typeof b.phone==="string"||b.phone===null)A.phone=b.phone;if(typeof b.phoneCountry==="string")A.phoneCountry=b.phoneCountry;if(typeof b.smsConsent==="boolean")A.smsConsent=b.smsConsent;if(X!==void 0)A.status=X;if(C(b.attributes))A.customAttributes={...C(J?.subscriber.customAttributes)?J.subscriber.customAttributes:{},...b.attributes};if(b.addTags||b.removeTags)A.tags=B;$=await D("PATCH",Q4(Q),A,W);break}case"remove_subscriber":{let W=b.companyId,Q=tw("remove_subscriber",b),X=Q4(Q);if(b.hardDelete===!0)$=await D("DELETE",X,void 0,W);else $=await D("PATCH",X,{status:"unsubscribed"},W);break}case"get_subscriber":{let W=b.companyId,Q=tw("get_subscriber",b);$=await Mb(Q,W,{includeMachineEngagement:b.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let W=b.companyId,Q=tw("list_subscriber_notes",b);$=await D("GET",s9(Q),void 0,W);break}case"add_subscriber_note":{let W=b.companyId,Q=tw("add_subscriber_note",b),X=typeof b.body==="string"?b.body.trim():void 0;if(!X)throw Error("`body` is required when calling `add_subscriber_note`.");if(X.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");$=await D("POST",s9(Q),{body:X},W);break}case"delete_subscriber_note":{let W=b.companyId,Q=typeof b.noteId==="string"?b.noteId.trim():"";if(!Q)throw Error("`noteId` is required when calling `delete_subscriber_note`.");$=await D("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(Q)}`,void 0,W);break}case"trigger_subscriber_event":{let W=b.companyId,Q=tw("trigger_subscriber_event",b),X=V("trigger_subscriber_event",b,"event");if(b.properties!==void 0&&!C(b.properties))throw Error("`properties` must be an object when calling `trigger_subscriber_event`.");$=await D("POST","/api/v1/subscribers/events",{...Q,event:X,...b.properties!==void 0&&{properties:b.properties},...b.firstName!==void 0&&{firstName:b.firstName},...b.lastName!==void 0&&{lastName:b.lastName},...b.attributes!==void 0&&{customAttributes:b.attributes},...b.occurredAt!==void 0&&{occurredAt:b.occurredAt},...b.eventId!==void 0&&{eventId:b.eventId}},W);break}case"trigger_subscriber_events":{let W=b.companyId,Q=tw("trigger_subscriber_events",b);if(!Array.isArray(b.events)||b.events.length===0)throw Error("`events` must be a non-empty array when calling `trigger_subscriber_events`.");if(b.events.length>500)throw Error("`trigger_subscriber_events` accepts at most 500 events per call. Split a larger history import into several calls.");for(let X=0;X<b.events.length;X+=1){let G=b.events[X];if(!C(G)||typeof G.name!=="string"||G.name.trim()==="")throw Error(`Event ${X} must include a non-empty \`name\` string.`)}$=await D("POST","/api/v1/subscribers/events/bulk",{...Q,events:b.events,...b.firstName!==void 0&&{firstName:b.firstName},...b.lastName!==void 0&&{lastName:b.lastName},...b.attributes!==void 0&&{customAttributes:b.attributes}},W);break}case"bulk_add_subscriber_tags":case"bulk_remove_subscriber_tags":{let W=b.companyId,Q=kj(w,b);$=await D("POST",`/api/v1/subscribers/bulk/tags/${w==="bulk_add_subscriber_tags"?"add":"remove"}`,Q,W);break}case"search_subscribers":{let W=b.companyId;$=await N5(b,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function T3(w,b){if(w!=="get_recipient_suppression"&&w!=="remove_recipient_suppression")return{handled:!1,result:void 0};let $=L(b,"companyId"),W=V(w,b,"email"),Q=L(b,"region"),X=new URLSearchParams;if(Q)X.set("region",Q);let G=`/api/v1/suppressions/${encodeURIComponent(W)}${X.size>0?`?${X}`:""}`;return{handled:!0,result:await D(w==="get_recipient_suppression"?"GET":"DELETE",G,void 0,$)}}async function R3(w,b){let $;switch(w){case"list_team_members":{let W=b.companyId;$=await D("GET","/api/v1/team",void 0,W);break}case"invite_team_member":{let W=b.companyId,Q=V("invite_team_member",b,"email"),X=jb("invite_team_member",b,"role",["admin","viewer","restricted"]);if(b.canManageBilling!==void 0&&typeof b.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");$=await D("POST","/api/v1/team/invitations",{email:Q,role:X,...b.canManageBilling!==void 0&&{canManageBilling:b.canManageBilling}},W);break}case"cancel_team_invitation":{let W=b.companyId,Q=V("cancel_team_invitation",b,"invitationId");$=await D("DELETE",`/api/v1/team/invitations/${encodeURIComponent(Q)}`,void 0,W);break}case"list_conversations":{let W=b.companyId,Q=new URLSearchParams,X=m("list_conversations",b,"status",["open","closed","all"]);if(X)Q.set("status",X);let G=L(b,"search");if(G)Q.set("search",G);if(b.unread!==void 0){if(typeof b.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(b.unread)Q.set("unread","true")}if(b.page!==void 0){if(typeof b.page!=="number"||!Number.isInteger(b.page)||b.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");Q.set("page",String(b.page))}let J=Yw("list_conversations",b,"limit",1,100);if(J!==void 0)Q.set("limit",String(J));$=await D("GET",`/api/v1/conversations${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_conversation":{let W=b.companyId,Q=V("get_conversation",b,"conversationId");$=await D("GET",`/api/v1/conversations/${encodeURIComponent(Q)}`,void 0,W);break}case"reply_to_conversation":{let W=b.companyId,Q=V("reply_to_conversation",b,"conversationId"),X=m("reply_to_conversation",b,"type",["outbound","note"])??"outbound",G=L(b,"subject"),J=L(b,"bodyText"),Y=L(b,"bodyHtml");if(X==="outbound"&&J===void 0&&Y===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");$=await D("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/messages`,{type:X,...G!==void 0&&{subject:G},...J!==void 0&&{bodyText:J},...Y!==void 0&&{bodyHtml:Y}},W);break}case"update_conversation_status":{let W=b.companyId,Q=V("update_conversation_status",b,"conversationId"),X=jb("update_conversation_status",b,"status",["open","closed"]);$=await D("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/status`,{status:X},W);break}case"mark_conversation_read":{let W=b.companyId,Q=V("mark_conversation_read",b,"conversationId");$=await D("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/read`,void 0,W);break}case"list_webhooks":{let W=b.companyId;$=await D("GET","/api/v1/webhooks",void 0,W);break}case"create_webhook":{let W=b.companyId,Q=V("create_webhook",b,"name"),X=V("create_webhook",b,"url"),G=a9("create_webhook",b);$=await D("POST","/api/v1/webhooks",{name:Q,url:X,...G!==void 0&&{events:G}},W);break}case"update_webhook":{let W=b.companyId,Q=V("update_webhook",b,"webhookId"),X=L(b,"name"),G=L(b,"url"),J=a9("update_webhook",b),Y=m("update_webhook",b,"status",["enabled","disabled"]);if(X===void 0&&G===void 0&&J===void 0&&Y===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");$=await D("PATCH",`/api/v1/webhooks/${encodeURIComponent(Q)}`,{...X!==void 0&&{name:X},...G!==void 0&&{url:G},...J!==void 0&&{events:J},...Y!==void 0&&{status:Y}},W);break}case"delete_webhook":{let W=b.companyId,Q=V("delete_webhook",b,"webhookId");$=await D("DELETE",`/api/v1/webhooks/${encodeURIComponent(Q)}`,void 0,W);break}case"test_webhook":{let W=b.companyId,Q=V("test_webhook",b,"webhookId");$=await D("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/test`,void 0,W);break}case"list_webhook_deliveries":{let W=b.companyId,Q=V("list_webhook_deliveries",b,"webhookId"),X=Yw("list_webhook_deliveries",b,"limit",1,100),G=new URLSearchParams;if(X!==void 0)G.set("limit",String(X));$=await D("GET",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries${G.size>0?`?${G}`:""}`,void 0,W);break}case"replay_webhook_delivery":{let W=b.companyId,Q=V("replay_webhook_delivery",b,"webhookId"),X=V("replay_webhook_delivery",b,"deliveryId");$=await D("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries/${encodeURIComponent(X)}/replay`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var S3=[F3,M3,E3,T3,q3,K3,O3,P3,Z3,j3,V3,XW,U3,R3,L3];var _j=new Set(["create_campaign","update_campaign","create_template","update_template","set_template_localization","create_transactional_email","update_transactional_email","create_sequence","update_sequence","update_sequence_node","update_sequence_nodes","insert_sequence_step","update_ab_test_variant","create_ab_test"]);function v3(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}function GW(w){if(Array.isArray(w))return w.some(GW);if(!v3(w))return!1;for(let[b,$]of Object.entries(w)){if((b==="html"||b==="htmlContent")&&typeof $==="string"&&$.trim().length>0)return!0;if(GW($))return!0}return!1}function C3(w,b,$){if(!_j.has(w)||!GW(b)||!v3($))return $;let W=Array.isArray($.warnings)?$.warnings.filter((Q)=>typeof Q==="string"):[];return{...$,warnings:[...new Set([...W,Hw])]}}var k3=A3.map(f5).map(eH);async function _3(w,b){try{let $,W=!1;for(let X of S3){let G=await X(w,b);if(G.handled){$=G.result,W=!0;break}}if(!W)throw Error(`Unknown tool: ${w}`);let Q=q5($);if(Q)throw Q;return $=C3(w,b,$),$=await S5(w,b,$),{structuredContent:u5($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:K1($)}]}}}async function x3(w,b,$){let W=b.getRequestContext?.(w)??{};try{return await F4(W,$)}finally{await b.onRequestContextUpdated?.(W,w)}}function JW(w={}){let b=new N9({name:"sequenzy",version:pH.version},{capabilities:{tools:{},resources:{}},instructions:["Sequenzy email marketing MCP server: manage subscribers, campaigns, sequences, templates, and delivery stats.","If you have access to multiple companies, call get_account and then select_company (or pass companyId per call) before other tools.","IMPORTANT: whenever the user wanted to accomplish something and these tools did not expose functionality for it (missing tool, missing argument, unsupported workflow, or broken behavior), call submit_feedback describing the gap before finishing the task. The Sequenzy team reads every submission and uses it to decide what to build next."].join(`
52
+ `)});return b.setRequestHandler(A$,async()=>{return{tools:k3}}),b.setRequestHandler(i0,async($,W)=>{let{name:Q,arguments:X}=$.params;return x3(W,w,()=>_3(Q,X??{}))}),b.setRequestHandler(G$,async()=>{return{resources:tH}}),b.setRequestHandler(Y$,async($,W)=>{let{uri:Q}=$.params;return x3(W,w,()=>rH(Q))}),b}import y3 from"node:process";class YW{append(w){this._buffer=this._buffer?Buffer.concat([this._buffer,w]):w}readMessage(){if(!this._buffer)return null;let w=this._buffer.indexOf(`
53
+ `);if(w===-1)return null;let b=this._buffer.toString("utf8",0,w).replace(/\r$/,"");return this._buffer=this._buffer.subarray(w+1),xj(b)}clear(){this._buffer=void 0}}function xj(w){return bG.parse(JSON.parse(w))}function h3(w){return JSON.stringify(w)+`
54
+ `}class HW{constructor(w=y3.stdin,b=y3.stdout){this._stdin=w,this._stdout=b,this._readBuffer=new YW,this._started=!1,this._ondata=($)=>{this._readBuffer.append($),this.processReadBuffer()},this._onerror=($)=>{this.onerror?.($)}}async start(){if(this._started)throw 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(){while(!0)try{let w=this._readBuffer.readMessage();if(w===null)break;this.onmessage?.(w)}catch(w){this.onerror?.(w)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(w){return new Promise((b)=>{let $=h3(w);if(this._stdout.write($))b();else this._stdout.once("drain",b)})}}async function hj(){VW(),LW();let w=JW(),b=new HW;await w.connect(b),console.error("Sequenzy MCP server running on stdio")}hj().catch((w)=>{console.error(K1(w)),process.exit(1)});export{F4 as withMcpRequestContext,Nb as setSelectedCompanyId,O1 as getSelectedCompanyId,JW as createSequenzyMcpServer,D as apiRequest};