@sequenzy/mcp 0.0.129 → 0.0.130
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 +20 -20
- package/dist/server.js +18 -18
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var P5=Object.create;var{getPrototypeOf:Z5,defineProperty:G4,getOwnPropertyNames:V5}=Object;var j5=Object.prototype.hasOwnProperty;function I5(w){return this[w]}var N5,E5,e9=(w,b,$)=>{var W=w!=null&&typeof w==="object";if(W){var Q=b?N5??=new WeakMap:E5??=new WeakMap,G=Q.get(w);if(G)return G}$=w!=null?P5(Z5(w)):{};let X=b||!w||!w.__esModule?G4($,"default",{value:w,enumerable:!0}):$;for(let Y of V5(w))if(!j5.call(X,Y))G4(X,Y,{get:I5.bind(w,Y),enumerable:!0});if(W)Q.set(w,X);return X};var I=(w,b)=>()=>(b||w((b={exports:{}}).exports,b),b.exports);var T5=(w)=>w;function R5(w,b){this[w]=T5.bind(null,b)}var a9=(w,b)=>{for(var $ in b)G4(w,$,{get:b[$],enumerable:!0,configurable:!0,set:R5.bind(b,$)})};var g0=I((wX)=>{Object.defineProperty(wX,"__esModule",{value:!0});wX.regexpCode=wX.getEsmExportName=wX.getProperty=wX.safeStringify=wX.stringify=wX.strConcat=wX.addCodeArg=wX.str=wX._=wX.nil=wX._Code=wX.Name=wX.IDENTIFIER=wX._CodeOrName=void 0;class b${}wX._CodeOrName=b$;wX.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class t1 extends b${constructor(w){super();if(!wX.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}}}wX.Name=t1;class mw extends b${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 t1)b[$.str]=(b[$.str]||0)+1;return b},{})}}wX._Code=mw;wX.nil=new mw("");function eG(w,...b){let $=[w[0]],W=0;while(W<b.length)L6($,b[W]),$.push(w[++W]);return new mw($)}wX._=eG;var A6=new mw("+");function aG(w,...b){let $=[m0(w[0])],W=0;while(W<b.length)$.push(A6),L6($,b[W]),$.push(A6,m0(w[++W]));return e3($),new mw($)}wX.str=aG;function L6(w,b){if(b instanceof mw)w.push(...b._items);else if(b instanceof t1)w.push(b);else w.push(bA(b))}wX.addCodeArg=L6;function e3(w){let b=1;while(b<w.length-1){if(w[b]===A6){let $=a3(w[b-1],w[b+1]);if($!==void 0){w.splice(b-1,3,$);continue}w[b++]="+"}b++}}function a3(w,b){if(b==='""')return w;if(w==='""')return b;if(typeof w=="string"){if(b instanceof t1||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 t1))return`"${w}${b.slice(1)}`;return}function wA(w,b){return b.emptyStr()?w:w.emptyStr()?b:aG`${w}${b}`}wX.strConcat=wA;function bA(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:m0(Array.isArray(w)?w.join(","):w)}function $A(w){return new mw(m0(w))}wX.stringify=$A;function m0(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}wX.safeStringify=m0;function WA(w){return typeof w=="string"&&wX.IDENTIFIER.test(w)?new mw(`.${w}`):eG`[${w}]`}wX.getProperty=WA;function QA(w){if(typeof w=="string"&&wX.IDENTIFIER.test(w))return new mw(`${w}`);throw Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}wX.getEsmExportName=QA;function GA(w){return new mw(w.toString())}wX.regexpCode=GA});var O6=I((QX)=>{Object.defineProperty(QX,"__esModule",{value:!0});QX.ValueScope=QX.ValueScopeName=QX.Scope=QX.varKinds=QX.UsedValueState=void 0;var Iw=g0();class $X extends Error{constructor(w){super(`CodeGen: "code" for ${w} not defined`);this.value=w.value}}var W$;(function(w){w[w.Started=0]="Started",w[w.Completed=1]="Completed"})(W$||(QX.UsedValueState=W$={}));QX.varKinds={const:new Iw.Name("const"),let:new Iw.Name("let"),var:new Iw.Name("var")};class B6{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}}}QX.Scope=B6;class K6 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)}[${$}]`}}QX.ValueScopeName=K6;var OA=Iw._`\n`;class WX extends B6{constructor(w){super(w);this._values={},this._scope=w.scope,this.opts={...w,_n:w.lines?OA:Iw.nil}}get(){return this._scope}name(w){return new K6(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,G=($=b.key)!==null&&$!==void 0?$:b.ref,X=this._values[Q];if(X){let H=X.get(G);if(H)return H}else X=this._values[Q]=new Map;X.set(G,W);let Y=this._scope[Q]||(this._scope[Q]=[]),J=Y.length;return Y[J]=b.ref,W.setValue(b,{property:Q,itemIndex:J}),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 G in w){let X=w[G];if(!X)continue;let Y=$[G]=$[G]||new Map;X.forEach((J)=>{if(Y.has(J))return;Y.set(J,W$.Started);let H=b(J);if(H){let z=this.opts.es5?QX.varKinds.var:QX.varKinds.const;Q=Iw._`${Q}${z} ${J} = ${H};${this.opts._n}`}else if(H=W===null||W===void 0?void 0:W(J))Q=Iw._`${Q}${H}${this.opts._n}`;else throw new $X(J);Y.set(J,W$.Completed)})}return Q}}QX.ValueScope=WX});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=g0(),gw=O6(),j1=g0();Object.defineProperty(Nw,"_",{enumerable:!0,get:function(){return j1._}});Object.defineProperty(Nw,"str",{enumerable:!0,get:function(){return j1.str}});Object.defineProperty(Nw,"strConcat",{enumerable:!0,get:function(){return j1.strConcat}});Object.defineProperty(Nw,"nil",{enumerable:!0,get:function(){return j1.nil}});Object.defineProperty(Nw,"getProperty",{enumerable:!0,get:function(){return j1.getProperty}});Object.defineProperty(Nw,"stringify",{enumerable:!0,get:function(){return j1.stringify}});Object.defineProperty(Nw,"regexpCode",{enumerable:!0,get:function(){return j1.regexpCode}});Object.defineProperty(Nw,"Name",{enumerable:!0,get:function(){return j1.Name}});var H$=O6();Object.defineProperty(Nw,"Scope",{enumerable:!0,get:function(){return H$.Scope}});Object.defineProperty(Nw,"ValueScope",{enumerable:!0,get:function(){return H$.ValueScope}});Object.defineProperty(Nw,"ValueScopeName",{enumerable:!0,get:function(){return H$.ValueScopeName}});Object.defineProperty(Nw,"varKinds",{enumerable:!0,get:function(){return H$.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 I1{optimizeNodes(){return this}optimizeNames(w,b){return this}}class XX extends I1{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=s1(this.rhs,w,b);return this}get names(){return this.rhs instanceof i._CodeOrName?this.rhs.names:{}}}class P6 extends I1{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=s1(this.rhs,w,b),this}get names(){let w=this.lhs instanceof i.Name?{}:{...this.lhs.names};return J$(w,this.rhs)}}class YX extends P6{constructor(w,b,$,W){super(w,$,W);this.op=b}render({_n:w}){return`${this.lhs} ${this.op}= ${this.rhs};`+w}}class JX extends I1{constructor(w){super();this.label=w,this.names={}}render({_n:w}){return`${this.label}:`+w}}class HX extends I1{constructor(w){super();this.label=w,this.names={}}render({_n:w}){return`break${this.label?` ${this.label}`:""};`+w}}class zX extends I1{constructor(w){super();this.error=w}render({_n:w}){return`throw ${this.error};`+w}get names(){return this.error.names}}class DX extends I1{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=s1(this.code,w,b),this}get names(){return this.code instanceof i._CodeOrName?this.code.names:{}}}class z$ extends I1{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;ZA(w,Q.names),$.splice(W,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((w,b)=>k1(w,b.names),{})}}class N1 extends z${render(w){return"{"+w._n+super.render(w)+"}"+w._n}}class UX extends z${}class l0 extends N1{}l0.kind="else";class X1 extends N1{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 l0($):$}if(b){if(w===!1)return b instanceof X1?b:b.nodes;if(this.nodes.length)return this;return new X1(KX(w),b instanceof X1?[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=s1(this.condition,w,b),this}get names(){let w=super.names;if(J$(w,this.condition),this.else)k1(w,this.else.names);return w}}X1.kind="if";class r1 extends N1{}r1.kind="for";class AX extends r1{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=s1(this.iteration,w,b),this}get names(){return k1(super.names,this.iteration.names)}}class LX extends r1{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=J$(super.names,this.from);return J$(w,this.to)}}class M6 extends r1{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=s1(this.iterable,w,b),this}get names(){return k1(super.names,this.iterable.names)}}class Q$ extends N1{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)}}Q$.kind="func";class G$ extends z${render(w){return"return "+super.render(w)}}G$.kind="return";class FX extends N1{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)k1(w,this.catch.names);if(this.finally)k1(w,this.finally.names);return w}}class X$ extends N1{constructor(w){super();this.error=w}render(w){return`catch(${this.error})`+super.render(w)}}X$.kind="catch";class Y$ extends N1{render(w){return"finally"+super.render(w)}}Y$.kind="finally";class BX{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 UX]}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 XX(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 P6(w,b,$))}add(w,b){return this._leafNode(new YX(w,Nw.operators.ADD,b))}code(w){if(typeof w=="function")w();else if(w!==i.nil)this._leafNode(new DX(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 X1(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 X1(w))}else(){return this._elseNode(new l0)}endIf(){return this._endBlockNode(X1,l0)}_for(w,b){if(this._blockNode(w),b)this.code(b).endFor();return this}for(w,b){return this._for(new AX(w),b)}forRange(w,b,$,W,Q=this.opts.es5?gw.varKinds.var:gw.varKinds.let){let G=this._scope.toName(w);return this._for(new LX(Q,G,b,$),()=>W(G))}forOf(w,b,$,W=gw.varKinds.const){let Q=this._scope.toName(w);if(this.opts.es5){let G=b instanceof i.Name?b:this.var("_arr",b);return this.forRange("_i",0,i._`${G}.length`,(X)=>{this.var(Q,i._`${G}[${X}]`),$(Q)})}return this._for(new M6("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,i._`Object.keys(${b})`,$);let Q=this._scope.toName(w);return this._for(new M6("in",W,Q,b),()=>$(Q))}endFor(){return this._endBlockNode(r1)}label(w){return this._leafNode(new JX(w))}break(w){return this._leafNode(new HX(w))}return(w){let b=new G$;if(this._blockNode(b),this.code(w),b.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(G$)}try(w,b,$){if(!b&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new FX;if(this._blockNode(W),this.code(w),b){let Q=this.name("e");this._currNode=W.catch=new X$(Q),b(Q)}if($)this._currNode=W.finally=new Y$,this.code($);return this._endBlockNode(X$,Y$)}throw(w){return this._leafNode(new zX(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 Q$(w,b,$)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(Q$)}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 X1))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=BX;function k1(w,b){for(let $ in b)w[$]=(w[$]||0)+(b[$]||0);return w}function J$(w,b){return b instanceof i._CodeOrName?k1(w,b.names):w}function s1(w,b,$){if(w instanceof i.Name)return W(w);if(!Q(w))return w;return new i._Code(w._items.reduce((G,X)=>{if(X instanceof i.Name)X=W(X);if(X instanceof i._Code)G.push(...X._items);else G.push(X);return G},[]));function W(G){let X=$[G.str];if(X===void 0||b[G.str]!==1)return G;return delete b[G.str],X}function Q(G){return G instanceof i._Code&&G._items.some((X)=>X instanceof i.Name&&b[X.str]===1&&$[X.str]!==void 0)}}function ZA(w,b){for(let $ in b)w[$]=(w[$]||0)-(b[$]||0)}function KX(w){return typeof w=="boolean"||typeof w=="number"||w===null?!w:i._`!${q6(w)}`}Nw.not=KX;var VA=OX(Nw.operators.AND);function jA(...w){return w.reduce(VA)}Nw.and=jA;var IA=OX(Nw.operators.OR);function NA(...w){return w.reduce(IA)}Nw.or=NA;function OX(w){return(b,$)=>b===i.nil?$:$===i.nil?b:i._`${q6(b)} ${w} ${q6($)}`}function q6(w){return w instanceof i.Name?w:i._`(${w})`}});var d=I((EX)=>{Object.defineProperty(EX,"__esModule",{value:!0});EX.checkStrictMode=EX.getErrorPath=EX.Type=EX.useFunc=EX.setEvaluated=EX.evaluatedPropsToName=EX.mergeEvaluated=EX.eachItem=EX.unescapeJsonPointer=EX.escapeJsonPointer=EX.escapeFragment=EX.unescapeFragment=EX.schemaRefOrVal=EX.schemaHasRulesButRef=EX.schemaHasRules=EX.checkUnknownRules=EX.alwaysValidSchema=EX.toHash=void 0;var s=f(),SA=g0();function CA(w){let b={};for(let $ of w)b[$]=!0;return b}EX.toHash=CA;function vA(w,b){if(typeof b=="boolean")return b;if(Object.keys(b).length===0)return!0;return ZX(w,b),!VX(b,w.self.RULES.all)}EX.alwaysValidSchema=vA;function ZX(w,b=w.schema){let{opts:$,self:W}=w;if(!$.strictSchema)return;if(typeof b==="boolean")return;let Q=W.RULES.keywords;for(let G in b)if(!Q[G])NX(w,`unknown keyword: "${G}"`)}EX.checkUnknownRules=ZX;function VX(w,b){if(typeof w=="boolean")return!w;for(let $ in w)if(b[$])return!0;return!1}EX.schemaHasRules=VX;function _A(w,b){if(typeof w=="boolean")return!w;for(let $ in w)if($!=="$ref"&&b.all[$])return!0;return!1}EX.schemaHasRulesButRef=_A;function kA({topSchemaRef:w,schemaPath:b},$,W,Q){if(!Q){if(typeof $=="number"||typeof $=="boolean")return $;if(typeof $=="string")return s._`${$}`}return s._`${w}${b}${(0,s.getProperty)(W)}`}EX.schemaRefOrVal=kA;function xA(w){return jX(decodeURIComponent(w))}EX.unescapeFragment=xA;function yA(w){return encodeURIComponent(V6(w))}EX.escapeFragment=yA;function V6(w){if(typeof w=="number")return`${w}`;return w.replace(/~/g,"~0").replace(/\//g,"~1")}EX.escapeJsonPointer=V6;function jX(w){return w.replace(/~1/g,"/").replace(/~0/g,"~")}EX.unescapeJsonPointer=jX;function hA(w,b){if(Array.isArray(w))for(let $ of w)b($);else b(w)}EX.eachItem=hA;function qX({mergeNames:w,mergeToName:b,mergeValues:$,resultToName:W}){return(Q,G,X,Y)=>{let J=X===void 0?G:X instanceof s.Name?(G instanceof s.Name?w(Q,G,X):b(Q,G,X),X):G instanceof s.Name?(b(Q,X,G),G):$(G,X);return Y===s.Name&&!(J instanceof s.Name)?W(Q,J):J}}EX.mergeEvaluated={props:qX({mergeNames:(w,b,$)=>w.if(s._`${$} !== true && ${b} !== undefined`,()=>{w.if(s._`${b} === true`,()=>w.assign($,!0),()=>w.assign($,s._`${$} || {}`).code(s._`Object.assign(${$}, ${b})`))}),mergeToName:(w,b,$)=>w.if(s._`${$} !== true`,()=>{if(b===!0)w.assign($,!0);else w.assign($,s._`${$} || {}`),j6(w,$,b)}),mergeValues:(w,b)=>w===!0?!0:{...w,...b},resultToName:IX}),items:qX({mergeNames:(w,b,$)=>w.if(s._`${$} !== true && ${b} !== undefined`,()=>w.assign($,s._`${b} === true ? true : ${$} > ${b} ? ${$} : ${b}`)),mergeToName:(w,b,$)=>w.if(s._`${$} !== true`,()=>w.assign($,b===!0?!0:s._`${$} > ${b} ? ${$} : ${b}`)),mergeValues:(w,b)=>w===!0?!0:Math.max(w,b),resultToName:(w,b)=>w.var("items",b)})};function IX(w,b){if(b===!0)return w.var("props",!0);let $=w.var("props",s._`{}`);if(b!==void 0)j6(w,$,b);return $}EX.evaluatedPropsToName=IX;function j6(w,b,$){Object.keys($).forEach((W)=>w.assign(s._`${b}${(0,s.getProperty)(W)}`,!0))}EX.setEvaluated=j6;var PX={};function uA(w,b){return w.scopeValue("func",{ref:b,code:PX[b.code]||(PX[b.code]=new SA._Code(b.code))})}EX.useFunc=uA;var Z6;(function(w){w[w.Num=0]="Num",w[w.Str=1]="Str"})(Z6||(EX.Type=Z6={}));function fA(w,b,$){if(w instanceof s.Name){let W=b===Z6.Num;return $?W?s._`"[" + ${w} + "]"`:s._`"['" + ${w} + "']"`:W?s._`"/" + ${w}`:s._`"/" + ${w}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,s.getProperty)(w).toString():"/"+V6(w)}EX.getErrorPath=fA;function NX(w,b,$=w.opts.strictSchema){if(!$)return;if(b=`strict mode: ${b}`,$===!0)throw Error(b);w.self.logger.warn(b)}EX.checkStrictMode=NX});var Y1=I((RX)=>{Object.defineProperty(RX,"__esModule",{value:!0});var Mw=f(),WL={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")};RX.default=WL});var i0=I((_X)=>{Object.defineProperty(_X,"__esModule",{value:!0});_X.extendErrors=_X.resetErrorsCount=_X.reportExtraError=_X.reportError=_X.keyword$DataError=_X.keywordError=void 0;var n=f(),U$=d(),Zw=Y1();_X.keywordError={message:({keyword:w})=>n.str`must pass "${w}" keyword validation`};_X.keyword$DataError={message:({keyword:w,schemaType:b})=>b?n.str`"${w}" keyword must be ${b} ($data)`:n.str`"${w}" keyword is invalid ($data)`};function GL(w,b=_X.keywordError,$,W){let{it:Q}=w,{gen:G,compositeRule:X,allErrors:Y}=Q,J=vX(w,b,$);if(W!==null&&W!==void 0?W:X||Y)SX(G,J);else CX(Q,n._`[${J}]`)}_X.reportError=GL;function XL(w,b=_X.keywordError,$){let{it:W}=w,{gen:Q,compositeRule:G,allErrors:X}=W,Y=vX(w,b,$);if(SX(Q,Y),!(G||X))CX(W,Zw.default.vErrors)}_X.reportExtraError=XL;function YL(w,b){w.assign(Zw.default.errors,b),w.if(n._`${Zw.default.vErrors} !== null`,()=>w.if(b,()=>w.assign(n._`${Zw.default.vErrors}.length`,b),()=>w.assign(Zw.default.vErrors,null)))}_X.resetErrorsCount=YL;function JL({gen:w,keyword:b,schemaValue:$,data:W,errsCount:Q,it:G}){if(Q===void 0)throw Error("ajv implementation error");let X=w.name("err");w.forRange("i",Q,Zw.default.errors,(Y)=>{if(w.const(X,n._`${Zw.default.vErrors}[${Y}]`),w.if(n._`${X}.instancePath === undefined`,()=>w.assign(n._`${X}.instancePath`,(0,n.strConcat)(Zw.default.instancePath,G.errorPath))),w.assign(n._`${X}.schemaPath`,n.str`${G.errSchemaPath}/${b}`),G.opts.verbose)w.assign(n._`${X}.schema`,$),w.assign(n._`${X}.data`,W)})}_X.extendErrors=JL;function SX(w,b){let $=w.const("err",b);w.if(n._`${Zw.default.vErrors} === null`,()=>w.assign(Zw.default.vErrors,n._`[${$}]`),n._`${Zw.default.vErrors}.push(${$})`),w.code(n._`${Zw.default.errors}++`)}function CX(w,b){let{gen:$,validateName:W,schemaEnv:Q}=w;if(Q.$async)$.throw(n._`new ${w.ValidationError}(${b})`);else $.assign(n._`${W}.errors`,b),$.return(!1)}var x1={keyword:new n.Name("keyword"),schemaPath:new n.Name("schemaPath"),params:new n.Name("params"),propertyName:new n.Name("propertyName"),message:new n.Name("message"),schema:new n.Name("schema"),parentSchema:new n.Name("parentSchema")};function vX(w,b,$){let{createErrors:W}=w.it;if(W===!1)return n._`{}`;return HL(w,b,$)}function HL(w,b,$={}){let{gen:W,it:Q}=w,G=[zL(Q,$),DL(w,$)];return UL(w,b,G),W.object(...G)}function zL({errorPath:w},{instancePath:b}){let $=b?n.str`${w}${(0,U$.getErrorPath)(b,U$.Type.Str)}`:w;return[Zw.default.instancePath,(0,n.strConcat)(Zw.default.instancePath,$)]}function DL({keyword:w,it:{errSchemaPath:b}},{schemaPath:$,parentSchema:W}){let Q=W?b:n.str`${b}/${w}`;if($)Q=n.str`${Q}${(0,U$.getErrorPath)($,U$.Type.Str)}`;return[x1.schemaPath,Q]}function UL(w,{params:b,message:$},W){let{keyword:Q,data:G,schemaValue:X,it:Y}=w,{opts:J,propertyName:H,topSchemaRef:z,schemaPath:D}=Y;if(W.push([x1.keyword,Q],[x1.params,typeof b=="function"?b(w):b||n._`{}`]),J.messages)W.push([x1.message,typeof $=="function"?$(w):$]);if(J.verbose)W.push([x1.schema,X],[x1.parentSchema,n._`${z}${D}`],[Zw.default.data,G]);if(H)W.push([x1.propertyName,H])}});var uX=I((yX)=>{Object.defineProperty(yX,"__esModule",{value:!0});yX.boolOrEmptySchema=yX.topBoolOrEmptySchema=void 0;var KL=i0(),OL=f(),ML=Y1(),qL={message:"boolean schema is false"};function PL(w){let{gen:b,schema:$,validateName:W}=w;if($===!1)xX(w,!1);else if(typeof $=="object"&&$.$async===!0)b.return(ML.default.data);else b.assign(OL._`${W}.errors`,null),b.return(!0)}yX.topBoolOrEmptySchema=PL;function ZL(w,b){let{gen:$,schema:W}=w;if(W===!1)$.var(b,!1),xX(w);else $.var(b,!0)}yX.boolOrEmptySchema=ZL;function xX(w,b){let{gen:$,data:W}=w,Q={gen:$,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:w};(0,KL.reportError)(Q,qL,void 0,b)}});var N6=I((fX)=>{Object.defineProperty(fX,"__esModule",{value:!0});fX.getRules=fX.isJSONType=void 0;var jL=["string","number","integer","boolean","null","object","array"],IL=new Set(jL);function NL(w){return typeof w=="string"&&IL.has(w)}fX.isJSONType=NL;function EL(){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:{}}}fX.getRules=EL});var E6=I((lX)=>{Object.defineProperty(lX,"__esModule",{value:!0});lX.shouldUseRule=lX.shouldUseGroup=lX.schemaHasRulesForType=void 0;function RL({schema:w,self:b},$){let W=b.RULES.types[$];return W&&W!==!0&&mX(w,W)}lX.schemaHasRulesForType=RL;function mX(w,b){return b.rules.some(($)=>gX(w,$))}lX.shouldUseGroup=mX;function gX(w,b){var $;return w[b.keyword]!==void 0||(($=b.definition.implements)===null||$===void 0?void 0:$.some((W)=>w[W]!==void 0))}lX.shouldUseRule=gX});var n0=I((dX)=>{Object.defineProperty(dX,"__esModule",{value:!0});dX.reportTypeError=dX.checkDataTypes=dX.checkDataType=dX.coerceAndCheckDataType=dX.getJSONTypes=dX.getSchemaTypes=dX.DataType=void 0;var vL=N6(),_L=E6(),kL=i0(),h=f(),nX=d(),e1;(function(w){w[w.Correct=0]="Correct",w[w.Wrong=1]="Wrong"})(e1||(dX.DataType=e1={}));function xL(w){let b=pX(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}dX.getSchemaTypes=xL;function pX(w){let b=Array.isArray(w)?w:w?[w]:[];if(b.every(vL.isJSONType))return b;throw Error("type must be JSONType or JSONType[]: "+b.join(","))}dX.getJSONTypes=pX;function yL(w,b){let{gen:$,data:W,opts:Q}=w,G=hL(b,Q.coerceTypes),X=b.length>0&&!(G.length===0&&b.length===1&&(0,_L.schemaHasRulesForType)(w,b[0]));if(X){let Y=R6(b,W,Q.strictNumbers,e1.Wrong);$.if(Y,()=>{if(G.length)uL(w,b,G);else S6(w)})}return X}dX.coerceAndCheckDataType=yL;var oX=new Set(["string","number","integer","boolean","null"]);function hL(w,b){return b?w.filter(($)=>oX.has($)||b==="array"&&$==="array"):[]}function uL(w,b,$){let{gen:W,data:Q,opts:G}=w,X=W.let("dataType",h._`typeof ${Q}`),Y=W.let("coerced",h._`undefined`);if(G.coerceTypes==="array")W.if(h._`${X} == 'object' && Array.isArray(${Q}) && ${Q}.length == 1`,()=>W.assign(Q,h._`${Q}[0]`).assign(X,h._`typeof ${Q}`).if(R6(b,Q,G.strictNumbers),()=>W.assign(Y,Q)));W.if(h._`${Y} !== undefined`);for(let H of $)if(oX.has(H)||H==="array"&&G.coerceTypes==="array")J(H);W.else(),S6(w),W.endIf(),W.if(h._`${Y} !== undefined`,()=>{W.assign(Q,Y),fL(w,Y)});function J(H){switch(H){case"string":W.elseIf(h._`${X} == "number" || ${X} == "boolean"`).assign(Y,h._`"" + ${Q}`).elseIf(h._`${Q} === null`).assign(Y,h._`""`);return;case"number":W.elseIf(h._`${X} == "boolean" || ${Q} === null
|
|
4
|
-
|| (${
|
|
5
|
-
|| (${
|
|
6
|
-
|| ${X} === "boolean" || ${Q} === null`).assign(Y,h._`[${Q}]`)}}}function fL({gen:w,parentData:b,parentDataProperty:$},W){w.if(h._`${b} !== undefined`,()=>w.assign(h._`${b}[${$}]`,W))}function T6(w,b,$,W=e1.Correct){let Q=W===e1.Correct?h.operators.EQ:h.operators.NEQ,G;switch(w){case"null":return h._`${b} ${Q} null`;case"array":G=h._`Array.isArray(${b})`;break;case"object":G=h._`${b} && typeof ${b} == "object" && !Array.isArray(${b})`;break;case"integer":G=X(h._`!(${b} % 1) && !isNaN(${b})`);break;case"number":G=X();break;default:return h._`typeof ${b} ${Q} ${w}`}return W===e1.Correct?G:(0,h.not)(G);function X(Y=h.nil){return(0,h.and)(h._`typeof ${b} == "number"`,Y,$?h._`isFinite(${b})`:h.nil)}}dX.checkDataType=T6;function R6(w,b,$,W){if(w.length===1)return T6(w[0],b,$,W);let Q,G=(0,nX.toHash)(w);if(G.array&&G.object){let X=h._`typeof ${b} != "object"`;Q=G.null?X:h._`!${b} || ${X}`,delete G.null,delete G.array,delete G.object}else Q=h.nil;if(G.number)delete G.integer;for(let X in G)Q=(0,h.and)(Q,T6(X,b,$,W));return Q}dX.checkDataTypes=R6;var cL={message:({schema:w})=>`must be ${w}`,params:({schema:w,schemaValue:b})=>typeof w=="string"?h._`{type: ${w}}`:h._`{type: ${b}}`};function S6(w){let b=mL(w);(0,kL.reportError)(b,cL)}dX.reportTypeError=S6;function mL(w){let{gen:b,data:$,schema:W}=w,Q=(0,nX.schemaRefOrVal)(w,W,"type");return{gen:b,keyword:"type",data:$,schema:W.type,schemaCode:Q,schemaValue:Q,parentSchema:W,params:{},it:w}}});var aX=I((sX)=>{Object.defineProperty(sX,"__esModule",{value:!0});sX.assignDefaults=void 0;var a1=f(),dL=d();function tL(w,b){let{properties:$,items:W}=w.schema;if(b==="object"&&$)for(let Q in $)rX(w,Q,$[Q].default);else if(b==="array"&&Array.isArray(W))W.forEach((Q,G)=>rX(w,G,Q.default))}sX.assignDefaults=tL;function rX(w,b,$){let{gen:W,compositeRule:Q,data:G,opts:X}=w;if($===void 0)return;let Y=a1._`${G}${(0,a1.getProperty)(b)}`;if(Q){(0,dL.checkStrictMode)(w,`default is ignored for: ${Y}`);return}let J=a1._`${Y} === undefined`;if(X.useDefaults==="empty")J=a1._`${J} || ${Y} === null || ${Y} === ""`;W.if(J,a1._`${Y} = ${(0,a1.stringify)($)}`)}});var yw=I(($Y)=>{Object.defineProperty($Y,"__esModule",{value:!0});$Y.validateUnion=$Y.validateArray=$Y.usePattern=$Y.callValidateCode=$Y.schemaProperties=$Y.allSchemaProperties=$Y.noPropertyInData=$Y.propertyInData=$Y.isOwnProperty=$Y.hasPropFunc=$Y.reportMissingProp=$Y.checkMissingProp=$Y.checkReportMissingProp=void 0;var bw=f(),C6=d(),E1=Y1(),rL=d();function sL(w,b){let{gen:$,data:W,it:Q}=w;$.if(_6($,W,b,Q.opts.ownProperties),()=>{w.setParams({missingProperty:bw._`${b}`},!0),w.error()})}$Y.checkReportMissingProp=sL;function eL({gen:w,data:b,it:{opts:$}},W,Q){return(0,bw.or)(...W.map((G)=>(0,bw.and)(_6(w,b,G,$.ownProperties),bw._`${Q} = ${G}`)))}$Y.checkMissingProp=eL;function aL(w,b){w.setParams({missingProperty:b},!0),w.error()}$Y.reportMissingProp=aL;function wY(w){return w.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:bw._`Object.prototype.hasOwnProperty`})}$Y.hasPropFunc=wY;function v6(w,b,$){return bw._`${wY(w)}.call(${b}, ${$})`}$Y.isOwnProperty=v6;function wF(w,b,$,W){let Q=bw._`${b}${(0,bw.getProperty)($)} !== undefined`;return W?bw._`${Q} && ${v6(w,b,$)}`:Q}$Y.propertyInData=wF;function _6(w,b,$,W){let Q=bw._`${b}${(0,bw.getProperty)($)} === undefined`;return W?(0,bw.or)(Q,(0,bw.not)(v6(w,b,$))):Q}$Y.noPropertyInData=_6;function bY(w){return w?Object.keys(w).filter((b)=>b!=="__proto__"):[]}$Y.allSchemaProperties=bY;function bF(w,b){return bY(b).filter(($)=>!(0,C6.alwaysValidSchema)(w,b[$]))}$Y.schemaProperties=bF;function $F({schemaCode:w,data:b,it:{gen:$,topSchemaRef:W,schemaPath:Q,errorPath:G},it:X},Y,J,H){let z=H?bw._`${w}, ${b}, ${W}${Q}`:b,D=[[E1.default.instancePath,(0,bw.strConcat)(E1.default.instancePath,G)],[E1.default.parentData,X.parentData],[E1.default.parentDataProperty,X.parentDataProperty],[E1.default.rootData,E1.default.rootData]];if(X.opts.dynamicRef)D.push([E1.default.dynamicAnchors,E1.default.dynamicAnchors]);let A=bw._`${z}, ${$.object(...D)}`;return J!==bw.nil?bw._`${Y}.call(${J}, ${A})`:bw._`${Y}(${A})`}$Y.callValidateCode=$F;var WF=bw._`new RegExp`;function QF({gen:w,it:{opts:b}},$){let W=b.unicodeRegExp?"u":"",{regExp:Q}=b.code,G=Q($,W);return w.scopeValue("pattern",{key:G.toString(),ref:G,code:bw._`${Q.code==="new RegExp"?WF:(0,rL.useFunc)(w,Q)}(${$}, ${W})`})}$Y.usePattern=QF;function GF(w){let{gen:b,data:$,keyword:W,it:Q}=w,G=b.name("valid");if(Q.allErrors){let Y=b.let("valid",!0);return X(()=>b.assign(Y,!1)),Y}return b.var(G,!0),X(()=>b.break()),G;function X(Y){let J=b.const("len",bw._`${$}.length`);b.forRange("i",0,J,(H)=>{w.subschema({keyword:W,dataProp:H,dataPropType:C6.Type.Num},G),b.if((0,bw.not)(G),Y)})}}$Y.validateArray=GF;function XF(w){let{gen:b,schema:$,keyword:W,it:Q}=w;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((J)=>(0,C6.alwaysValidSchema)(Q,J))&&!Q.opts.unevaluated)return;let X=b.let("valid",!1),Y=b.name("_valid");b.block(()=>$.forEach((J,H)=>{let z=w.subschema({keyword:W,schemaProp:H,compositeRule:!0},Y);if(b.assign(X,bw._`${X} || ${Y}`),!w.mergeValidEvaluated(z,Y))b.if((0,bw.not)(X))})),w.result(X,()=>w.reset(),()=>w.error(!0))}$Y.validateUnion=XF});var JY=I((XY)=>{Object.defineProperty(XY,"__esModule",{value:!0});XY.validateKeywordUsage=XY.validSchemaType=XY.funcKeywordCode=XY.macroKeywordCode=void 0;var Vw=f(),y1=Y1(),MF=yw(),qF=i0();function PF(w,b){let{gen:$,keyword:W,schema:Q,parentSchema:G,it:X}=w,Y=b.macro.call(X.self,Q,G,X),J=GY($,W,Y);if(X.opts.validateSchema!==!1)X.self.validateSchema(Y,!0);let H=$.name("valid");w.subschema({schema:Y,schemaPath:Vw.nil,errSchemaPath:`${X.errSchemaPath}/${W}`,topSchemaRef:J,compositeRule:!0},H),w.pass(H,()=>w.error(!0))}XY.macroKeywordCode=PF;function ZF(w,b){var $;let{gen:W,keyword:Q,schema:G,parentSchema:X,$data:Y,it:J}=w;jF(J,b);let H=!Y&&b.compile?b.compile.call(J.self,G,X,J):b.validate,z=GY(W,Q,H),D=W.let("valid");w.block$data(D,A),w.ok(($=b.valid)!==null&&$!==void 0?$:D);function A(){if(b.errors===!1){if(M(),b.modifying)QY(w);j(()=>w.error())}else{let V=b.async?L():K();if(b.modifying)QY(w);j(()=>VF(w,V))}}function L(){let V=W.let("ruleErrs",null);return W.try(()=>M(Vw._`await `),(C)=>W.assign(D,!1).if(Vw._`${C} instanceof ${J.ValidationError}`,()=>W.assign(V,Vw._`${C}.errors`),()=>W.throw(C))),V}function K(){let V=Vw._`${z}.errors`;return W.assign(V,null),M(Vw.nil),V}function M(V=b.async?Vw._`await `:Vw.nil){let C=J.opts.passContext?y1.default.this:y1.default.self,R=!(("compile"in b)&&!Y||b.schema===!1);W.assign(D,Vw._`${V}${(0,MF.callValidateCode)(w,z,C,R)}`,b.modifying)}function j(V){var C;W.if((0,Vw.not)((C=b.valid)!==null&&C!==void 0?C:D),V)}}XY.funcKeywordCode=ZF;function QY(w){let{gen:b,data:$,it:W}=w;b.if(W.parentData,()=>b.assign($,Vw._`${W.parentData}[${W.parentDataProperty}]`))}function VF(w,b){let{gen:$}=w;$.if(Vw._`Array.isArray(${b})`,()=>{$.assign(y1.default.vErrors,Vw._`${y1.default.vErrors} === null ? ${b} : ${y1.default.vErrors}.concat(${b})`).assign(y1.default.errors,Vw._`${y1.default.vErrors}.length`),(0,qF.extendErrors)(w)},()=>w.error())}function jF({schemaEnv:w},b){if(b.async&&!w.$async)throw Error("async keyword in sync schema")}function GY(w,b,$){if($===void 0)throw Error(`keyword "${b}" failed to compile`);return w.scopeValue("keyword",typeof $=="function"?{ref:$}:{ref:$,code:(0,Vw.stringify)($)})}function IF(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")}XY.validSchemaType=IF;function NF({schema:w,opts:b,self:$,errSchemaPath:W},Q,G){if(Array.isArray(Q.keyword)?!Q.keyword.includes(G):Q.keyword!==G)throw Error("ajv implementation error");let X=Q.dependencies;if(X===null||X===void 0?void 0:X.some((Y)=>!Object.prototype.hasOwnProperty.call(w,Y)))throw Error(`parent schema must have dependencies of ${G}: ${X.join(",")}`);if(Q.validateSchema){if(!Q.validateSchema(w[G])){let J=`keyword "${G}" value is invalid at path "${W}": `+$.errorsText(Q.validateSchema.errors);if(b.validateSchema==="log")$.logger.error(J);else throw Error(J)}}}XY.validateKeywordUsage=NF});var UY=I((zY)=>{Object.defineProperty(zY,"__esModule",{value:!0});zY.extendSubschemaMode=zY.extendSubschemaData=zY.getSubschema=void 0;var sw=f(),HY=d();function SF(w,{keyword:b,schemaProp:$,schema:W,schemaPath:Q,errSchemaPath:G,topSchemaRef:X}){if(b!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(b!==void 0){let Y=w.schema[b];return $===void 0?{schema:Y,schemaPath:sw._`${w.schemaPath}${(0,sw.getProperty)(b)}`,errSchemaPath:`${w.errSchemaPath}/${b}`}:{schema:Y[$],schemaPath:sw._`${w.schemaPath}${(0,sw.getProperty)(b)}${(0,sw.getProperty)($)}`,errSchemaPath:`${w.errSchemaPath}/${b}/${(0,HY.escapeFragment)($)}`}}if(W!==void 0){if(Q===void 0||G===void 0||X===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:Q,topSchemaRef:X,errSchemaPath:G}}throw Error('either "keyword" or "schema" must be passed')}zY.getSubschema=SF;function CF(w,b,{dataProp:$,dataPropType:W,data:Q,dataTypes:G,propertyName:X}){if(Q!==void 0&&$!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:Y}=b;if($!==void 0){let{errorPath:H,dataPathArr:z,opts:D}=b,A=Y.let("data",sw._`${b.data}${(0,sw.getProperty)($)}`,!0);J(A),w.errorPath=sw.str`${H}${(0,HY.getErrorPath)($,W,D.jsPropertySyntax)}`,w.parentDataProperty=sw._`${$}`,w.dataPathArr=[...z,w.parentDataProperty]}if(Q!==void 0){let H=Q instanceof sw.Name?Q:Y.let("data",Q,!0);if(J(H),X!==void 0)w.propertyName=X}if(G)w.dataTypes=G;function J(H){w.data=H,w.dataLevel=b.dataLevel+1,w.dataTypes=[],b.definedProperties=new Set,w.parentData=b.data,w.dataNames=[...b.dataNames,H]}}zY.extendSubschemaData=CF;function vF(w,{jtdDiscriminator:b,jtdMetadata:$,compositeRule:W,createErrors:Q,allErrors:G}){if(W!==void 0)w.compositeRule=W;if(Q!==void 0)w.createErrors=Q;if(G!==void 0)w.allErrors=G;w.jtdDiscriminator=b,w.jtdMetadata=$}zY.extendSubschemaMode=vF});var k6=I((kT,AY)=>{AY.exports=function w(b,$){if(b===$)return!0;if(b&&$&&typeof b=="object"&&typeof $=="object"){if(b.constructor!==$.constructor)return!1;var W,Q,G;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(G=Object.keys(b),W=G.length,W!==Object.keys($).length)return!1;for(Q=W;Q--!==0;)if(!Object.prototype.hasOwnProperty.call($,G[Q]))return!1;for(Q=W;Q--!==0;){var X=G[Q];if(!w(b[X],$[X]))return!1}return!0}return b!==b&&$!==$}});var FY=I((xT,LY)=>{var T1=LY.exports=function(w,b,$){if(typeof b=="function")$=b,b={};$=b.cb||$;var W=typeof $=="function"?$:$.pre||function(){},Q=$.post||function(){};A$(b,W,Q,w,"",w)};T1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};T1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};T1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};T1.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 A$(w,b,$,W,Q,G,X,Y,J,H){if(W&&typeof W=="object"&&!Array.isArray(W)){b(W,Q,G,X,Y,J,H);for(var z in W){var D=W[z];if(Array.isArray(D)){if(z in T1.arrayKeywords)for(var A=0;A<D.length;A++)A$(w,b,$,D[A],Q+"/"+z+"/"+A,G,Q,z,W,A)}else if(z in T1.propsKeywords){if(D&&typeof D=="object")for(var L in D)A$(w,b,$,D[L],Q+"/"+z+"/"+xF(L),G,Q,z,W,L)}else if(z in T1.keywords||w.allKeys&&!(z in T1.skipKeywords))A$(w,b,$,D,Q+"/"+z,G,Q,z,W)}$(W,Q,G,X,Y,J,H)}}function xF(w){return w.replace(/~/g,"~0").replace(/\//g,"~1")}});var p0=I((MY)=>{Object.defineProperty(MY,"__esModule",{value:!0});MY.getSchemaRefs=MY.resolveUrl=MY.normalizeId=MY._getFullPath=MY.getFullPath=MY.inlineRef=void 0;var yF=d(),hF=k6(),uF=FY(),fF=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function cF(w,b=!0){if(typeof w=="boolean")return!0;if(b===!0)return!x6(w);if(!b)return!1;return BY(w)<=b}MY.inlineRef=cF;var mF=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function x6(w){for(let b in w){if(mF.has(b))return!0;let $=w[b];if(Array.isArray($)&&$.some(x6))return!0;if(typeof $=="object"&&x6($))return!0}return!1}function BY(w){let b=0;for(let $ in w){if($==="$ref")return 1/0;if(b++,fF.has($))continue;if(typeof w[$]=="object")(0,yF.eachItem)(w[$],(W)=>b+=BY(W));if(b===1/0)return 1/0}return b}function KY(w,b="",$){if($!==!1)b=w0(b);let W=w.parse(b);return OY(w,W)}MY.getFullPath=KY;function OY(w,b){return w.serialize(b).split("#")[0]+"#"}MY._getFullPath=OY;var gF=/#\/?$/;function w0(w){return w?w.replace(gF,""):""}MY.normalizeId=w0;function lF(w,b,$){return $=w0($),w.resolve(b,$)}MY.resolveUrl=lF;var iF=/^[a-z_][-a-z0-9._]*$/i;function nF(w,b){if(typeof w=="boolean")return{};let{schemaId:$,uriResolver:W}=this.opts,Q=w0(w[$]||b),G={"":Q},X=KY(W,Q,!1),Y={},J=new Set;return uF(w,{allKeys:!0},(D,A,L,K)=>{if(K===void 0)return;let M=X+A,j=G[K];if(typeof D[$]=="string")j=V.call(this,D[$]);C.call(this,D.$anchor),C.call(this,D.$dynamicAnchor),G[A]=j;function V(R){let m=this.opts.uriResolver.resolve;if(R=w0(j?m(j,R):R),J.has(R))throw z(R);J.add(R);let _=this.refs[R];if(typeof _=="string")_=this.refs[_];if(typeof _=="object")H(D,_.schema,R);else if(R!==w0(M))if(R[0]==="#")H(D,Y[R],R),Y[R]=D;else this.refs[R]=M;return R}function C(R){if(typeof R=="string"){if(!iF.test(R))throw Error(`invalid anchor "${R}"`);V.call(this,`#${R}`)}}}),Y;function H(D,A,L){if(A!==void 0&&!hF(D,A))throw z(L)}function z(D){return Error(`reference "${D}" resolves to more than one schema`)}}MY.getSchemaRefs=nF});var t0=I((xY)=>{Object.defineProperty(xY,"__esModule",{value:!0});xY.getData=xY.KeywordCxt=xY.validateFunctionCode=void 0;var IY=uX(),PY=n0(),h6=E6(),L$=n0(),sF=aX(),d0=JY(),y6=UY(),T=f(),x=Y1(),eF=p0(),J1=d(),o0=i0();function aF(w){if(TY(w)){if(RY(w),EY(w)){$B(w);return}}NY(w,()=>(0,IY.topBoolOrEmptySchema)(w))}xY.validateFunctionCode=aF;function NY({gen:w,validateName:b,schema:$,schemaEnv:W,opts:Q},G){if(Q.code.es5)w.func(b,T._`${x.default.data}, ${x.default.valCxt}`,W.$async,()=>{w.code(T._`"use strict"; ${ZY($,Q)}`),bB(w,Q),w.code(G)});else w.func(b,T._`${x.default.data}, ${wB(Q)}`,W.$async,()=>w.code(ZY($,Q)).code(G))}function wB(w){return T._`{${x.default.instancePath}="", ${x.default.parentData}, ${x.default.parentDataProperty}, ${x.default.rootData}=${x.default.data}${w.dynamicRef?T._`, ${x.default.dynamicAnchors}={}`:T.nil}}={}`}function bB(w,b){w.if(x.default.valCxt,()=>{if(w.var(x.default.instancePath,T._`${x.default.valCxt}.${x.default.instancePath}`),w.var(x.default.parentData,T._`${x.default.valCxt}.${x.default.parentData}`),w.var(x.default.parentDataProperty,T._`${x.default.valCxt}.${x.default.parentDataProperty}`),w.var(x.default.rootData,T._`${x.default.valCxt}.${x.default.rootData}`),b.dynamicRef)w.var(x.default.dynamicAnchors,T._`${x.default.valCxt}.${x.default.dynamicAnchors}`)},()=>{if(w.var(x.default.instancePath,T._`""`),w.var(x.default.parentData,T._`undefined`),w.var(x.default.parentDataProperty,T._`undefined`),w.var(x.default.rootData,x.default.data),b.dynamicRef)w.var(x.default.dynamicAnchors,T._`{}`)})}function $B(w){let{schema:b,opts:$,gen:W}=w;NY(w,()=>{if($.$comment&&b.$comment)CY(w);if(YB(w),W.let(x.default.vErrors,null),W.let(x.default.errors,0),$.unevaluated)WB(w);SY(w),zB(w)});return}function WB(w){let{gen:b,validateName:$}=w;w.evaluated=b.const("evaluated",T._`${$}.evaluated`),b.if(T._`${w.evaluated}.dynamicProps`,()=>b.assign(T._`${w.evaluated}.props`,T._`undefined`)),b.if(T._`${w.evaluated}.dynamicItems`,()=>b.assign(T._`${w.evaluated}.items`,T._`undefined`))}function ZY(w,b){let $=typeof w=="object"&&w[b.schemaId];return $&&(b.code.source||b.code.process)?T._`/*# sourceURL=${$} */`:T.nil}function QB(w,b){if(TY(w)){if(RY(w),EY(w)){GB(w,b);return}}(0,IY.boolOrEmptySchema)(w,b)}function EY({schema:w,self:b}){if(typeof w=="boolean")return!w;for(let $ in w)if(b.RULES.all[$])return!0;return!1}function TY(w){return typeof w.schema!="boolean"}function GB(w,b){let{schema:$,gen:W,opts:Q}=w;if(Q.$comment&&$.$comment)CY(w);JB(w),HB(w);let G=W.const("_errs",x.default.errors);SY(w,G),W.var(b,T._`${G} === ${x.default.errors}`)}function RY(w){(0,J1.checkUnknownRules)(w),XB(w)}function SY(w,b){if(w.opts.jtd)return VY(w,[],!1,b);let $=(0,PY.getSchemaTypes)(w.schema),W=(0,PY.coerceAndCheckDataType)(w,$);VY(w,$,!W,b)}function XB(w){let{schema:b,errSchemaPath:$,opts:W,self:Q}=w;if(b.$ref&&W.ignoreKeywordsWithRef&&(0,J1.schemaHasRulesButRef)(b,Q.RULES))Q.logger.warn(`$ref: keywords ignored in schema at path "${$}"`)}function YB(w){let{schema:b,opts:$}=w;if(b.default!==void 0&&$.useDefaults&&$.strictSchema)(0,J1.checkStrictMode)(w,"default is ignored in the schema root")}function JB(w){let b=w.schema[w.opts.schemaId];if(b)w.baseId=(0,eF.resolveUrl)(w.opts.uriResolver,w.baseId,b)}function HB(w){if(w.schema.$async&&!w.schemaEnv.$async)throw Error("async schema in sync schema")}function CY({gen:w,schemaEnv:b,schema:$,errSchemaPath:W,opts:Q}){let G=$.$comment;if(Q.$comment===!0)w.code(T._`${x.default.self}.logger.log(${G})`);else if(typeof Q.$comment=="function"){let X=T.str`${W}/$comment`,Y=w.scopeValue("root",{ref:b.root});w.code(T._`${x.default.self}.opts.$comment(${G}, ${X}, ${Y}.schema)`)}}function zB(w){let{gen:b,schemaEnv:$,validateName:W,ValidationError:Q,opts:G}=w;if($.$async)b.if(T._`${x.default.errors} === 0`,()=>b.return(x.default.data),()=>b.throw(T._`new ${Q}(${x.default.vErrors})`));else{if(b.assign(T._`${W}.errors`,x.default.vErrors),G.unevaluated)DB(w);b.return(T._`${x.default.errors} === 0`)}}function DB({gen:w,evaluated:b,props:$,items:W}){if($ instanceof T.Name)w.assign(T._`${b}.props`,$);if(W instanceof T.Name)w.assign(T._`${b}.items`,W)}function VY(w,b,$,W){let{gen:Q,schema:G,data:X,allErrors:Y,opts:J,self:H}=w,{RULES:z}=H;if(G.$ref&&(J.ignoreKeywordsWithRef||!(0,J1.schemaHasRulesButRef)(G,z))){Q.block(()=>_Y(w,"$ref",z.all.$ref.definition));return}if(!J.jtd)UB(w,b);Q.block(()=>{for(let A of z.rules)D(A);D(z.post)});function D(A){if(!(0,h6.shouldUseGroup)(G,A))return;if(A.type){if(Q.if((0,L$.checkDataType)(A.type,X,J.strictNumbers)),jY(w,A),b.length===1&&b[0]===A.type&&$)Q.else(),(0,L$.reportTypeError)(w);Q.endIf()}else jY(w,A);if(!Y)Q.if(T._`${x.default.errors} === ${W||0}`)}}function jY(w,b){let{gen:$,schema:W,opts:{useDefaults:Q}}=w;if(Q)(0,sF.assignDefaults)(w,b.type);$.block(()=>{for(let G of b.rules)if((0,h6.shouldUseRule)(W,G))_Y(w,G.keyword,G.definition,b.type)})}function UB(w,b){if(w.schemaEnv.meta||!w.opts.strictTypes)return;if(AB(w,b),!w.opts.allowUnionTypes)LB(w,b);FB(w,w.dataTypes)}function AB(w,b){if(!b.length)return;if(!w.dataTypes.length){w.dataTypes=b;return}b.forEach(($)=>{if(!vY(w.dataTypes,$))u6(w,`type "${$}" not allowed by context "${w.dataTypes.join(",")}"`)}),KB(w,b)}function LB(w,b){if(b.length>1&&!(b.length===2&&b.includes("null")))u6(w,"use allowUnionTypes to allow union type keyword")}function FB(w,b){let $=w.self.RULES.all;for(let W in $){let Q=$[W];if(typeof Q=="object"&&(0,h6.shouldUseRule)(w.schema,Q)){let{type:G}=Q.definition;if(G.length&&!G.some((X)=>BB(b,X)))u6(w,`missing type "${G.join(",")}" for keyword "${W}"`)}}}function BB(w,b){return w.includes(b)||b==="number"&&w.includes("integer")}function vY(w,b){return w.includes(b)||b==="integer"&&w.includes("number")}function KB(w,b){let $=[];for(let W of w.dataTypes)if(vY(b,W))$.push(W);else if(b.includes("integer")&&W==="number")$.push("integer");w.dataTypes=$}function u6(w,b){let $=w.schemaEnv.baseId+w.errSchemaPath;b+=` at "${$}" (strictTypes)`,(0,J1.checkStrictMode)(w,b,w.opts.strictTypes)}class f6{constructor(w,b,$){if((0,d0.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,J1.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",kY(this.$data,w));else if(this.schemaCode=this.schemaValue,!(0,d0.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,T.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,T.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(T._`${b} !== undefined && (${(0,T.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?o0.reportExtraError:o0.reportError)(this,this.def.error,b)}$dataError(){(0,o0.reportError)(this,this.def.$dataError||o0.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,o0.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,$=T.nil){this.gen.block(()=>{this.check$data(w,$),b()})}check$data(w=T.nil,b=T.nil){if(!this.$data)return;let{gen:$,schemaCode:W,schemaType:Q,def:G}=this;if($.if((0,T.or)(T._`${W} === undefined`,b)),w!==T.nil)$.assign(w,!0);if(Q.length||G.validateSchema){if($.elseIf(this.invalid$data()),this.$dataError(),w!==T.nil)$.assign(w,!1)}$.else()}invalid$data(){let{gen:w,schemaCode:b,schemaType:$,def:W,it:Q}=this;return(0,T.or)(G(),X());function G(){if($.length){if(!(b instanceof T.Name))throw Error("ajv implementation error");let Y=Array.isArray($)?$:[$];return T._`${(0,L$.checkDataTypes)(Y,b,Q.opts.strictNumbers,L$.DataType.Wrong)}`}return T.nil}function X(){if(W.validateSchema){let Y=w.scopeValue("validate$data",{ref:W.validateSchema});return T._`!${Y}(${b})`}return T.nil}}subschema(w,b){let $=(0,y6.getSubschema)(this.it,w);(0,y6.extendSubschemaData)($,this.it,w),(0,y6.extendSubschemaMode)($,w);let W={...this.it,...$,items:void 0,props:void 0};return QB(W,b),W}mergeEvaluated(w,b){let{it:$,gen:W}=this;if(!$.opts.unevaluated)return;if($.props!==!0&&w.props!==void 0)$.props=J1.mergeEvaluated.props(W,w.props,$.props,b);if($.items!==!0&&w.items!==void 0)$.items=J1.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,T.Name)),!0}}xY.KeywordCxt=f6;function _Y(w,b,$,W){let Q=new f6(w,$,b);if("code"in $)$.code(Q,W);else if(Q.$data&&$.validate)(0,d0.funcKeywordCode)(Q,$);else if("macro"in $)(0,d0.macroKeywordCode)(Q,$);else if($.compile||$.validate)(0,d0.funcKeywordCode)(Q,$)}var OB=/^\/(?:[^~]|~0|~1)*$/,MB=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function kY(w,{dataLevel:b,dataNames:$,dataPathArr:W}){let Q,G;if(w==="")return x.default.rootData;if(w[0]==="/"){if(!OB.test(w))throw Error(`Invalid JSON-pointer: ${w}`);Q=w,G=x.default.rootData}else{let H=MB.exec(w);if(!H)throw Error(`Invalid JSON-pointer: ${w}`);let z=+H[1];if(Q=H[2],Q==="#"){if(z>=b)throw Error(J("property/index",z));return W[b-z]}if(z>b)throw Error(J("data",z));if(G=$[b-z],!Q)return G}let X=G,Y=Q.split("/");for(let H of Y)if(H)G=T._`${G}${(0,T.getProperty)((0,J1.unescapeJsonPointer)(H))}`,X=T._`${X} && ${G}`;return X;function J(H,z){return`Cannot access ${H} ${z} levels up, current level is ${b}`}}xY.getData=kY});var F$=I((uY)=>{Object.defineProperty(uY,"__esModule",{value:!0});class hY extends Error{constructor(w){super("validation failed");this.errors=w,this.ajv=this.validation=!0}}uY.default=hY});var r0=I((cY)=>{Object.defineProperty(cY,"__esModule",{value:!0});var c6=p0();class fY extends Error{constructor(w,b,$,W){super(W||`can't resolve reference ${$} from id ${b}`);this.missingRef=(0,c6.resolveUrl)(w,b,$),this.missingSchema=(0,c6.normalizeId)((0,c6.getFullPath)(w,this.missingRef))}}cY.default=fY});var K$=I((lY)=>{Object.defineProperty(lY,"__esModule",{value:!0});lY.resolveSchema=lY.getCompilingSchema=lY.resolveRef=lY.compileSchema=lY.SchemaEnv=void 0;var lw=f(),jB=F$(),h1=Y1(),iw=p0(),mY=d(),IB=t0();class s0{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={}}}lY.SchemaEnv=s0;function g6(w){let b=gY.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:G}=this.opts,X=new lw.CodeGen(this.scope,{es5:W,lines:Q,ownProperties:G}),Y;if(w.$async)Y=X.scopeValue("Error",{ref:jB.default,code:lw._`require("ajv/dist/runtime/validation_error").default`});let J=X.scopeName("validate");w.validateName=J;let H={gen:X,allErrors:this.opts.allErrors,data:h1.default.data,parentData:h1.default.parentData,parentDataProperty:h1.default.parentDataProperty,dataNames:[h1.default.data],dataPathArr:[lw.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:X.scopeValue("schema",this.opts.code.source===!0?{ref:w.schema,code:(0,lw.stringify)(w.schema)}:{ref:w.schema}),validateName:J,ValidationError:Y,schema:w.schema,schemaEnv:w,rootId:$,baseId:w.baseId||$,schemaPath:lw.nil,errSchemaPath:w.schemaPath||(this.opts.jtd?"":"#"),errorPath:lw._`""`,opts:this.opts,self:this},z;try{this._compilations.add(w),(0,IB.validateFunctionCode)(H),X.optimize(this.opts.code.optimize);let D=X.toString();if(z=`${X.scopeRefs(h1.default.scope)}return ${D}`,this.opts.code.process)z=this.opts.code.process(z,w);let L=Function(`${h1.default.self}`,`${h1.default.scope}`,z)(this,this.scope.get());if(this.scope.value(J,{ref:L}),L.errors=null,L.schema=w.schema,L.schemaEnv=w,w.$async)L.$async=!0;if(this.opts.code.source===!0)L.source={validateName:J,validateCode:D,scopeValues:X._values};if(this.opts.unevaluated){let{props:K,items:M}=H;if(L.evaluated={props:K instanceof lw.Name?void 0:K,items:M instanceof lw.Name?void 0:M,dynamicProps:K instanceof lw.Name,dynamicItems:M instanceof lw.Name},L.source)L.source.evaluated=(0,lw.stringify)(L.evaluated)}return w.validate=L,w}catch(D){if(delete w.validate,delete w.validateName,z)this.logger.error("Error compiling schema, function code:",z);throw D}finally{this._compilations.delete(w)}}lY.compileSchema=g6;function NB(w,b,$){var W;$=(0,iw.resolveUrl)(this.opts.uriResolver,b,$);let Q=w.refs[$];if(Q)return Q;let G=RB.call(this,w,$);if(G===void 0){let X=(W=w.localRefs)===null||W===void 0?void 0:W[$],{schemaId:Y}=this.opts;if(X)G=new s0({schema:X,schemaId:Y,root:w,baseId:b})}if(G===void 0)return;return w.refs[$]=EB.call(this,G)}lY.resolveRef=NB;function EB(w){if((0,iw.inlineRef)(w.schema,this.opts.inlineRefs))return w.schema;return w.validate?w:g6.call(this,w)}function gY(w){for(let b of this._compilations)if(TB(b,w))return b}lY.getCompilingSchema=gY;function TB(w,b){return w.schema===b.schema&&w.root===b.root&&w.baseId===b.baseId}function RB(w,b){let $;while(typeof($=this.refs[b])=="string")b=$;return $||this.schemas[b]||B$.call(this,w,b)}function B$(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 m6.call(this,$,w);let G=(0,iw.normalizeId)(W),X=this.refs[G]||this.schemas[G];if(typeof X=="string"){let Y=B$.call(this,w,X);if(typeof(Y===null||Y===void 0?void 0:Y.schema)!=="object")return;return m6.call(this,$,Y)}if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;if(!X.validate)g6.call(this,X);if(G===(0,iw.normalizeId)(b)){let{schema:Y}=X,{schemaId:J}=this.opts,H=Y[J];if(H)Q=(0,iw.resolveUrl)(this.opts.uriResolver,Q,H);return new s0({schema:Y,schemaId:J,root:w,baseId:Q})}return m6.call(this,$,X)}lY.resolveSchema=B$;var SB=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function m6(w,{baseId:b,schema:$,root:W}){var Q;if(((Q=w.fragment)===null||Q===void 0?void 0:Q[0])!=="/")return;for(let Y of w.fragment.slice(1).split("/")){if(typeof $==="boolean")return;let J=$[(0,mY.unescapeFragment)(Y)];if(J===void 0)return;$=J;let H=typeof $==="object"&&$[this.opts.schemaId];if(!SB.has(Y)&&H)b=(0,iw.resolveUrl)(this.opts.uriResolver,b,H)}let G;if(typeof $!="boolean"&&$.$ref&&!(0,mY.schemaHasRulesButRef)($,this.RULES)){let Y=(0,iw.resolveUrl)(this.opts.uriResolver,b,$.$ref);G=B$.call(this,W,Y)}let{schemaId:X}=this.opts;if(G=G||new s0({schema:$,schemaId:X,root:W,baseId:b}),G.schema!==G.root.schema)return G;return}});var nY=I((mT,xB)=>{xB.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 i6=I((gT,tY)=>{var yB=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),oY=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 l6(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 hB=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function pY(w){return w.length=0,!0}function uB(w,b,$){if(w.length){let W=l6(w);if(W!=="")b.push(W);else return $.error=!0,!1;w.length=0}return!0}function fB(w){let b=0,$={error:!1,address:"",zone:""},W=[],Q=[],G=!1,X=!1,Y=uB;for(let J=0;J<w.length;J++){let H=w[J];if(H==="["||H==="]")continue;if(H===":"){if(G===!0)X=!0;if(!Y(Q,W,$))break;if(++b>7){$.error=!0;break}if(J>0&&w[J-1]===":")G=!0;W.push(":");continue}else if(H==="%"){if(!Y(Q,W,$))break;Y=pY}else{Q.push(H);continue}}if(Q.length)if(Y===pY)$.zone=Q.join("");else if(X)W.push(Q.join(""));else W.push(l6(Q));return $.address=W.join(""),$}function dY(w){if(cB(w,":")<2)return{host:w,isIPV6:!1};let b=fB(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 cB(w,b){let $=0;for(let W=0;W<w.length;W++)if(w[W]===b)$++;return $}function mB(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 gB(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 lB(w){let b=[];if(w.userinfo!==void 0)b.push(w.userinfo),b.push("@");if(w.host!==void 0){let $=unescape(w.host);if(!oY($)){let W=dY($);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}tY.exports={nonSimpleDomain:hB,recomposeAuthority:lB,normalizeComponentEncoding:gB,removeDotSegments:mB,isIPv4:oY,isUUID:yB,normalizeIPv6:dY,stringArrayToHexStripped:l6}});var wJ=I((lT,aY)=>{var{isUUID:iB}=i6(),nB=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,pB=["http","https","ws","wss","urn","urn:uuid"];function oB(w){return pB.indexOf(w)!==-1}function n6(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 rY(w){if(!w.host)w.error=w.error||"HTTP URIs must have a host.";return w}function sY(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 dB(w){return w.secure=n6(w),w.resourceName=(w.path||"/")+(w.query?"?"+w.query:""),w.path=void 0,w.query=void 0,w}function tB(w){if(w.port===(n6(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 rB(w,b){if(!w.path)return w.error="URN can not be parsed",w;let $=w.path.match(nB);if($){let W=b.scheme||w.scheme||"urn";w.nid=$[1].toLowerCase(),w.nss=$[2];let Q=`${W}:${b.nid||w.nid}`,G=p6(Q);if(w.path=void 0,G)w=G.parse(w,b)}else w.error=w.error||"URN can not be parsed.";return w}function sB(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}`,G=p6(Q);if(G)w=G.serialize(w,b);let X=w,Y=w.nss;return X.path=`${W||b.nid}:${Y}`,b.skipEscape=!0,X}function eB(w,b){let $=w;if($.uuid=$.nss,$.nss=void 0,!b.tolerant&&(!$.uuid||!iB($.uuid)))$.error=$.error||"UUID is not valid.";return $}function aB(w){let b=w;return b.nss=(w.uuid||"").toLowerCase(),b}var eY={scheme:"http",domainHost:!0,parse:rY,serialize:sY},wK={scheme:"https",domainHost:eY.domainHost,parse:rY,serialize:sY},O$={scheme:"ws",domainHost:!0,parse:dB,serialize:tB},bK={scheme:"wss",domainHost:O$.domainHost,parse:O$.parse,serialize:O$.serialize},$K={scheme:"urn",parse:rB,serialize:sB,skipNormalize:!0},WK={scheme:"urn:uuid",parse:eB,serialize:aB,skipNormalize:!0},M$={http:eY,https:wK,ws:O$,wss:bK,urn:$K,"urn:uuid":WK};Object.setPrototypeOf(M$,null);function p6(w){return w&&(M$[w]||M$[w.toLowerCase()])||void 0}aY.exports={wsIsSecure:n6,SCHEMES:M$,isValidSchemeName:oB,getSchemeHandler:p6}});var WJ=I((iT,P$)=>{var{normalizeIPv6:QK,removeDotSegments:e0,recomposeAuthority:GK,normalizeComponentEncoding:q$,isIPv4:XK,nonSimpleDomain:YK}=i6(),{SCHEMES:JK,getSchemeHandler:bJ}=wJ();function HK(w,b){if(typeof w==="string")w=ew(H1(w,b),b);else if(typeof w==="object")w=H1(ew(w,b),b);return w}function zK(w,b,$){let W=$?Object.assign({scheme:"null"},$):{scheme:"null"},Q=$J(H1(w,W),H1(b,W),W,!0);return W.skipEscape=!0,ew(Q,W)}function $J(w,b,$,W){let Q={};if(!W)w=H1(ew(w,$),$),b=H1(ew(b,$),$);if($=$||{},!$.tolerant&&b.scheme)Q.scheme=b.scheme,Q.userinfo=b.userinfo,Q.host=b.host,Q.port=b.port,Q.path=e0(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=e0(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=e0(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=e0(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 DK(w,b,$){if(typeof w==="string")w=unescape(w),w=ew(q$(H1(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=ew(q$(w,!0),{...$,skipEscape:!0});if(typeof b==="string")b=unescape(b),b=ew(q$(H1(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=ew(q$(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=[],G=bJ(W.scheme||$.scheme);if(G&&G.serialize)G.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 X=GK($);if(X!==void 0){if(W.reference!=="suffix")Q.push("//");if(Q.push(X),$.path&&$.path[0]!=="/")Q.push("/")}if($.path!==void 0){let Y=$.path;if(!W.absolutePath&&(!G||!G.absolutePath))Y=e0(Y);if(X===void 0&&Y[0]==="/"&&Y[1]==="/")Y="/%2F"+Y.slice(2);Q.push(Y)}if($.query!==void 0)Q.push("?",$.query);if($.fragment!==void 0)Q.push("#",$.fragment);return Q.join("")}var UK=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function H1(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 G=w.match(UK);if(G){if(W.scheme=G[1],W.userinfo=G[3],W.host=G[4],W.port=parseInt(G[5],10),W.path=G[6]||"",W.query=G[7],W.fragment=G[8],isNaN(W.port))W.port=G[5];if(W.host)if(XK(W.host)===!1){let J=QK(W.host);W.host=J.host.toLowerCase(),Q=J.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 X=bJ($.scheme||W.scheme);if(!$.unicodeSupport&&(!X||!X.unicodeSupport)){if(W.host&&($.domainHost||X&&X.domainHost)&&Q===!1&&YK(W.host))try{W.host=URL.domainToASCII(W.host.toLowerCase())}catch(Y){W.error=W.error||"Host's domain name can not be converted to ASCII: "+Y}}if(!X||X&&!X.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(X&&X.parse)X.parse(W,$)}else W.error=W.error||"URI can not be parsed.";return W}var o6={SCHEMES:JK,normalize:HK,resolve:zK,resolveComponent:$J,equal:DK,serialize:ew,parse:H1};P$.exports=o6;P$.exports.default=o6;P$.exports.fastUri=o6});var XJ=I((GJ)=>{Object.defineProperty(GJ,"__esModule",{value:!0});var QJ=WJ();QJ.code='require("ajv/dist/runtime/uri").default';GJ.default=QJ});var LJ=I((z1)=>{Object.defineProperty(z1,"__esModule",{value:!0});z1.CodeGen=z1.Name=z1.nil=z1.stringify=z1.str=z1._=z1.KeywordCxt=void 0;var LK=t0();Object.defineProperty(z1,"KeywordCxt",{enumerable:!0,get:function(){return LK.KeywordCxt}});var b0=f();Object.defineProperty(z1,"_",{enumerable:!0,get:function(){return b0._}});Object.defineProperty(z1,"str",{enumerable:!0,get:function(){return b0.str}});Object.defineProperty(z1,"stringify",{enumerable:!0,get:function(){return b0.stringify}});Object.defineProperty(z1,"nil",{enumerable:!0,get:function(){return b0.nil}});Object.defineProperty(z1,"Name",{enumerable:!0,get:function(){return b0.Name}});Object.defineProperty(z1,"CodeGen",{enumerable:!0,get:function(){return b0.CodeGen}});var FK=F$(),DJ=r0(),BK=N6(),a0=K$(),KK=f(),wb=p0(),Z$=n0(),t6=d(),YJ=nY(),OK=XJ(),UJ=(w,b)=>new RegExp(w,b);UJ.code="new RegExp";var MK=["removeAdditional","useDefaults","coerceTypes"],qK=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),PK={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."},ZK={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},JJ=200;function VK(w){var b,$,W,Q,G,X,Y,J,H,z,D,A,L,K,M,j,V,C,R,m,_,tw,b1,$4,W4;let L0=w.strict,Q4=(b=w.code)===null||b===void 0?void 0:b.optimize,r9=Q4===!0||Q4===void 0?1:Q4||0,s9=(W=($=w.code)===null||$===void 0?void 0:$.regExp)!==null&&W!==void 0?W:UJ,q5=(Q=w.uriResolver)!==null&&Q!==void 0?Q:OK.default;return{strictSchema:(X=(G=w.strictSchema)!==null&&G!==void 0?G:L0)!==null&&X!==void 0?X:!0,strictNumbers:(J=(Y=w.strictNumbers)!==null&&Y!==void 0?Y:L0)!==null&&J!==void 0?J:!0,strictTypes:(z=(H=w.strictTypes)!==null&&H!==void 0?H:L0)!==null&&z!==void 0?z:"log",strictTuples:(A=(D=w.strictTuples)!==null&&D!==void 0?D:L0)!==null&&A!==void 0?A:"log",strictRequired:(K=(L=w.strictRequired)!==null&&L!==void 0?L:L0)!==null&&K!==void 0?K:!1,code:w.code?{...w.code,optimize:r9,regExp:s9}:{optimize:r9,regExp:s9},loopRequired:(M=w.loopRequired)!==null&&M!==void 0?M:JJ,loopEnum:(j=w.loopEnum)!==null&&j!==void 0?j:JJ,meta:(V=w.meta)!==null&&V!==void 0?V:!0,messages:(C=w.messages)!==null&&C!==void 0?C:!0,inlineRefs:(R=w.inlineRefs)!==null&&R!==void 0?R:!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:(b1=w.validateFormats)!==null&&b1!==void 0?b1:!0,unicodeRegExp:($4=w.unicodeRegExp)!==null&&$4!==void 0?$4:!0,int32range:(W4=w.int32range)!==null&&W4!==void 0?W4:!0,uriResolver:q5}}class V${constructor(w={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,w=this.opts={...w,...VK(w)};let{es5:b,lines:$}=this.opts.code;this.scope=new KK.ValueScope({scope:{},prefixes:qK,es5:b,lines:$}),this.logger=RK(w.logger);let W=w.validateFormats;if(w.validateFormats=!1,this.RULES=(0,BK.getRules)(),HJ.call(this,PK,w,"NOT SUPPORTED"),HJ.call(this,ZK,w,"DEPRECATED","warn"),this._metaOpts=EK.call(this),w.formats)IK.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),w.keywords)NK.call(this,w.keywords);if(typeof w.meta=="object")this.addMetaSchema(w.meta);jK.call(this),w.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:w,meta:b,schemaId:$}=this.opts,W=YJ;if($==="id")W={...YJ},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 D=this._addSchema(H,z);return D.validate||G.call(this,D)}async function Q(H){if(H&&!this.getSchema(H))await W.call(this,{$ref:H},!0)}async function G(H){try{return this._compileSchemaEnv(H)}catch(z){if(!(z instanceof DJ.default))throw z;return X.call(this,z),await Y.call(this,z.missingSchema),G.call(this,H)}}function X({missingSchema:H,missingRef:z}){if(this.refs[H])throw Error(`AnySchema ${H} is loaded but ${z} cannot be resolved`)}async function Y(H){let z=await J.call(this,H);if(!this.refs[H])await Q.call(this,z.$schema);if(!this.refs[H])this.addSchema(z,H,b)}async function J(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 G of w)this.addSchema(G,void 0,$,W);return this}let Q;if(typeof w==="object"){let{schemaId:G}=this.opts;if(Q=w[G],Q!==void 0&&typeof Q!="string")throw Error(`schema ${G} must be string`)}return b=(0,wb.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=zJ.call(this,w))=="string")w=b;if(b===void 0){let{schemaId:$}=this.opts,W=new a0.SchemaEnv({schema:{},schemaId:$});if(b=a0.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=zJ.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,wb.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(CK.call(this,$,b),!b)return(0,t6.eachItem)($,(Q)=>d6.call(this,Q)),this;_K.call(this,b);let W={...b,type:(0,Z$.getJSONTypes)(b.type),schemaType:(0,Z$.getJSONTypes)(b.schemaType)};return(0,t6.eachItem)($,W.type.length===0?(Q)=>d6.call(this,Q,W):(Q)=>W.type.forEach((G)=>d6.call(this,Q,W,G))),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),G=w;for(let X of Q)G=G[X];for(let X in $){let Y=$[X];if(typeof Y!="object")continue;let{$data:J}=Y.definition,H=G[X];if(J&&H)G[X]=AJ(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 G,{schemaId:X}=this.opts;if(typeof w=="object")G=w[X];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 Y=this._cache.get(w);if(Y!==void 0)return Y;$=(0,wb.normalizeId)(G||$);let J=wb.getSchemaRefs.call(this,w,$);if(Y=new a0.SchemaEnv({schema:w,schemaId:X,meta:b,baseId:$,localRefs:J}),this._cache.set(Y.schema,Y),Q&&!$.startsWith("#")){if($)this._checkUnique($);this.refs[$]=Y}if(W)this.validateSchema(w,!0);return Y}_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 a0.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{a0.compileSchema.call(this,w)}finally{this.opts=b}}}V$.ValidationError=FK.default;V$.MissingRefError=DJ.default;z1.default=V$;function HJ(w,b,$,W="error"){for(let Q in w){let G=Q;if(G in b)this.logger[W](`${$}: option ${Q}. ${w[G]}`)}}function zJ(w){return w=(0,wb.normalizeId)(w),this.schemas[w]||this.refs[w]}function jK(){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 IK(){for(let w in this.opts.formats){let b=this.opts.formats[w];if(b)this.addFormat(w,b)}}function NK(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 EK(){let w={...this.opts};for(let b of MK)delete w[b];return w}var TK={log(){},warn(){},error(){}};function RK(w){if(w===!1)return TK;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 SK=/^[a-z_$][a-z0-9_$:-]*$/i;function CK(w,b){let{RULES:$}=this;if((0,t6.eachItem)(w,(W)=>{if($.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!SK.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 d6(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:G}=this,X=Q?G.post:G.rules.find(({type:J})=>J===$);if(!X)X={type:$,rules:[]},G.rules.push(X);if(G.keywords[w]=!0,!b)return;let Y={keyword:w,definition:{...b,type:(0,Z$.getJSONTypes)(b.type),schemaType:(0,Z$.getJSONTypes)(b.schemaType)}};if(b.before)vK.call(this,X,Y,b.before);else X.rules.push(Y);G.all[w]=Y,(W=b.implements)===null||W===void 0||W.forEach((J)=>this.addKeyword(J))}function vK(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 _K(w){let{metaSchema:b}=w;if(b===void 0)return;if(w.$data&&this.opts.$data)b=AJ(b);w.validateSchema=this.compile(b,!0)}var kK={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function AJ(w){return{anyOf:[w,kK]}}});var BJ=I((FJ)=>{Object.defineProperty(FJ,"__esModule",{value:!0});var hK={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};FJ.default=hK});var ZJ=I((qJ)=>{Object.defineProperty(qJ,"__esModule",{value:!0});qJ.callRef=qJ.getValidate=void 0;var fK=r0(),KJ=yw(),Ew=f(),$0=Y1(),OJ=K$(),j$=d(),cK={keyword:"$ref",schemaType:"string",code(w){let{gen:b,schema:$,it:W}=w,{baseId:Q,schemaEnv:G,validateName:X,opts:Y,self:J}=W,{root:H}=G;if(($==="#"||$==="#/")&&Q===H.baseId)return D();let z=OJ.resolveRef.call(J,H,Q,$);if(z===void 0)throw new fK.default(W.opts.uriResolver,Q,$);if(z instanceof OJ.SchemaEnv)return A(z);return L(z);function D(){if(G===H)return I$(w,X,G,G.$async);let K=b.scopeValue("root",{ref:H});return I$(w,Ew._`${K}.validate`,H,H.$async)}function A(K){let M=MJ(w,K);I$(w,M,K,K.$async)}function L(K){let M=b.scopeValue("schema",Y.code.source===!0?{ref:K,code:(0,Ew.stringify)(K)}:{ref:K}),j=b.name("valid"),V=w.subschema({schema:K,dataTypes:[],schemaPath:Ew.nil,topSchemaRef:M,errSchemaPath:$},j);w.mergeEvaluated(V),w.ok(j)}}};function MJ(w,b){let{gen:$}=w;return b.validate?$.scopeValue("validate",{ref:b.validate}):Ew._`${$.scopeValue("wrapper",{ref:b})}.validate`}qJ.getValidate=MJ;function I$(w,b,$,W){let{gen:Q,it:G}=w,{allErrors:X,schemaEnv:Y,opts:J}=G,H=J.passContext?$0.default.this:Ew.nil;if(W)z();else D();function z(){if(!Y.$async)throw Error("async schema referenced by sync schema");let K=Q.let("valid");Q.try(()=>{if(Q.code(Ew._`await ${(0,KJ.callValidateCode)(w,b,H)}`),L(b),!X)Q.assign(K,!0)},(M)=>{if(Q.if(Ew._`!(${M} instanceof ${G.ValidationError})`,()=>Q.throw(M)),A(M),!X)Q.assign(K,!1)}),w.ok(K)}function D(){w.result((0,KJ.callValidateCode)(w,b,H),()=>L(b),()=>A(b))}function A(K){let M=Ew._`${K}.errors`;Q.assign($0.default.vErrors,Ew._`${$0.default.vErrors} === null ? ${M} : ${$0.default.vErrors}.concat(${M})`),Q.assign($0.default.errors,Ew._`${$0.default.vErrors}.length`)}function L(K){var M;if(!G.opts.unevaluated)return;let j=(M=$===null||$===void 0?void 0:$.validate)===null||M===void 0?void 0:M.evaluated;if(G.props!==!0)if(j&&!j.dynamicProps){if(j.props!==void 0)G.props=j$.mergeEvaluated.props(Q,j.props,G.props)}else{let V=Q.var("props",Ew._`${K}.evaluated.props`);G.props=j$.mergeEvaluated.props(Q,V,G.props,Ew.Name)}if(G.items!==!0)if(j&&!j.dynamicItems){if(j.items!==void 0)G.items=j$.mergeEvaluated.items(Q,j.items,G.items)}else{let V=Q.var("items",Ew._`${K}.evaluated.items`);G.items=j$.mergeEvaluated.items(Q,V,G.items,Ew.Name)}}}qJ.callRef=I$;qJ.default=cK});var jJ=I((VJ)=>{Object.defineProperty(VJ,"__esModule",{value:!0});var lK=BJ(),iK=ZJ(),nK=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",lK.default,iK.default];VJ.default=nK});var NJ=I((IJ)=>{Object.defineProperty(IJ,"__esModule",{value:!0});var N$=f(),R1=N$.operators,E$={maximum:{okStr:"<=",ok:R1.LTE,fail:R1.GT},minimum:{okStr:">=",ok:R1.GTE,fail:R1.LT},exclusiveMaximum:{okStr:"<",ok:R1.LT,fail:R1.GTE},exclusiveMinimum:{okStr:">",ok:R1.GT,fail:R1.LTE}},oK={message:({keyword:w,schemaCode:b})=>N$.str`must be ${E$[w].okStr} ${b}`,params:({keyword:w,schemaCode:b})=>N$._`{comparison: ${E$[w].okStr}, limit: ${b}}`},dK={keyword:Object.keys(E$),type:"number",schemaType:"number",$data:!0,error:oK,code(w){let{keyword:b,data:$,schemaCode:W}=w;w.fail$data(N$._`${$} ${E$[b].fail} ${W} || isNaN(${$})`)}};IJ.default=dK});var TJ=I((EJ)=>{Object.defineProperty(EJ,"__esModule",{value:!0});var bb=f(),rK={message:({schemaCode:w})=>bb.str`must be multiple of ${w}`,params:({schemaCode:w})=>bb._`{multipleOf: ${w}}`},sK={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:rK,code(w){let{gen:b,data:$,schemaCode:W,it:Q}=w,G=Q.opts.multipleOfPrecision,X=b.let("res"),Y=G?bb._`Math.abs(Math.round(${X}) - ${X}) > 1e-${G}`:bb._`${X} !== parseInt(${X})`;w.fail$data(bb._`(${W} === 0 || (${X} = ${$}/${W}, ${Y}))`)}};EJ.default=sK});var CJ=I((SJ)=>{Object.defineProperty(SJ,"__esModule",{value:!0});function RJ(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 $}SJ.default=RJ;RJ.code='require("ajv/dist/runtime/ucs2length").default'});var _J=I((vJ)=>{Object.defineProperty(vJ,"__esModule",{value:!0});var u1=f(),wO=d(),bO=CJ(),$O={message({keyword:w,schemaCode:b}){let $=w==="maxLength"?"more":"fewer";return u1.str`must NOT have ${$} than ${b} characters`},params:({schemaCode:w})=>u1._`{limit: ${w}}`},WO={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:$O,code(w){let{keyword:b,data:$,schemaCode:W,it:Q}=w,G=b==="maxLength"?u1.operators.GT:u1.operators.LT,X=Q.opts.unicode===!1?u1._`${$}.length`:u1._`${(0,wO.useFunc)(w.gen,bO.default)}(${$})`;w.fail$data(u1._`${X} ${G} ${W}`)}};vJ.default=WO});var xJ=I((kJ)=>{Object.defineProperty(kJ,"__esModule",{value:!0});var GO=yw(),T$=f(),XO={message:({schemaCode:w})=>T$.str`must match pattern "${w}"`,params:({schemaCode:w})=>T$._`{pattern: ${w}}`},YO={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:XO,code(w){let{data:b,$data:$,schema:W,schemaCode:Q,it:G}=w,X=G.opts.unicodeRegExp?"u":"",Y=$?T$._`(new RegExp(${Q}, ${X}))`:(0,GO.usePattern)(w,W);w.fail$data(T$._`!${Y}.test(${b})`)}};kJ.default=YO});var hJ=I((yJ)=>{Object.defineProperty(yJ,"__esModule",{value:!0});var $b=f(),HO={message({keyword:w,schemaCode:b}){let $=w==="maxProperties"?"more":"fewer";return $b.str`must NOT have ${$} than ${b} properties`},params:({schemaCode:w})=>$b._`{limit: ${w}}`},zO={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:HO,code(w){let{keyword:b,data:$,schemaCode:W}=w,Q=b==="maxProperties"?$b.operators.GT:$b.operators.LT;w.fail$data($b._`Object.keys(${$}).length ${Q} ${W}`)}};yJ.default=zO});var fJ=I((uJ)=>{Object.defineProperty(uJ,"__esModule",{value:!0});var Wb=yw(),Qb=f(),UO=d(),AO={message:({params:{missingProperty:w}})=>Qb.str`must have required property '${w}'`,params:({params:{missingProperty:w}})=>Qb._`{missingProperty: ${w}}`},LO={keyword:"required",type:"object",schemaType:"array",$data:!0,error:AO,code(w){let{gen:b,schema:$,schemaCode:W,data:Q,$data:G,it:X}=w,{opts:Y}=X;if(!G&&$.length===0)return;let J=$.length>=Y.loopRequired;if(X.allErrors)H();else z();if(Y.strictRequired){let L=w.parentSchema.properties,{definedProperties:K}=w.it;for(let M of $)if((L===null||L===void 0?void 0:L[M])===void 0&&!K.has(M)){let j=X.schemaEnv.baseId+X.errSchemaPath,V=`required property "${M}" is not defined at "${j}" (strictRequired)`;(0,UO.checkStrictMode)(X,V,X.opts.strictRequired)}}function H(){if(J||G)w.block$data(Qb.nil,D);else for(let L of $)(0,Wb.checkReportMissingProp)(w,L)}function z(){let L=b.let("missing");if(J||G){let K=b.let("valid",!0);w.block$data(K,()=>A(L,K)),w.ok(K)}else b.if((0,Wb.checkMissingProp)(w,$,L)),(0,Wb.reportMissingProp)(w,L),b.else()}function D(){b.forOf("prop",W,(L)=>{w.setParams({missingProperty:L}),b.if((0,Wb.noPropertyInData)(b,Q,L,Y.ownProperties),()=>w.error())})}function A(L,K){w.setParams({missingProperty:L}),b.forOf(L,W,()=>{b.assign(K,(0,Wb.propertyInData)(b,Q,L,Y.ownProperties)),b.if((0,Qb.not)(K),()=>{w.error(),b.break()})},Qb.nil)}}};uJ.default=LO});var mJ=I((cJ)=>{Object.defineProperty(cJ,"__esModule",{value:!0});var Gb=f(),BO={message({keyword:w,schemaCode:b}){let $=w==="maxItems"?"more":"fewer";return Gb.str`must NOT have ${$} than ${b} items`},params:({schemaCode:w})=>Gb._`{limit: ${w}}`},KO={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:BO,code(w){let{keyword:b,data:$,schemaCode:W}=w,Q=b==="maxItems"?Gb.operators.GT:Gb.operators.LT;w.fail$data(Gb._`${$}.length ${Q} ${W}`)}};cJ.default=KO});var R$=I((lJ)=>{Object.defineProperty(lJ,"__esModule",{value:!0});var gJ=k6();gJ.code='require("ajv/dist/runtime/equal").default';lJ.default=gJ});var nJ=I((iJ)=>{Object.defineProperty(iJ,"__esModule",{value:!0});var r6=n0(),Ow=f(),qO=d(),PO=R$(),ZO={message:({params:{i:w,j:b}})=>Ow.str`must NOT have duplicate items (items ## ${b} and ${w} are identical)`,params:({params:{i:w,j:b}})=>Ow._`{i: ${w}, j: ${b}}`},VO={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:ZO,code(w){let{gen:b,data:$,$data:W,schema:Q,parentSchema:G,schemaCode:X,it:Y}=w;if(!W&&!Q)return;let J=b.let("valid"),H=G.items?(0,r6.getSchemaTypes)(G.items):[];w.block$data(J,z,Ow._`${X} === false`),w.ok(J);function z(){let K=b.let("i",Ow._`${$}.length`),M=b.let("j");w.setParams({i:K,j:M}),b.assign(J,!0),b.if(Ow._`${K} > 1`,()=>(D()?A:L)(K,M))}function D(){return H.length>0&&!H.some((K)=>K==="object"||K==="array")}function A(K,M){let j=b.name("item"),V=(0,r6.checkDataTypes)(H,j,Y.opts.strictNumbers,r6.DataType.Wrong),C=b.const("indices",Ow._`{}`);b.for(Ow._`;${K}--;`,()=>{if(b.let(j,Ow._`${$}[${K}]`),b.if(V,Ow._`continue`),H.length>1)b.if(Ow._`typeof ${j} == "string"`,Ow._`${j} += "_"`);b.if(Ow._`typeof ${C}[${j}] == "number"`,()=>{b.assign(M,Ow._`${C}[${j}]`),w.error(),b.assign(J,!1).break()}).code(Ow._`${C}[${j}] = ${K}`)})}function L(K,M){let j=(0,qO.useFunc)(b,PO.default),V=b.name("outer");b.label(V).for(Ow._`;${K}--;`,()=>b.for(Ow._`${M} = ${K}; ${M}--;`,()=>b.if(Ow._`${j}(${$}[${K}], ${$}[${M}])`,()=>{w.error(),b.assign(J,!1).break(V)})))}}};iJ.default=VO});var oJ=I((pJ)=>{Object.defineProperty(pJ,"__esModule",{value:!0});var s6=f(),IO=d(),NO=R$(),EO={message:"must be equal to constant",params:({schemaCode:w})=>s6._`{allowedValue: ${w}}`},TO={keyword:"const",$data:!0,error:EO,code(w){let{gen:b,data:$,$data:W,schemaCode:Q,schema:G}=w;if(W||G&&typeof G=="object")w.fail$data(s6._`!${(0,IO.useFunc)(b,NO.default)}(${$}, ${Q})`);else w.fail(s6._`${G} !== ${$}`)}};pJ.default=TO});var tJ=I((dJ)=>{Object.defineProperty(dJ,"__esModule",{value:!0});var Xb=f(),SO=d(),CO=R$(),vO={message:"must be equal to one of the allowed values",params:({schemaCode:w})=>Xb._`{allowedValues: ${w}}`},_O={keyword:"enum",schemaType:"array",$data:!0,error:vO,code(w){let{gen:b,data:$,$data:W,schema:Q,schemaCode:G,it:X}=w;if(!W&&Q.length===0)throw Error("enum must have non-empty array");let Y=Q.length>=X.opts.loopEnum,J,H=()=>J!==null&&J!==void 0?J:J=(0,SO.useFunc)(b,CO.default),z;if(Y||W)z=b.let("valid"),w.block$data(z,D);else{if(!Array.isArray(Q))throw Error("ajv implementation error");let L=b.const("vSchema",G);z=(0,Xb.or)(...Q.map((K,M)=>A(L,M)))}w.pass(z);function D(){b.assign(z,!1),b.forOf("v",G,(L)=>b.if(Xb._`${H()}(${$}, ${L})`,()=>b.assign(z,!0).break()))}function A(L,K){let M=Q[K];return typeof M==="object"&&M!==null?Xb._`${H()}(${$}, ${L}[${K}])`:Xb._`${$} === ${M}`}}};dJ.default=_O});var sJ=I((rJ)=>{Object.defineProperty(rJ,"__esModule",{value:!0});var xO=NJ(),yO=TJ(),hO=_J(),uO=xJ(),fO=hJ(),cO=fJ(),mO=mJ(),gO=nJ(),lO=oJ(),iO=tJ(),nO=[xO.default,yO.default,hO.default,uO.default,fO.default,cO.default,mO.default,gO.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},lO.default,iO.default];rJ.default=nO});var a6=I((aJ)=>{Object.defineProperty(aJ,"__esModule",{value:!0});aJ.validateAdditionalItems=void 0;var f1=f(),e6=d(),oO={message:({params:{len:w}})=>f1.str`must NOT have more than ${w} items`,params:({params:{len:w}})=>f1._`{limit: ${w}}`},dO={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:oO,code(w){let{parentSchema:b,it:$}=w,{items:W}=b;if(!Array.isArray(W)){(0,e6.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}eJ(w,W)}};function eJ(w,b){let{gen:$,schema:W,data:Q,keyword:G,it:X}=w;X.items=!0;let Y=$.const("len",f1._`${Q}.length`);if(W===!1)w.setParams({len:b.length}),w.pass(f1._`${Y} <= ${b.length}`);else if(typeof W=="object"&&!(0,e6.alwaysValidSchema)(X,W)){let H=$.var("valid",f1._`${Y} <= ${b.length}`);$.if((0,f1.not)(H),()=>J(H)),w.ok(H)}function J(H){$.forRange("i",b.length,Y,(z)=>{if(w.subschema({keyword:G,dataProp:z,dataPropType:e6.Type.Num},H),!X.allErrors)$.if((0,f1.not)(H),()=>$.break())})}}aJ.validateAdditionalItems=eJ;aJ.default=dO});var w9=I((WH)=>{Object.defineProperty(WH,"__esModule",{value:!0});WH.validateTuple=void 0;var bH=f(),S$=d(),rO=yw(),sO={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(w){let{schema:b,it:$}=w;if(Array.isArray(b))return $H(w,"additionalItems",b);if($.items=!0,(0,S$.alwaysValidSchema)($,b))return;w.ok((0,rO.validateArray)(w))}};function $H(w,b,$=w.schema){let{gen:W,parentSchema:Q,data:G,keyword:X,it:Y}=w;if(z(Q),Y.opts.unevaluated&&$.length&&Y.items!==!0)Y.items=S$.mergeEvaluated.items(W,$.length,Y.items);let J=W.name("valid"),H=W.const("len",bH._`${G}.length`);$.forEach((D,A)=>{if((0,S$.alwaysValidSchema)(Y,D))return;W.if(bH._`${H} > ${A}`,()=>w.subschema({keyword:X,schemaProp:A,dataProp:A},J)),w.ok(J)});function z(D){let{opts:A,errSchemaPath:L}=Y,K=$.length,M=K===D.minItems&&(K===D.maxItems||D[b]===!1);if(A.strictTuples&&!M){let j=`"${X}" is ${K}-tuple, but minItems or maxItems/${b} are not specified or different at path "${L}"`;(0,S$.checkStrictMode)(Y,j,A.strictTuples)}}}WH.validateTuple=$H;WH.default=sO});var XH=I((GH)=>{Object.defineProperty(GH,"__esModule",{value:!0});var aO=w9(),wM={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(w)=>(0,aO.validateTuple)(w,"items")};GH.default=wM});var HH=I((JH)=>{Object.defineProperty(JH,"__esModule",{value:!0});var YH=f(),$M=d(),WM=yw(),QM=a6(),GM={message:({params:{len:w}})=>YH.str`must NOT have more than ${w} items`,params:({params:{len:w}})=>YH._`{limit: ${w}}`},XM={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:GM,code(w){let{schema:b,parentSchema:$,it:W}=w,{prefixItems:Q}=$;if(W.items=!0,(0,$M.alwaysValidSchema)(W,b))return;if(Q)(0,QM.validateAdditionalItems)(w,Q);else w.ok((0,WM.validateArray)(w))}};JH.default=XM});var DH=I((zH)=>{Object.defineProperty(zH,"__esModule",{value:!0});var hw=f(),C$=d(),JM={message:({params:{min:w,max:b}})=>b===void 0?hw.str`must contain at least ${w} valid item(s)`:hw.str`must contain at least ${w} and no more than ${b} valid item(s)`,params:({params:{min:w,max:b}})=>b===void 0?hw._`{minContains: ${w}}`:hw._`{minContains: ${w}, maxContains: ${b}}`},HM={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:JM,code(w){let{gen:b,schema:$,parentSchema:W,data:Q,it:G}=w,X,Y,{minContains:J,maxContains:H}=W;if(G.opts.next)X=J===void 0?1:J,Y=H;else X=1;let z=b.const("len",hw._`${Q}.length`);if(w.setParams({min:X,max:Y}),Y===void 0&&X===0){(0,C$.checkStrictMode)(G,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(Y!==void 0&&X>Y){(0,C$.checkStrictMode)(G,'"minContains" > "maxContains" is always invalid'),w.fail();return}if((0,C$.alwaysValidSchema)(G,$)){let M=hw._`${z} >= ${X}`;if(Y!==void 0)M=hw._`${M} && ${z} <= ${Y}`;w.pass(M);return}G.items=!0;let D=b.name("valid");if(Y===void 0&&X===1)L(D,()=>b.if(D,()=>b.break()));else if(X===0){if(b.let(D,!0),Y!==void 0)b.if(hw._`${Q}.length > 0`,A)}else b.let(D,!1),A();w.result(D,()=>w.reset());function A(){let M=b.name("_valid"),j=b.let("count",0);L(M,()=>b.if(M,()=>K(j)))}function L(M,j){b.forRange("i",0,z,(V)=>{w.subschema({keyword:"contains",dataProp:V,dataPropType:C$.Type.Num,compositeRule:!0},M),j()})}function K(M){if(b.code(hw._`${M}++`),Y===void 0)b.if(hw._`${M} >= ${X}`,()=>b.assign(D,!0).break());else if(b.if(hw._`${M} > ${Y}`,()=>b.assign(D,!1).break()),X===1)b.assign(D,!0);else b.if(hw._`${M} >= ${X}`,()=>b.assign(D,!0))}}};zH.default=HM});var KH=I((LH)=>{Object.defineProperty(LH,"__esModule",{value:!0});LH.validateSchemaDeps=LH.validatePropertyDeps=LH.error=void 0;var b9=f(),DM=d(),Yb=yw();LH.error={message:({params:{property:w,depsCount:b,deps:$}})=>{let W=b===1?"property":"properties";return b9.str`must have ${W} ${$} when property ${w} is present`},params:({params:{property:w,depsCount:b,deps:$,missingProperty:W}})=>b9._`{property: ${w},
|
|
7
|
-
missingProperty: ${
|
|
2
|
+
var v5=Object.create;var{getPrototypeOf:_5,defineProperty:H4,getOwnPropertyNames:k5}=Object;var x5=Object.prototype.hasOwnProperty;function h5(w){return this[w]}var y5,u5,JQ=(w,b,$)=>{var Q=w!=null&&typeof w==="object";if(Q){var W=b?y5??=new WeakMap:u5??=new WeakMap,X=W.get(w);if(X)return X}$=w!=null?v5(_5(w)):{};let Y=b||!w||!w.__esModule?H4($,"default",{value:w,enumerable:!0}):$;for(let G of k5(w))if(!x5.call(Y,G))H4(Y,G,{get:h5.bind(w,G),enumerable:!0});if(Q)W.set(w,Y);return Y};var I=(w,b)=>()=>(b||w((b={exports:{}}).exports,b),b.exports);var f5=(w)=>w;function c5(w,b){this[w]=f5.bind(null,b)}var HQ=(w,b)=>{for(var $ in b)H4(w,$,{get:b[$],enumerable:!0,configurable:!0,set:c5.bind(b,$)})};var i0=I((zY)=>{Object.defineProperty(zY,"__esModule",{value:!0});zY.regexpCode=zY.getEsmExportName=zY.getProperty=zY.safeStringify=zY.stringify=zY.strConcat=zY.addCodeArg=zY.str=zY._=zY.nil=zY._Code=zY.Name=zY.IDENTIFIER=zY._CodeOrName=void 0;class Q${}zY._CodeOrName=Q$;zY.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r1 extends Q${constructor(w){super();if(!zY.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}}}zY.Name=r1;class mw extends Q${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 r1)b[$.str]=(b[$.str]||0)+1;return b},{})}}zY._Code=mw;zY.nil=new mw("");function JY(w,...b){let $=[w[0]],Q=0;while(Q<b.length)M6($,b[Q]),$.push(w[++Q]);return new mw($)}zY._=JY;var O6=new mw("+");function HY(w,...b){let $=[l0(w[0])],Q=0;while(Q<b.length)$.push(O6),M6($,b[Q]),$.push(O6,l0(w[++Q]));return HA($),new mw($)}zY.str=HY;function M6(w,b){if(b instanceof mw)w.push(...b._items);else if(b instanceof r1)w.push(b);else w.push(UA(b))}zY.addCodeArg=M6;function HA(w){let b=1;while(b<w.length-1){if(w[b]===O6){let $=zA(w[b-1],w[b+1]);if($!==void 0){w.splice(b-1,3,$);continue}w[b++]="+"}b++}}function zA(w,b){if(b==='""')return w;if(w==='""')return b;if(typeof w=="string"){if(b instanceof r1||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 r1))return`"${w}${b.slice(1)}`;return}function DA(w,b){return b.emptyStr()?w:w.emptyStr()?b:HY`${w}${b}`}zY.strConcat=DA;function UA(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:l0(Array.isArray(w)?w.join(","):w)}function AA(w){return new mw(l0(w))}zY.stringify=AA;function l0(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}zY.safeStringify=l0;function LA(w){return typeof w=="string"&&zY.IDENTIFIER.test(w)?new mw(`.${w}`):JY`[${w}]`}zY.getProperty=LA;function FA(w){if(typeof w=="string"&&zY.IDENTIFIER.test(w))return new mw(`${w}`);throw Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}zY.getEsmExportName=FA;function BA(w){return new mw(w.toString())}zY.regexpCode=BA});var P6=I((LY)=>{Object.defineProperty(LY,"__esModule",{value:!0});LY.ValueScope=LY.ValueScopeName=LY.Scope=LY.varKinds=LY.UsedValueState=void 0;var Iw=i0();class UY extends Error{constructor(w){super(`CodeGen: "code" for ${w} not defined`);this.value=w.value}}var X$;(function(w){w[w.Started=0]="Started",w[w.Completed=1]="Completed"})(X$||(LY.UsedValueState=X$={}));LY.varKinds={const:new Iw.Name("const"),let:new Iw.Name("let"),var:new Iw.Name("var")};class q6{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}}}LY.Scope=q6;class Z6 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)}[${$}]`}}LY.ValueScopeName=Z6;var RA=Iw._`\n`;class AY extends q6{constructor(w){super(w);this._values={},this._scope=w.scope,this.opts={...w,_n:w.lines?RA:Iw.nil}}get(){return this._scope}name(w){return new Z6(w,this._newName(w))}value(w,b){var $;if(b.ref===void 0)throw Error("CodeGen: ref must be passed in value");let Q=this.toName(w),{prefix:W}=Q,X=($=b.key)!==null&&$!==void 0?$:b.ref,Y=this._values[W];if(Y){let H=Y.get(X);if(H)return H}else Y=this._values[W]=new Map;Y.set(X,Q);let G=this._scope[W]||(this._scope[W]=[]),J=G.length;return G[J]=b.ref,Q.setValue(b,{property:W,itemIndex:J}),Q}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,(Q)=>{if(Q.value===void 0)throw Error(`CodeGen: name "${Q}" has no value`);return Q.value.code},b,$)}_reduceValues(w,b,$={},Q){let W=Iw.nil;for(let X in w){let Y=w[X];if(!Y)continue;let G=$[X]=$[X]||new Map;Y.forEach((J)=>{if(G.has(J))return;G.set(J,X$.Started);let H=b(J);if(H){let z=this.opts.es5?LY.varKinds.var:LY.varKinds.const;W=Iw._`${W}${z} ${J} = ${H};${this.opts._n}`}else if(H=Q===null||Q===void 0?void 0:Q(J))W=Iw._`${W}${H}${this.opts._n}`;else throw new UY(J);G.set(J,X$.Completed)})}return W}}LY.ValueScope=AY});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=i0(),gw=P6(),j1=i0();Object.defineProperty(Nw,"_",{enumerable:!0,get:function(){return j1._}});Object.defineProperty(Nw,"str",{enumerable:!0,get:function(){return j1.str}});Object.defineProperty(Nw,"strConcat",{enumerable:!0,get:function(){return j1.strConcat}});Object.defineProperty(Nw,"nil",{enumerable:!0,get:function(){return j1.nil}});Object.defineProperty(Nw,"getProperty",{enumerable:!0,get:function(){return j1.getProperty}});Object.defineProperty(Nw,"stringify",{enumerable:!0,get:function(){return j1.stringify}});Object.defineProperty(Nw,"regexpCode",{enumerable:!0,get:function(){return j1.regexpCode}});Object.defineProperty(Nw,"Name",{enumerable:!0,get:function(){return j1.Name}});var D$=P6();Object.defineProperty(Nw,"Scope",{enumerable:!0,get:function(){return D$.Scope}});Object.defineProperty(Nw,"ValueScope",{enumerable:!0,get:function(){return D$.ValueScope}});Object.defineProperty(Nw,"ValueScopeName",{enumerable:!0,get:function(){return D$.ValueScopeName}});Object.defineProperty(Nw,"varKinds",{enumerable:!0,get:function(){return D$.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 I1{optimizeNodes(){return this}optimizeNames(w,b){return this}}class BY extends I1{constructor(w,b,$){super();this.varKind=w,this.name=b,this.rhs=$}render({es5:w,_n:b}){let $=w?gw.varKinds.var:this.varKind,Q=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${Q};`+b}optimizeNames(w,b){if(!w[this.name.str])return;if(this.rhs)this.rhs=e1(this.rhs,w,b);return this}get names(){return this.rhs instanceof i._CodeOrName?this.rhs.names:{}}}class I6 extends I1{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=e1(this.rhs,w,b),this}get names(){let w=this.lhs instanceof i.Name?{}:{...this.lhs.names};return z$(w,this.rhs)}}class OY extends I6{constructor(w,b,$,Q){super(w,$,Q);this.op=b}render({_n:w}){return`${this.lhs} ${this.op}= ${this.rhs};`+w}}class MY extends I1{constructor(w){super();this.label=w,this.names={}}render({_n:w}){return`${this.label}:`+w}}class KY extends I1{constructor(w){super();this.label=w,this.names={}}render({_n:w}){return`break${this.label?` ${this.label}`:""};`+w}}class qY extends I1{constructor(w){super();this.error=w}render({_n:w}){return`throw ${this.error};`+w}get names(){return this.error.names}}class ZY extends I1{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=e1(this.code,w,b),this}get names(){return this.code instanceof i._CodeOrName?this.code.names:{}}}class U$ extends I1{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,Q=$.length;while(Q--){let W=$[Q];if(W.optimizeNames(w,b))continue;_A(w,W.names),$.splice(Q,1)}return $.length>0?this:void 0}get names(){return this.nodes.reduce((w,b)=>k1(w,b.names),{})}}class N1 extends U${render(w){return"{"+w._n+super.render(w)+"}"+w._n}}class PY extends U${}class n0 extends N1{}n0.kind="else";class Y1 extends N1{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 n0($):$}if(b){if(w===!1)return b instanceof Y1?b:b.nodes;if(this.nodes.length)return this;return new Y1(EY(w),b instanceof Y1?[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=e1(this.condition,w,b),this}get names(){let w=super.names;if(z$(w,this.condition),this.else)k1(w,this.else.names);return w}}Y1.kind="if";class s1 extends N1{}s1.kind="for";class VY extends s1{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=e1(this.iteration,w,b),this}get names(){return k1(super.names,this.iteration.names)}}class jY extends s1{constructor(w,b,$,Q){super();this.varKind=w,this.name=b,this.from=$,this.to=Q}render(w){let b=w.es5?gw.varKinds.var:this.varKind,{name:$,from:Q,to:W}=this;return`for(${b} ${$}=${Q}; ${$}<${W}; ${$}++)`+super.render(w)}get names(){let w=z$(super.names,this.from);return z$(w,this.to)}}class V6 extends s1{constructor(w,b,$,Q){super();this.loop=w,this.varKind=b,this.name=$,this.iterable=Q}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=e1(this.iterable,w,b),this}get names(){return k1(super.names,this.iterable.names)}}class Y$ extends N1{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)}}Y$.kind="func";class G$ extends U${render(w){return"return "+super.render(w)}}G$.kind="return";class IY extends N1{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 $,Q;return super.optimizeNames(w,b),($=this.catch)===null||$===void 0||$.optimizeNames(w,b),(Q=this.finally)===null||Q===void 0||Q.optimizeNames(w,b),this}get names(){let w=super.names;if(this.catch)k1(w,this.catch.names);if(this.finally)k1(w,this.finally.names);return w}}class J$ extends N1{constructor(w){super();this.error=w}render(w){return`catch(${this.error})`+super.render(w)}}J$.kind="catch";class H$ extends N1{render(w){return"finally"+super.render(w)}}H$.kind="finally";class NY{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 PY]}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,$,Q){let W=this._scope.toName(b);if($!==void 0&&Q)this._constants[W.str]=$;return this._leafNode(new BY(w,W,$)),W}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 I6(w,b,$))}add(w,b){return this._leafNode(new OY(w,Nw.operators.ADD,b))}code(w){if(typeof w=="function")w();else if(w!==i.nil)this._leafNode(new ZY(w));return this}object(...w){let b=["{"];for(let[$,Q]of w){if(b.length>1)b.push(",");if(b.push($),$!==Q||this.opts.es5)b.push(":"),(0,i.addCodeArg)(b,Q)}return b.push("}"),new i._Code(b)}if(w,b,$){if(this._blockNode(new Y1(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 Y1(w))}else(){return this._elseNode(new n0)}endIf(){return this._endBlockNode(Y1,n0)}_for(w,b){if(this._blockNode(w),b)this.code(b).endFor();return this}for(w,b){return this._for(new VY(w),b)}forRange(w,b,$,Q,W=this.opts.es5?gw.varKinds.var:gw.varKinds.let){let X=this._scope.toName(w);return this._for(new jY(W,X,b,$),()=>Q(X))}forOf(w,b,$,Q=gw.varKinds.const){let W=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`,(Y)=>{this.var(W,i._`${X}[${Y}]`),$(W)})}return this._for(new V6("of",Q,W,b),()=>$(W))}forIn(w,b,$,Q=this.opts.es5?gw.varKinds.var:gw.varKinds.const){if(this.opts.ownProperties)return this.forOf(w,i._`Object.keys(${b})`,$);let W=this._scope.toName(w);return this._for(new V6("in",Q,W,b),()=>$(W))}endFor(){return this._endBlockNode(s1)}label(w){return this._leafNode(new MY(w))}break(w){return this._leafNode(new KY(w))}return(w){let b=new G$;if(this._blockNode(b),this.code(w),b.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(G$)}try(w,b,$){if(!b&&!$)throw Error('CodeGen: "try" without "catch" and "finally"');let Q=new IY;if(this._blockNode(Q),this.code(w),b){let W=this.name("e");this._currNode=Q.catch=new J$(W),b(W)}if($)this._currNode=Q.finally=new H$,this.code($);return this._endBlockNode(J$,H$)}throw(w){return this._leafNode(new qY(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,$,Q){if(this._blockNode(new Y$(w,b,$)),Q)this.code(Q).endFunc();return this}endFunc(){return this._endBlockNode(Y$)}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 Y1))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=NY;function k1(w,b){for(let $ in b)w[$]=(w[$]||0)+(b[$]||0);return w}function z$(w,b){return b instanceof i._CodeOrName?k1(w,b.names):w}function e1(w,b,$){if(w instanceof i.Name)return Q(w);if(!W(w))return w;return new i._Code(w._items.reduce((X,Y)=>{if(Y instanceof i.Name)Y=Q(Y);if(Y instanceof i._Code)X.push(...Y._items);else X.push(Y);return X},[]));function Q(X){let Y=$[X.str];if(Y===void 0||b[X.str]!==1)return X;return delete b[X.str],Y}function W(X){return X instanceof i._Code&&X._items.some((Y)=>Y instanceof i.Name&&b[Y.str]===1&&$[Y.str]!==void 0)}}function _A(w,b){for(let $ in b)w[$]=(w[$]||0)-(b[$]||0)}function EY(w){return typeof w=="boolean"||typeof w=="number"||w===null?!w:i._`!${j6(w)}`}Nw.not=EY;var kA=TY(Nw.operators.AND);function xA(...w){return w.reduce(kA)}Nw.and=xA;var hA=TY(Nw.operators.OR);function yA(...w){return w.reduce(hA)}Nw.or=yA;function TY(w){return(b,$)=>b===i.nil?$:$===i.nil?b:i._`${j6(b)} ${w} ${j6($)}`}function j6(w){return w instanceof i.Name?w:i._`(${w})`}});var d=I((yY)=>{Object.defineProperty(yY,"__esModule",{value:!0});yY.checkStrictMode=yY.getErrorPath=yY.Type=yY.useFunc=yY.setEvaluated=yY.evaluatedPropsToName=yY.mergeEvaluated=yY.eachItem=yY.unescapeJsonPointer=yY.escapeJsonPointer=yY.escapeFragment=yY.unescapeFragment=yY.schemaRefOrVal=yY.schemaHasRulesButRef=yY.schemaHasRules=yY.checkUnknownRules=yY.alwaysValidSchema=yY.toHash=void 0;var s=f(),mA=i0();function gA(w){let b={};for(let $ of w)b[$]=!0;return b}yY.toHash=gA;function lA(w,b){if(typeof b=="boolean")return b;if(Object.keys(b).length===0)return!0;return vY(w,b),!_Y(b,w.self.RULES.all)}yY.alwaysValidSchema=lA;function vY(w,b=w.schema){let{opts:$,self:Q}=w;if(!$.strictSchema)return;if(typeof b==="boolean")return;let W=Q.RULES.keywords;for(let X in b)if(!W[X])hY(w,`unknown keyword: "${X}"`)}yY.checkUnknownRules=vY;function _Y(w,b){if(typeof w=="boolean")return!w;for(let $ in w)if(b[$])return!0;return!1}yY.schemaHasRules=_Y;function iA(w,b){if(typeof w=="boolean")return!w;for(let $ in w)if($!=="$ref"&&b.all[$])return!0;return!1}yY.schemaHasRulesButRef=iA;function nA({topSchemaRef:w,schemaPath:b},$,Q,W){if(!W){if(typeof $=="number"||typeof $=="boolean")return $;if(typeof $=="string")return s._`${$}`}return s._`${w}${b}${(0,s.getProperty)(Q)}`}yY.schemaRefOrVal=nA;function pA(w){return kY(decodeURIComponent(w))}yY.unescapeFragment=pA;function oA(w){return encodeURIComponent(E6(w))}yY.escapeFragment=oA;function E6(w){if(typeof w=="number")return`${w}`;return w.replace(/~/g,"~0").replace(/\//g,"~1")}yY.escapeJsonPointer=E6;function kY(w){return w.replace(/~1/g,"/").replace(/~0/g,"~")}yY.unescapeJsonPointer=kY;function dA(w,b){if(Array.isArray(w))for(let $ of w)b($);else b(w)}yY.eachItem=dA;function SY({mergeNames:w,mergeToName:b,mergeValues:$,resultToName:Q}){return(W,X,Y,G)=>{let J=Y===void 0?X:Y instanceof s.Name?(X instanceof s.Name?w(W,X,Y):b(W,X,Y),Y):X instanceof s.Name?(b(W,Y,X),X):$(X,Y);return G===s.Name&&!(J instanceof s.Name)?Q(W,J):J}}yY.mergeEvaluated={props:SY({mergeNames:(w,b,$)=>w.if(s._`${$} !== true && ${b} !== undefined`,()=>{w.if(s._`${b} === true`,()=>w.assign($,!0),()=>w.assign($,s._`${$} || {}`).code(s._`Object.assign(${$}, ${b})`))}),mergeToName:(w,b,$)=>w.if(s._`${$} !== true`,()=>{if(b===!0)w.assign($,!0);else w.assign($,s._`${$} || {}`),T6(w,$,b)}),mergeValues:(w,b)=>w===!0?!0:{...w,...b},resultToName:xY}),items:SY({mergeNames:(w,b,$)=>w.if(s._`${$} !== true && ${b} !== undefined`,()=>w.assign($,s._`${b} === true ? true : ${$} > ${b} ? ${$} : ${b}`)),mergeToName:(w,b,$)=>w.if(s._`${$} !== true`,()=>w.assign($,b===!0?!0:s._`${$} > ${b} ? ${$} : ${b}`)),mergeValues:(w,b)=>w===!0?!0:Math.max(w,b),resultToName:(w,b)=>w.var("items",b)})};function xY(w,b){if(b===!0)return w.var("props",!0);let $=w.var("props",s._`{}`);if(b!==void 0)T6(w,$,b);return $}yY.evaluatedPropsToName=xY;function T6(w,b,$){Object.keys($).forEach((Q)=>w.assign(s._`${b}${(0,s.getProperty)(Q)}`,!0))}yY.setEvaluated=T6;var CY={};function tA(w,b){return w.scopeValue("func",{ref:b,code:CY[b.code]||(CY[b.code]=new mA._Code(b.code))})}yY.useFunc=tA;var N6;(function(w){w[w.Num=0]="Num",w[w.Str=1]="Str"})(N6||(yY.Type=N6={}));function rA(w,b,$){if(w instanceof s.Name){let Q=b===N6.Num;return $?Q?s._`"[" + ${w} + "]"`:s._`"['" + ${w} + "']"`:Q?s._`"/" + ${w}`:s._`"/" + ${w}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return $?(0,s.getProperty)(w).toString():"/"+E6(w)}yY.getErrorPath=rA;function hY(w,b,$=w.opts.strictSchema){if(!$)return;if(b=`strict mode: ${b}`,$===!0)throw Error(b);w.self.logger.warn(b)}yY.checkStrictMode=hY});var G1=I((fY)=>{Object.defineProperty(fY,"__esModule",{value:!0});var qw=f(),LL={data:new qw.Name("data"),valCxt:new qw.Name("valCxt"),instancePath:new qw.Name("instancePath"),parentData:new qw.Name("parentData"),parentDataProperty:new qw.Name("parentDataProperty"),rootData:new qw.Name("rootData"),dynamicAnchors:new qw.Name("dynamicAnchors"),vErrors:new qw.Name("vErrors"),errors:new qw.Name("errors"),this:new qw.Name("this"),self:new qw.Name("self"),scope:new qw.Name("scope"),json:new qw.Name("json"),jsonPos:new qw.Name("jsonPos"),jsonLen:new qw.Name("jsonLen"),jsonPart:new qw.Name("jsonPart")};fY.default=LL});var p0=I((lY)=>{Object.defineProperty(lY,"__esModule",{value:!0});lY.extendErrors=lY.resetErrorsCount=lY.reportExtraError=lY.reportError=lY.keyword$DataError=lY.keywordError=void 0;var n=f(),L$=d(),Pw=G1();lY.keywordError={message:({keyword:w})=>n.str`must pass "${w}" keyword validation`};lY.keyword$DataError={message:({keyword:w,schemaType:b})=>b?n.str`"${w}" keyword must be ${b} ($data)`:n.str`"${w}" keyword is invalid ($data)`};function BL(w,b=lY.keywordError,$,Q){let{it:W}=w,{gen:X,compositeRule:Y,allErrors:G}=W,J=gY(w,b,$);if(Q!==null&&Q!==void 0?Q:Y||G)cY(X,J);else mY(W,n._`[${J}]`)}lY.reportError=BL;function OL(w,b=lY.keywordError,$){let{it:Q}=w,{gen:W,compositeRule:X,allErrors:Y}=Q,G=gY(w,b,$);if(cY(W,G),!(X||Y))mY(Q,Pw.default.vErrors)}lY.reportExtraError=OL;function ML(w,b){w.assign(Pw.default.errors,b),w.if(n._`${Pw.default.vErrors} !== null`,()=>w.if(b,()=>w.assign(n._`${Pw.default.vErrors}.length`,b),()=>w.assign(Pw.default.vErrors,null)))}lY.resetErrorsCount=ML;function KL({gen:w,keyword:b,schemaValue:$,data:Q,errsCount:W,it:X}){if(W===void 0)throw Error("ajv implementation error");let Y=w.name("err");w.forRange("i",W,Pw.default.errors,(G)=>{if(w.const(Y,n._`${Pw.default.vErrors}[${G}]`),w.if(n._`${Y}.instancePath === undefined`,()=>w.assign(n._`${Y}.instancePath`,(0,n.strConcat)(Pw.default.instancePath,X.errorPath))),w.assign(n._`${Y}.schemaPath`,n.str`${X.errSchemaPath}/${b}`),X.opts.verbose)w.assign(n._`${Y}.schema`,$),w.assign(n._`${Y}.data`,Q)})}lY.extendErrors=KL;function cY(w,b){let $=w.const("err",b);w.if(n._`${Pw.default.vErrors} === null`,()=>w.assign(Pw.default.vErrors,n._`[${$}]`),n._`${Pw.default.vErrors}.push(${$})`),w.code(n._`${Pw.default.errors}++`)}function mY(w,b){let{gen:$,validateName:Q,schemaEnv:W}=w;if(W.$async)$.throw(n._`new ${w.ValidationError}(${b})`);else $.assign(n._`${Q}.errors`,b),$.return(!1)}var x1={keyword:new n.Name("keyword"),schemaPath:new n.Name("schemaPath"),params:new n.Name("params"),propertyName:new n.Name("propertyName"),message:new n.Name("message"),schema:new n.Name("schema"),parentSchema:new n.Name("parentSchema")};function gY(w,b,$){let{createErrors:Q}=w.it;if(Q===!1)return n._`{}`;return qL(w,b,$)}function qL(w,b,$={}){let{gen:Q,it:W}=w,X=[ZL(W,$),PL(w,$)];return VL(w,b,X),Q.object(...X)}function ZL({errorPath:w},{instancePath:b}){let $=b?n.str`${w}${(0,L$.getErrorPath)(b,L$.Type.Str)}`:w;return[Pw.default.instancePath,(0,n.strConcat)(Pw.default.instancePath,$)]}function PL({keyword:w,it:{errSchemaPath:b}},{schemaPath:$,parentSchema:Q}){let W=Q?b:n.str`${b}/${w}`;if($)W=n.str`${W}${(0,L$.getErrorPath)($,L$.Type.Str)}`;return[x1.schemaPath,W]}function VL(w,{params:b,message:$},Q){let{keyword:W,data:X,schemaValue:Y,it:G}=w,{opts:J,propertyName:H,topSchemaRef:z,schemaPath:D}=G;if(Q.push([x1.keyword,W],[x1.params,typeof b=="function"?b(w):b||n._`{}`]),J.messages)Q.push([x1.message,typeof $=="function"?$(w):$]);if(J.verbose)Q.push([x1.schema,Y],[x1.parentSchema,n._`${z}${D}`],[Pw.default.data,X]);if(H)Q.push([x1.propertyName,H])}});var dY=I((pY)=>{Object.defineProperty(pY,"__esModule",{value:!0});pY.boolOrEmptySchema=pY.topBoolOrEmptySchema=void 0;var TL=p0(),RL=f(),SL=G1(),CL={message:"boolean schema is false"};function vL(w){let{gen:b,schema:$,validateName:Q}=w;if($===!1)nY(w,!1);else if(typeof $=="object"&&$.$async===!0)b.return(SL.default.data);else b.assign(RL._`${Q}.errors`,null),b.return(!0)}pY.topBoolOrEmptySchema=vL;function _L(w,b){let{gen:$,schema:Q}=w;if(Q===!1)$.var(b,!1),nY(w);else $.var(b,!0)}pY.boolOrEmptySchema=_L;function nY(w,b){let{gen:$,data:Q}=w,W={gen:$,keyword:"false schema",data:Q,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:w};(0,TL.reportError)(W,CL,void 0,b)}});var S6=I((tY)=>{Object.defineProperty(tY,"__esModule",{value:!0});tY.getRules=tY.isJSONType=void 0;var xL=["string","number","integer","boolean","null","object","array"],hL=new Set(xL);function yL(w){return typeof w=="string"&&hL.has(w)}tY.isJSONType=yL;function uL(){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:{}}}tY.getRules=uL});var C6=I((aY)=>{Object.defineProperty(aY,"__esModule",{value:!0});aY.shouldUseRule=aY.shouldUseGroup=aY.schemaHasRulesForType=void 0;function cL({schema:w,self:b},$){let Q=b.RULES.types[$];return Q&&Q!==!0&&sY(w,Q)}aY.schemaHasRulesForType=cL;function sY(w,b){return b.rules.some(($)=>eY(w,$))}aY.shouldUseGroup=sY;function eY(w,b){var $;return w[b.keyword]!==void 0||(($=b.definition.implements)===null||$===void 0?void 0:$.some((Q)=>w[Q]!==void 0))}aY.shouldUseRule=eY});var o0=I((WG)=>{Object.defineProperty(WG,"__esModule",{value:!0});WG.reportTypeError=WG.checkDataTypes=WG.checkDataType=WG.coerceAndCheckDataType=WG.getJSONTypes=WG.getSchemaTypes=WG.DataType=void 0;var lL=S6(),iL=C6(),nL=p0(),y=f(),bG=d(),a1;(function(w){w[w.Correct=0]="Correct",w[w.Wrong=1]="Wrong"})(a1||(WG.DataType=a1={}));function pL(w){let b=$G(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}WG.getSchemaTypes=pL;function $G(w){let b=Array.isArray(w)?w:w?[w]:[];if(b.every(lL.isJSONType))return b;throw Error("type must be JSONType or JSONType[]: "+b.join(","))}WG.getJSONTypes=$G;function oL(w,b){let{gen:$,data:Q,opts:W}=w,X=dL(b,W.coerceTypes),Y=b.length>0&&!(X.length===0&&b.length===1&&(0,iL.schemaHasRulesForType)(w,b[0]));if(Y){let G=_6(b,Q,W.strictNumbers,a1.Wrong);$.if(G,()=>{if(X.length)tL(w,b,X);else k6(w)})}return Y}WG.coerceAndCheckDataType=oL;var QG=new Set(["string","number","integer","boolean","null"]);function dL(w,b){return b?w.filter(($)=>QG.has($)||b==="array"&&$==="array"):[]}function tL(w,b,$){let{gen:Q,data:W,opts:X}=w,Y=Q.let("dataType",y._`typeof ${W}`),G=Q.let("coerced",y._`undefined`);if(X.coerceTypes==="array")Q.if(y._`${Y} == 'object' && Array.isArray(${W}) && ${W}.length == 1`,()=>Q.assign(W,y._`${W}[0]`).assign(Y,y._`typeof ${W}`).if(_6(b,W,X.strictNumbers),()=>Q.assign(G,W)));Q.if(y._`${G} !== undefined`);for(let H of $)if(QG.has(H)||H==="array"&&X.coerceTypes==="array")J(H);Q.else(),k6(w),Q.endIf(),Q.if(y._`${G} !== undefined`,()=>{Q.assign(W,G),rL(w,G)});function J(H){switch(H){case"string":Q.elseIf(y._`${Y} == "number" || ${Y} == "boolean"`).assign(G,y._`"" + ${W}`).elseIf(y._`${W} === null`).assign(G,y._`""`);return;case"number":Q.elseIf(y._`${Y} == "boolean" || ${W} === null
|
|
4
|
+
|| (${Y} == "string" && ${W} && ${W} == +${W})`).assign(G,y._`+${W}`);return;case"integer":Q.elseIf(y._`${Y} === "boolean" || ${W} === null
|
|
5
|
+
|| (${Y} === "string" && ${W} && ${W} == +${W} && !(${W} % 1))`).assign(G,y._`+${W}`);return;case"boolean":Q.elseIf(y._`${W} === "false" || ${W} === 0 || ${W} === null`).assign(G,!1).elseIf(y._`${W} === "true" || ${W} === 1`).assign(G,!0);return;case"null":Q.elseIf(y._`${W} === "" || ${W} === 0 || ${W} === false`),Q.assign(G,null);return;case"array":Q.elseIf(y._`${Y} === "string" || ${Y} === "number"
|
|
6
|
+
|| ${Y} === "boolean" || ${W} === null`).assign(G,y._`[${W}]`)}}}function rL({gen:w,parentData:b,parentDataProperty:$},Q){w.if(y._`${b} !== undefined`,()=>w.assign(y._`${b}[${$}]`,Q))}function v6(w,b,$,Q=a1.Correct){let W=Q===a1.Correct?y.operators.EQ:y.operators.NEQ,X;switch(w){case"null":return y._`${b} ${W} null`;case"array":X=y._`Array.isArray(${b})`;break;case"object":X=y._`${b} && typeof ${b} == "object" && !Array.isArray(${b})`;break;case"integer":X=Y(y._`!(${b} % 1) && !isNaN(${b})`);break;case"number":X=Y();break;default:return y._`typeof ${b} ${W} ${w}`}return Q===a1.Correct?X:(0,y.not)(X);function Y(G=y.nil){return(0,y.and)(y._`typeof ${b} == "number"`,G,$?y._`isFinite(${b})`:y.nil)}}WG.checkDataType=v6;function _6(w,b,$,Q){if(w.length===1)return v6(w[0],b,$,Q);let W,X=(0,bG.toHash)(w);if(X.array&&X.object){let Y=y._`typeof ${b} != "object"`;W=X.null?Y:y._`!${b} || ${Y}`,delete X.null,delete X.array,delete X.object}else W=y.nil;if(X.number)delete X.integer;for(let Y in X)W=(0,y.and)(W,v6(Y,b,$,Q));return W}WG.checkDataTypes=_6;var sL={message:({schema:w})=>`must be ${w}`,params:({schema:w,schemaValue:b})=>typeof w=="string"?y._`{type: ${w}}`:y._`{type: ${b}}`};function k6(w){let b=eL(w);(0,nL.reportError)(b,sL)}WG.reportTypeError=k6;function eL(w){let{gen:b,data:$,schema:Q}=w,W=(0,bG.schemaRefOrVal)(w,Q,"type");return{gen:b,keyword:"type",data:$,schema:Q.type,schemaCode:W,schemaValue:W,parentSchema:Q,params:{},it:w}}});var HG=I((GG)=>{Object.defineProperty(GG,"__esModule",{value:!0});GG.assignDefaults=void 0;var w0=f(),XF=d();function YF(w,b){let{properties:$,items:Q}=w.schema;if(b==="object"&&$)for(let W in $)YG(w,W,$[W].default);else if(b==="array"&&Array.isArray(Q))Q.forEach((W,X)=>YG(w,X,W.default))}GG.assignDefaults=YF;function YG(w,b,$){let{gen:Q,compositeRule:W,data:X,opts:Y}=w;if($===void 0)return;let G=w0._`${X}${(0,w0.getProperty)(b)}`;if(W){(0,XF.checkStrictMode)(w,`default is ignored for: ${G}`);return}let J=w0._`${G} === undefined`;if(Y.useDefaults==="empty")J=w0._`${J} || ${G} === null || ${G} === ""`;Q.if(J,w0._`${G} = ${(0,w0.stringify)($)}`)}});var hw=I((UG)=>{Object.defineProperty(UG,"__esModule",{value:!0});UG.validateUnion=UG.validateArray=UG.usePattern=UG.callValidateCode=UG.schemaProperties=UG.allSchemaProperties=UG.noPropertyInData=UG.propertyInData=UG.isOwnProperty=UG.hasPropFunc=UG.reportMissingProp=UG.checkMissingProp=UG.checkReportMissingProp=void 0;var bw=f(),x6=d(),E1=G1(),GF=d();function JF(w,b){let{gen:$,data:Q,it:W}=w;$.if(y6($,Q,b,W.opts.ownProperties),()=>{w.setParams({missingProperty:bw._`${b}`},!0),w.error()})}UG.checkReportMissingProp=JF;function HF({gen:w,data:b,it:{opts:$}},Q,W){return(0,bw.or)(...Q.map((X)=>(0,bw.and)(y6(w,b,X,$.ownProperties),bw._`${W} = ${X}`)))}UG.checkMissingProp=HF;function zF(w,b){w.setParams({missingProperty:b},!0),w.error()}UG.reportMissingProp=zF;function zG(w){return w.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:bw._`Object.prototype.hasOwnProperty`})}UG.hasPropFunc=zG;function h6(w,b,$){return bw._`${zG(w)}.call(${b}, ${$})`}UG.isOwnProperty=h6;function DF(w,b,$,Q){let W=bw._`${b}${(0,bw.getProperty)($)} !== undefined`;return Q?bw._`${W} && ${h6(w,b,$)}`:W}UG.propertyInData=DF;function y6(w,b,$,Q){let W=bw._`${b}${(0,bw.getProperty)($)} === undefined`;return Q?(0,bw.or)(W,(0,bw.not)(h6(w,b,$))):W}UG.noPropertyInData=y6;function DG(w){return w?Object.keys(w).filter((b)=>b!=="__proto__"):[]}UG.allSchemaProperties=DG;function UF(w,b){return DG(b).filter(($)=>!(0,x6.alwaysValidSchema)(w,b[$]))}UG.schemaProperties=UF;function AF({schemaCode:w,data:b,it:{gen:$,topSchemaRef:Q,schemaPath:W,errorPath:X},it:Y},G,J,H){let z=H?bw._`${w}, ${b}, ${Q}${W}`:b,D=[[E1.default.instancePath,(0,bw.strConcat)(E1.default.instancePath,X)],[E1.default.parentData,Y.parentData],[E1.default.parentDataProperty,Y.parentDataProperty],[E1.default.rootData,E1.default.rootData]];if(Y.opts.dynamicRef)D.push([E1.default.dynamicAnchors,E1.default.dynamicAnchors]);let A=bw._`${z}, ${$.object(...D)}`;return J!==bw.nil?bw._`${G}.call(${J}, ${A})`:bw._`${G}(${A})`}UG.callValidateCode=AF;var LF=bw._`new RegExp`;function FF({gen:w,it:{opts:b}},$){let Q=b.unicodeRegExp?"u":"",{regExp:W}=b.code,X=W($,Q);return w.scopeValue("pattern",{key:X.toString(),ref:X,code:bw._`${W.code==="new RegExp"?LF:(0,GF.useFunc)(w,W)}(${$}, ${Q})`})}UG.usePattern=FF;function BF(w){let{gen:b,data:$,keyword:Q,it:W}=w,X=b.name("valid");if(W.allErrors){let G=b.let("valid",!0);return Y(()=>b.assign(G,!1)),G}return b.var(X,!0),Y(()=>b.break()),X;function Y(G){let J=b.const("len",bw._`${$}.length`);b.forRange("i",0,J,(H)=>{w.subschema({keyword:Q,dataProp:H,dataPropType:x6.Type.Num},X),b.if((0,bw.not)(X),G)})}}UG.validateArray=BF;function OF(w){let{gen:b,schema:$,keyword:Q,it:W}=w;if(!Array.isArray($))throw Error("ajv implementation error");if($.some((J)=>(0,x6.alwaysValidSchema)(W,J))&&!W.opts.unevaluated)return;let Y=b.let("valid",!1),G=b.name("_valid");b.block(()=>$.forEach((J,H)=>{let z=w.subschema({keyword:Q,schemaProp:H,compositeRule:!0},G);if(b.assign(Y,bw._`${Y} || ${G}`),!w.mergeValidEvaluated(z,G))b.if((0,bw.not)(Y))})),w.result(Y,()=>w.reset(),()=>w.error(!0))}UG.validateUnion=OF});var MG=I((BG)=>{Object.defineProperty(BG,"__esModule",{value:!0});BG.validateKeywordUsage=BG.validSchemaType=BG.funcKeywordCode=BG.macroKeywordCode=void 0;var Vw=f(),h1=G1(),SF=hw(),CF=p0();function vF(w,b){let{gen:$,keyword:Q,schema:W,parentSchema:X,it:Y}=w,G=b.macro.call(Y.self,W,X,Y),J=FG($,Q,G);if(Y.opts.validateSchema!==!1)Y.self.validateSchema(G,!0);let H=$.name("valid");w.subschema({schema:G,schemaPath:Vw.nil,errSchemaPath:`${Y.errSchemaPath}/${Q}`,topSchemaRef:J,compositeRule:!0},H),w.pass(H,()=>w.error(!0))}BG.macroKeywordCode=vF;function _F(w,b){var $;let{gen:Q,keyword:W,schema:X,parentSchema:Y,$data:G,it:J}=w;xF(J,b);let H=!G&&b.compile?b.compile.call(J.self,X,Y,J):b.validate,z=FG(Q,W,H),D=Q.let("valid");w.block$data(D,A),w.ok(($=b.valid)!==null&&$!==void 0?$:D);function A(){if(b.errors===!1){if(K(),b.modifying)LG(w);j(()=>w.error())}else{let V=b.async?L():O();if(b.modifying)LG(w);j(()=>kF(w,V))}}function L(){let V=Q.let("ruleErrs",null);return Q.try(()=>K(Vw._`await `),(_)=>Q.assign(D,!1).if(Vw._`${_} instanceof ${J.ValidationError}`,()=>Q.assign(V,Vw._`${_}.errors`),()=>Q.throw(_))),V}function O(){let V=Vw._`${z}.errors`;return Q.assign(V,null),K(Vw.nil),V}function K(V=b.async?Vw._`await `:Vw.nil){let _=J.opts.passContext?h1.default.this:h1.default.self,R=!(("compile"in b)&&!G||b.schema===!1);Q.assign(D,Vw._`${V}${(0,SF.callValidateCode)(w,z,_,R)}`,b.modifying)}function j(V){var _;Q.if((0,Vw.not)((_=b.valid)!==null&&_!==void 0?_:D),V)}}BG.funcKeywordCode=_F;function LG(w){let{gen:b,data:$,it:Q}=w;b.if(Q.parentData,()=>b.assign($,Vw._`${Q.parentData}[${Q.parentDataProperty}]`))}function kF(w,b){let{gen:$}=w;$.if(Vw._`Array.isArray(${b})`,()=>{$.assign(h1.default.vErrors,Vw._`${h1.default.vErrors} === null ? ${b} : ${h1.default.vErrors}.concat(${b})`).assign(h1.default.errors,Vw._`${h1.default.vErrors}.length`),(0,CF.extendErrors)(w)},()=>w.error())}function xF({schemaEnv:w},b){if(b.async&&!w.$async)throw Error("async keyword in sync schema")}function FG(w,b,$){if($===void 0)throw Error(`keyword "${b}" failed to compile`);return w.scopeValue("keyword",typeof $=="function"?{ref:$}:{ref:$,code:(0,Vw.stringify)($)})}function hF(w,b,$=!1){return!b.length||b.some((Q)=>Q==="array"?Array.isArray(w):Q==="object"?w&&typeof w=="object"&&!Array.isArray(w):typeof w==Q||$&&typeof w>"u")}BG.validSchemaType=hF;function yF({schema:w,opts:b,self:$,errSchemaPath:Q},W,X){if(Array.isArray(W.keyword)?!W.keyword.includes(X):W.keyword!==X)throw Error("ajv implementation error");let Y=W.dependencies;if(Y===null||Y===void 0?void 0:Y.some((G)=>!Object.prototype.hasOwnProperty.call(w,G)))throw Error(`parent schema must have dependencies of ${X}: ${Y.join(",")}`);if(W.validateSchema){if(!W.validateSchema(w[X])){let J=`keyword "${X}" value is invalid at path "${Q}": `+$.errorsText(W.validateSchema.errors);if(b.validateSchema==="log")$.logger.error(J);else throw Error(J)}}}BG.validateKeywordUsage=yF});var PG=I((qG)=>{Object.defineProperty(qG,"__esModule",{value:!0});qG.extendSubschemaMode=qG.extendSubschemaData=qG.getSubschema=void 0;var sw=f(),KG=d();function mF(w,{keyword:b,schemaProp:$,schema:Q,schemaPath:W,errSchemaPath:X,topSchemaRef:Y}){if(b!==void 0&&Q!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(b!==void 0){let G=w.schema[b];return $===void 0?{schema:G,schemaPath:sw._`${w.schemaPath}${(0,sw.getProperty)(b)}`,errSchemaPath:`${w.errSchemaPath}/${b}`}:{schema:G[$],schemaPath:sw._`${w.schemaPath}${(0,sw.getProperty)(b)}${(0,sw.getProperty)($)}`,errSchemaPath:`${w.errSchemaPath}/${b}/${(0,KG.escapeFragment)($)}`}}if(Q!==void 0){if(W===void 0||X===void 0||Y===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:Q,schemaPath:W,topSchemaRef:Y,errSchemaPath:X}}throw Error('either "keyword" or "schema" must be passed')}qG.getSubschema=mF;function gF(w,b,{dataProp:$,dataPropType:Q,data:W,dataTypes:X,propertyName:Y}){if(W!==void 0&&$!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:G}=b;if($!==void 0){let{errorPath:H,dataPathArr:z,opts:D}=b,A=G.let("data",sw._`${b.data}${(0,sw.getProperty)($)}`,!0);J(A),w.errorPath=sw.str`${H}${(0,KG.getErrorPath)($,Q,D.jsPropertySyntax)}`,w.parentDataProperty=sw._`${$}`,w.dataPathArr=[...z,w.parentDataProperty]}if(W!==void 0){let H=W instanceof sw.Name?W:G.let("data",W,!0);if(J(H),Y!==void 0)w.propertyName=Y}if(X)w.dataTypes=X;function J(H){w.data=H,w.dataLevel=b.dataLevel+1,w.dataTypes=[],b.definedProperties=new Set,w.parentData=b.data,w.dataNames=[...b.dataNames,H]}}qG.extendSubschemaData=gF;function lF(w,{jtdDiscriminator:b,jtdMetadata:$,compositeRule:Q,createErrors:W,allErrors:X}){if(Q!==void 0)w.compositeRule=Q;if(W!==void 0)w.createErrors=W;if(X!==void 0)w.allErrors=X;w.jtdDiscriminator=b,w.jtdMetadata=$}qG.extendSubschemaMode=lF});var u6=I((iT,VG)=>{VG.exports=function w(b,$){if(b===$)return!0;if(b&&$&&typeof b=="object"&&typeof $=="object"){if(b.constructor!==$.constructor)return!1;var Q,W,X;if(Array.isArray(b)){if(Q=b.length,Q!=$.length)return!1;for(W=Q;W--!==0;)if(!w(b[W],$[W]))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),Q=X.length,Q!==Object.keys($).length)return!1;for(W=Q;W--!==0;)if(!Object.prototype.hasOwnProperty.call($,X[W]))return!1;for(W=Q;W--!==0;){var Y=X[W];if(!w(b[Y],$[Y]))return!1}return!0}return b!==b&&$!==$}});var IG=I((nT,jG)=>{var T1=jG.exports=function(w,b,$){if(typeof b=="function")$=b,b={};$=b.cb||$;var Q=typeof $=="function"?$:$.pre||function(){},W=$.post||function(){};F$(b,Q,W,w,"",w)};T1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};T1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};T1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};T1.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 F$(w,b,$,Q,W,X,Y,G,J,H){if(Q&&typeof Q=="object"&&!Array.isArray(Q)){b(Q,W,X,Y,G,J,H);for(var z in Q){var D=Q[z];if(Array.isArray(D)){if(z in T1.arrayKeywords)for(var A=0;A<D.length;A++)F$(w,b,$,D[A],W+"/"+z+"/"+A,X,W,z,Q,A)}else if(z in T1.propsKeywords){if(D&&typeof D=="object")for(var L in D)F$(w,b,$,D[L],W+"/"+z+"/"+pF(L),X,W,z,Q,L)}else if(z in T1.keywords||w.allKeys&&!(z in T1.skipKeywords))F$(w,b,$,D,W+"/"+z,X,W,z,Q)}$(Q,W,X,Y,G,J,H)}}function pF(w){return w.replace(/~/g,"~0").replace(/\//g,"~1")}});var d0=I((RG)=>{Object.defineProperty(RG,"__esModule",{value:!0});RG.getSchemaRefs=RG.resolveUrl=RG.normalizeId=RG._getFullPath=RG.getFullPath=RG.inlineRef=void 0;var oF=d(),dF=u6(),tF=IG(),rF=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function sF(w,b=!0){if(typeof w=="boolean")return!0;if(b===!0)return!f6(w);if(!b)return!1;return NG(w)<=b}RG.inlineRef=sF;var eF=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function f6(w){for(let b in w){if(eF.has(b))return!0;let $=w[b];if(Array.isArray($)&&$.some(f6))return!0;if(typeof $=="object"&&f6($))return!0}return!1}function NG(w){let b=0;for(let $ in w){if($==="$ref")return 1/0;if(b++,rF.has($))continue;if(typeof w[$]=="object")(0,oF.eachItem)(w[$],(Q)=>b+=NG(Q));if(b===1/0)return 1/0}return b}function EG(w,b="",$){if($!==!1)b=b0(b);let Q=w.parse(b);return TG(w,Q)}RG.getFullPath=EG;function TG(w,b){return w.serialize(b).split("#")[0]+"#"}RG._getFullPath=TG;var aF=/#\/?$/;function b0(w){return w?w.replace(aF,""):""}RG.normalizeId=b0;function wB(w,b,$){return $=b0($),w.resolve(b,$)}RG.resolveUrl=wB;var bB=/^[a-z_][-a-z0-9._]*$/i;function $B(w,b){if(typeof w=="boolean")return{};let{schemaId:$,uriResolver:Q}=this.opts,W=b0(w[$]||b),X={"":W},Y=EG(Q,W,!1),G={},J=new Set;return tF(w,{allKeys:!0},(D,A,L,O)=>{if(O===void 0)return;let K=Y+A,j=X[O];if(typeof D[$]=="string")j=V.call(this,D[$]);_.call(this,D.$anchor),_.call(this,D.$dynamicAnchor),X[A]=j;function V(R){let m=this.opts.uriResolver.resolve;if(R=b0(j?m(j,R):R),J.has(R))throw z(R);J.add(R);let k=this.refs[R];if(typeof k=="string")k=this.refs[k];if(typeof k=="object")H(D,k.schema,R);else if(R!==b0(K))if(R[0]==="#")H(D,G[R],R),G[R]=D;else this.refs[R]=K;return R}function _(R){if(typeof R=="string"){if(!bB.test(R))throw Error(`invalid anchor "${R}"`);V.call(this,`#${R}`)}}}),G;function H(D,A,L){if(A!==void 0&&!dF(D,A))throw z(L)}function z(D){return Error(`reference "${D}" resolves to more than one schema`)}}RG.getSchemaRefs=$B});var s0=I((nG)=>{Object.defineProperty(nG,"__esModule",{value:!0});nG.getData=nG.KeywordCxt=nG.validateFunctionCode=void 0;var xG=dY(),CG=o0(),m6=C6(),B$=o0(),JB=HG(),r0=MG(),c6=PG(),T=f(),x=G1(),HB=d0(),J1=d(),t0=p0();function zB(w){if(uG(w)){if(fG(w),yG(w)){AB(w);return}}hG(w,()=>(0,xG.topBoolOrEmptySchema)(w))}nG.validateFunctionCode=zB;function hG({gen:w,validateName:b,schema:$,schemaEnv:Q,opts:W},X){if(W.code.es5)w.func(b,T._`${x.default.data}, ${x.default.valCxt}`,Q.$async,()=>{w.code(T._`"use strict"; ${vG($,W)}`),UB(w,W),w.code(X)});else w.func(b,T._`${x.default.data}, ${DB(W)}`,Q.$async,()=>w.code(vG($,W)).code(X))}function DB(w){return T._`{${x.default.instancePath}="", ${x.default.parentData}, ${x.default.parentDataProperty}, ${x.default.rootData}=${x.default.data}${w.dynamicRef?T._`, ${x.default.dynamicAnchors}={}`:T.nil}}={}`}function UB(w,b){w.if(x.default.valCxt,()=>{if(w.var(x.default.instancePath,T._`${x.default.valCxt}.${x.default.instancePath}`),w.var(x.default.parentData,T._`${x.default.valCxt}.${x.default.parentData}`),w.var(x.default.parentDataProperty,T._`${x.default.valCxt}.${x.default.parentDataProperty}`),w.var(x.default.rootData,T._`${x.default.valCxt}.${x.default.rootData}`),b.dynamicRef)w.var(x.default.dynamicAnchors,T._`${x.default.valCxt}.${x.default.dynamicAnchors}`)},()=>{if(w.var(x.default.instancePath,T._`""`),w.var(x.default.parentData,T._`undefined`),w.var(x.default.parentDataProperty,T._`undefined`),w.var(x.default.rootData,x.default.data),b.dynamicRef)w.var(x.default.dynamicAnchors,T._`{}`)})}function AB(w){let{schema:b,opts:$,gen:Q}=w;hG(w,()=>{if($.$comment&&b.$comment)mG(w);if(MB(w),Q.let(x.default.vErrors,null),Q.let(x.default.errors,0),$.unevaluated)LB(w);cG(w),ZB(w)});return}function LB(w){let{gen:b,validateName:$}=w;w.evaluated=b.const("evaluated",T._`${$}.evaluated`),b.if(T._`${w.evaluated}.dynamicProps`,()=>b.assign(T._`${w.evaluated}.props`,T._`undefined`)),b.if(T._`${w.evaluated}.dynamicItems`,()=>b.assign(T._`${w.evaluated}.items`,T._`undefined`))}function vG(w,b){let $=typeof w=="object"&&w[b.schemaId];return $&&(b.code.source||b.code.process)?T._`/*# sourceURL=${$} */`:T.nil}function FB(w,b){if(uG(w)){if(fG(w),yG(w)){BB(w,b);return}}(0,xG.boolOrEmptySchema)(w,b)}function yG({schema:w,self:b}){if(typeof w=="boolean")return!w;for(let $ in w)if(b.RULES.all[$])return!0;return!1}function uG(w){return typeof w.schema!="boolean"}function BB(w,b){let{schema:$,gen:Q,opts:W}=w;if(W.$comment&&$.$comment)mG(w);KB(w),qB(w);let X=Q.const("_errs",x.default.errors);cG(w,X),Q.var(b,T._`${X} === ${x.default.errors}`)}function fG(w){(0,J1.checkUnknownRules)(w),OB(w)}function cG(w,b){if(w.opts.jtd)return _G(w,[],!1,b);let $=(0,CG.getSchemaTypes)(w.schema),Q=(0,CG.coerceAndCheckDataType)(w,$);_G(w,$,!Q,b)}function OB(w){let{schema:b,errSchemaPath:$,opts:Q,self:W}=w;if(b.$ref&&Q.ignoreKeywordsWithRef&&(0,J1.schemaHasRulesButRef)(b,W.RULES))W.logger.warn(`$ref: keywords ignored in schema at path "${$}"`)}function MB(w){let{schema:b,opts:$}=w;if(b.default!==void 0&&$.useDefaults&&$.strictSchema)(0,J1.checkStrictMode)(w,"default is ignored in the schema root")}function KB(w){let b=w.schema[w.opts.schemaId];if(b)w.baseId=(0,HB.resolveUrl)(w.opts.uriResolver,w.baseId,b)}function qB(w){if(w.schema.$async&&!w.schemaEnv.$async)throw Error("async schema in sync schema")}function mG({gen:w,schemaEnv:b,schema:$,errSchemaPath:Q,opts:W}){let X=$.$comment;if(W.$comment===!0)w.code(T._`${x.default.self}.logger.log(${X})`);else if(typeof W.$comment=="function"){let Y=T.str`${Q}/$comment`,G=w.scopeValue("root",{ref:b.root});w.code(T._`${x.default.self}.opts.$comment(${X}, ${Y}, ${G}.schema)`)}}function ZB(w){let{gen:b,schemaEnv:$,validateName:Q,ValidationError:W,opts:X}=w;if($.$async)b.if(T._`${x.default.errors} === 0`,()=>b.return(x.default.data),()=>b.throw(T._`new ${W}(${x.default.vErrors})`));else{if(b.assign(T._`${Q}.errors`,x.default.vErrors),X.unevaluated)PB(w);b.return(T._`${x.default.errors} === 0`)}}function PB({gen:w,evaluated:b,props:$,items:Q}){if($ instanceof T.Name)w.assign(T._`${b}.props`,$);if(Q instanceof T.Name)w.assign(T._`${b}.items`,Q)}function _G(w,b,$,Q){let{gen:W,schema:X,data:Y,allErrors:G,opts:J,self:H}=w,{RULES:z}=H;if(X.$ref&&(J.ignoreKeywordsWithRef||!(0,J1.schemaHasRulesButRef)(X,z))){W.block(()=>lG(w,"$ref",z.all.$ref.definition));return}if(!J.jtd)VB(w,b);W.block(()=>{for(let A of z.rules)D(A);D(z.post)});function D(A){if(!(0,m6.shouldUseGroup)(X,A))return;if(A.type){if(W.if((0,B$.checkDataType)(A.type,Y,J.strictNumbers)),kG(w,A),b.length===1&&b[0]===A.type&&$)W.else(),(0,B$.reportTypeError)(w);W.endIf()}else kG(w,A);if(!G)W.if(T._`${x.default.errors} === ${Q||0}`)}}function kG(w,b){let{gen:$,schema:Q,opts:{useDefaults:W}}=w;if(W)(0,JB.assignDefaults)(w,b.type);$.block(()=>{for(let X of b.rules)if((0,m6.shouldUseRule)(Q,X))lG(w,X.keyword,X.definition,b.type)})}function VB(w,b){if(w.schemaEnv.meta||!w.opts.strictTypes)return;if(jB(w,b),!w.opts.allowUnionTypes)IB(w,b);NB(w,w.dataTypes)}function jB(w,b){if(!b.length)return;if(!w.dataTypes.length){w.dataTypes=b;return}b.forEach(($)=>{if(!gG(w.dataTypes,$))g6(w,`type "${$}" not allowed by context "${w.dataTypes.join(",")}"`)}),TB(w,b)}function IB(w,b){if(b.length>1&&!(b.length===2&&b.includes("null")))g6(w,"use allowUnionTypes to allow union type keyword")}function NB(w,b){let $=w.self.RULES.all;for(let Q in $){let W=$[Q];if(typeof W=="object"&&(0,m6.shouldUseRule)(w.schema,W)){let{type:X}=W.definition;if(X.length&&!X.some((Y)=>EB(b,Y)))g6(w,`missing type "${X.join(",")}" for keyword "${Q}"`)}}}function EB(w,b){return w.includes(b)||b==="number"&&w.includes("integer")}function gG(w,b){return w.includes(b)||b==="integer"&&w.includes("number")}function TB(w,b){let $=[];for(let Q of w.dataTypes)if(gG(b,Q))$.push(Q);else if(b.includes("integer")&&Q==="number")$.push("integer");w.dataTypes=$}function g6(w,b){let $=w.schemaEnv.baseId+w.errSchemaPath;b+=` at "${$}" (strictTypes)`,(0,J1.checkStrictMode)(w,b,w.opts.strictTypes)}class l6{constructor(w,b,$){if((0,r0.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,J1.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",iG(this.$data,w));else if(this.schemaCode=this.schemaValue,!(0,r0.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,T.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,T.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(T._`${b} !== undefined && (${(0,T.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?t0.reportExtraError:t0.reportError)(this,this.def.error,b)}$dataError(){(0,t0.reportError)(this,this.def.$dataError||t0.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,t0.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,$=T.nil){this.gen.block(()=>{this.check$data(w,$),b()})}check$data(w=T.nil,b=T.nil){if(!this.$data)return;let{gen:$,schemaCode:Q,schemaType:W,def:X}=this;if($.if((0,T.or)(T._`${Q} === undefined`,b)),w!==T.nil)$.assign(w,!0);if(W.length||X.validateSchema){if($.elseIf(this.invalid$data()),this.$dataError(),w!==T.nil)$.assign(w,!1)}$.else()}invalid$data(){let{gen:w,schemaCode:b,schemaType:$,def:Q,it:W}=this;return(0,T.or)(X(),Y());function X(){if($.length){if(!(b instanceof T.Name))throw Error("ajv implementation error");let G=Array.isArray($)?$:[$];return T._`${(0,B$.checkDataTypes)(G,b,W.opts.strictNumbers,B$.DataType.Wrong)}`}return T.nil}function Y(){if(Q.validateSchema){let G=w.scopeValue("validate$data",{ref:Q.validateSchema});return T._`!${G}(${b})`}return T.nil}}subschema(w,b){let $=(0,c6.getSubschema)(this.it,w);(0,c6.extendSubschemaData)($,this.it,w),(0,c6.extendSubschemaMode)($,w);let Q={...this.it,...$,items:void 0,props:void 0};return FB(Q,b),Q}mergeEvaluated(w,b){let{it:$,gen:Q}=this;if(!$.opts.unevaluated)return;if($.props!==!0&&w.props!==void 0)$.props=J1.mergeEvaluated.props(Q,w.props,$.props,b);if($.items!==!0&&w.items!==void 0)$.items=J1.mergeEvaluated.items(Q,w.items,$.items,b)}mergeValidEvaluated(w,b){let{it:$,gen:Q}=this;if($.opts.unevaluated&&($.props!==!0||$.items!==!0))return Q.if(b,()=>this.mergeEvaluated(w,T.Name)),!0}}nG.KeywordCxt=l6;function lG(w,b,$,Q){let W=new l6(w,$,b);if("code"in $)$.code(W,Q);else if(W.$data&&$.validate)(0,r0.funcKeywordCode)(W,$);else if("macro"in $)(0,r0.macroKeywordCode)(W,$);else if($.compile||$.validate)(0,r0.funcKeywordCode)(W,$)}var RB=/^\/(?:[^~]|~0|~1)*$/,SB=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function iG(w,{dataLevel:b,dataNames:$,dataPathArr:Q}){let W,X;if(w==="")return x.default.rootData;if(w[0]==="/"){if(!RB.test(w))throw Error(`Invalid JSON-pointer: ${w}`);W=w,X=x.default.rootData}else{let H=SB.exec(w);if(!H)throw Error(`Invalid JSON-pointer: ${w}`);let z=+H[1];if(W=H[2],W==="#"){if(z>=b)throw Error(J("property/index",z));return Q[b-z]}if(z>b)throw Error(J("data",z));if(X=$[b-z],!W)return X}let Y=X,G=W.split("/");for(let H of G)if(H)X=T._`${X}${(0,T.getProperty)((0,J1.unescapeJsonPointer)(H))}`,Y=T._`${Y} && ${X}`;return Y;function J(H,z){return`Cannot access ${H} ${z} levels up, current level is ${b}`}}nG.getData=iG});var O$=I((dG)=>{Object.defineProperty(dG,"__esModule",{value:!0});class oG extends Error{constructor(w){super("validation failed");this.errors=w,this.ajv=this.validation=!0}}dG.default=oG});var e0=I((rG)=>{Object.defineProperty(rG,"__esModule",{value:!0});var i6=d0();class tG extends Error{constructor(w,b,$,Q){super(Q||`can't resolve reference ${$} from id ${b}`);this.missingRef=(0,i6.resolveUrl)(w,b,$),this.missingSchema=(0,i6.normalizeId)((0,i6.getFullPath)(w,this.missingRef))}}rG.default=tG});var K$=I((aG)=>{Object.defineProperty(aG,"__esModule",{value:!0});aG.resolveSchema=aG.getCompilingSchema=aG.resolveRef=aG.compileSchema=aG.SchemaEnv=void 0;var lw=f(),xB=O$(),y1=G1(),iw=d0(),sG=d(),hB=s0();class a0{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={}}}aG.SchemaEnv=a0;function p6(w){let b=eG.call(this,w);if(b)return b;let $=(0,iw.getFullPath)(this.opts.uriResolver,w.root.baseId),{es5:Q,lines:W}=this.opts.code,{ownProperties:X}=this.opts,Y=new lw.CodeGen(this.scope,{es5:Q,lines:W,ownProperties:X}),G;if(w.$async)G=Y.scopeValue("Error",{ref:xB.default,code:lw._`require("ajv/dist/runtime/validation_error").default`});let J=Y.scopeName("validate");w.validateName=J;let H={gen:Y,allErrors:this.opts.allErrors,data:y1.default.data,parentData:y1.default.parentData,parentDataProperty:y1.default.parentDataProperty,dataNames:[y1.default.data],dataPathArr:[lw.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:Y.scopeValue("schema",this.opts.code.source===!0?{ref:w.schema,code:(0,lw.stringify)(w.schema)}:{ref:w.schema}),validateName:J,ValidationError:G,schema:w.schema,schemaEnv:w,rootId:$,baseId:w.baseId||$,schemaPath:lw.nil,errSchemaPath:w.schemaPath||(this.opts.jtd?"":"#"),errorPath:lw._`""`,opts:this.opts,self:this},z;try{this._compilations.add(w),(0,hB.validateFunctionCode)(H),Y.optimize(this.opts.code.optimize);let D=Y.toString();if(z=`${Y.scopeRefs(y1.default.scope)}return ${D}`,this.opts.code.process)z=this.opts.code.process(z,w);let L=Function(`${y1.default.self}`,`${y1.default.scope}`,z)(this,this.scope.get());if(this.scope.value(J,{ref:L}),L.errors=null,L.schema=w.schema,L.schemaEnv=w,w.$async)L.$async=!0;if(this.opts.code.source===!0)L.source={validateName:J,validateCode:D,scopeValues:Y._values};if(this.opts.unevaluated){let{props:O,items:K}=H;if(L.evaluated={props:O instanceof lw.Name?void 0:O,items:K instanceof lw.Name?void 0:K,dynamicProps:O instanceof lw.Name,dynamicItems:K instanceof lw.Name},L.source)L.source.evaluated=(0,lw.stringify)(L.evaluated)}return w.validate=L,w}catch(D){if(delete w.validate,delete w.validateName,z)this.logger.error("Error compiling schema, function code:",z);throw D}finally{this._compilations.delete(w)}}aG.compileSchema=p6;function yB(w,b,$){var Q;$=(0,iw.resolveUrl)(this.opts.uriResolver,b,$);let W=w.refs[$];if(W)return W;let X=cB.call(this,w,$);if(X===void 0){let Y=(Q=w.localRefs)===null||Q===void 0?void 0:Q[$],{schemaId:G}=this.opts;if(Y)X=new a0({schema:Y,schemaId:G,root:w,baseId:b})}if(X===void 0)return;return w.refs[$]=uB.call(this,X)}aG.resolveRef=yB;function uB(w){if((0,iw.inlineRef)(w.schema,this.opts.inlineRefs))return w.schema;return w.validate?w:p6.call(this,w)}function eG(w){for(let b of this._compilations)if(fB(b,w))return b}aG.getCompilingSchema=eG;function fB(w,b){return w.schema===b.schema&&w.root===b.root&&w.baseId===b.baseId}function cB(w,b){let $;while(typeof($=this.refs[b])=="string")b=$;return $||this.schemas[b]||M$.call(this,w,b)}function M$(w,b){let $=this.opts.uriResolver.parse(b),Q=(0,iw._getFullPath)(this.opts.uriResolver,$),W=(0,iw.getFullPath)(this.opts.uriResolver,w.baseId,void 0);if(Object.keys(w.schema).length>0&&Q===W)return n6.call(this,$,w);let X=(0,iw.normalizeId)(Q),Y=this.refs[X]||this.schemas[X];if(typeof Y=="string"){let G=M$.call(this,w,Y);if(typeof(G===null||G===void 0?void 0:G.schema)!=="object")return;return n6.call(this,$,G)}if(typeof(Y===null||Y===void 0?void 0:Y.schema)!=="object")return;if(!Y.validate)p6.call(this,Y);if(X===(0,iw.normalizeId)(b)){let{schema:G}=Y,{schemaId:J}=this.opts,H=G[J];if(H)W=(0,iw.resolveUrl)(this.opts.uriResolver,W,H);return new a0({schema:G,schemaId:J,root:w,baseId:W})}return n6.call(this,$,Y)}aG.resolveSchema=M$;var mB=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function n6(w,{baseId:b,schema:$,root:Q}){var W;if(((W=w.fragment)===null||W===void 0?void 0:W[0])!=="/")return;for(let G of w.fragment.slice(1).split("/")){if(typeof $==="boolean")return;let J=$[(0,sG.unescapeFragment)(G)];if(J===void 0)return;$=J;let H=typeof $==="object"&&$[this.opts.schemaId];if(!mB.has(G)&&H)b=(0,iw.resolveUrl)(this.opts.uriResolver,b,H)}let X;if(typeof $!="boolean"&&$.$ref&&!(0,sG.schemaHasRulesButRef)($,this.RULES)){let G=(0,iw.resolveUrl)(this.opts.uriResolver,b,$.$ref);X=M$.call(this,Q,G)}let{schemaId:Y}=this.opts;if(X=X||new a0({schema:$,schemaId:Y,root:Q,baseId:b}),X.schema!==X.root.schema)return X;return}});var bJ=I((sT,pB)=>{pB.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 d6=I((eT,XJ)=>{var oB=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),QJ=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 o6(w){let b="",$=0,Q=0;for(Q=0;Q<w.length;Q++){if($=w[Q].charCodeAt(0),$===48)continue;if(!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";b+=w[Q];break}for(Q+=1;Q<w.length;Q++){if($=w[Q].charCodeAt(0),!($>=48&&$<=57||$>=65&&$<=70||$>=97&&$<=102))return"";b+=w[Q]}return b}var dB=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function $J(w){return w.length=0,!0}function tB(w,b,$){if(w.length){let Q=o6(w);if(Q!=="")b.push(Q);else return $.error=!0,!1;w.length=0}return!0}function rB(w){let b=0,$={error:!1,address:"",zone:""},Q=[],W=[],X=!1,Y=!1,G=tB;for(let J=0;J<w.length;J++){let H=w[J];if(H==="["||H==="]")continue;if(H===":"){if(X===!0)Y=!0;if(!G(W,Q,$))break;if(++b>7){$.error=!0;break}if(J>0&&w[J-1]===":")X=!0;Q.push(":");continue}else if(H==="%"){if(!G(W,Q,$))break;G=$J}else{W.push(H);continue}}if(W.length)if(G===$J)$.zone=W.join("");else if(Y)Q.push(W.join(""));else Q.push(o6(W));return $.address=Q.join(""),$}function WJ(w){if(sB(w,":")<2)return{host:w,isIPV6:!1};let b=rB(w);if(!b.error){let{address:$,address:Q}=b;if(b.zone)$+="%"+b.zone,Q+="%25"+b.zone;return{host:$,isIPV6:!0,escapedHost:Q}}else return{host:w,isIPV6:!1}}function sB(w,b){let $=0;for(let Q=0;Q<w.length;Q++)if(w[Q]===b)$++;return $}function eB(w){let b=w,$=[],Q=-1,W=0;while(W=b.length){if(W===1)if(b===".")break;else if(b==="/"){$.push("/");break}else{$.push(b);break}else if(W===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(W===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((Q=b.indexOf("/",1))===-1){$.push(b);break}else $.push(b.slice(0,Q)),b=b.slice(Q)}return $.join("")}function aB(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 wO(w){let b=[];if(w.userinfo!==void 0)b.push(w.userinfo),b.push("@");if(w.host!==void 0){let $=unescape(w.host);if(!QJ($)){let Q=WJ($);if(Q.isIPV6===!0)$=`[${Q.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}XJ.exports={nonSimpleDomain:dB,recomposeAuthority:wO,normalizeComponentEncoding:aB,removeDotSegments:eB,isIPv4:QJ,isUUID:oB,normalizeIPv6:WJ,stringArrayToHexStripped:o6}});var zJ=I((aT,HJ)=>{var{isUUID:bO}=d6(),$O=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,QO=["http","https","ws","wss","urn","urn:uuid"];function WO(w){return QO.indexOf(w)!==-1}function t6(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 YJ(w){if(!w.host)w.error=w.error||"HTTP URIs must have a host.";return w}function GJ(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 XO(w){return w.secure=t6(w),w.resourceName=(w.path||"/")+(w.query?"?"+w.query:""),w.path=void 0,w.query=void 0,w}function YO(w){if(w.port===(t6(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 GO(w,b){if(!w.path)return w.error="URN can not be parsed",w;let $=w.path.match($O);if($){let Q=b.scheme||w.scheme||"urn";w.nid=$[1].toLowerCase(),w.nss=$[2];let W=`${Q}:${b.nid||w.nid}`,X=r6(W);if(w.path=void 0,X)w=X.parse(w,b)}else w.error=w.error||"URN can not be parsed.";return w}function JO(w,b){if(w.nid===void 0)throw Error("URN without nid cannot be serialized");let $=b.scheme||w.scheme||"urn",Q=w.nid.toLowerCase(),W=`${$}:${b.nid||Q}`,X=r6(W);if(X)w=X.serialize(w,b);let Y=w,G=w.nss;return Y.path=`${Q||b.nid}:${G}`,b.skipEscape=!0,Y}function HO(w,b){let $=w;if($.uuid=$.nss,$.nss=void 0,!b.tolerant&&(!$.uuid||!bO($.uuid)))$.error=$.error||"UUID is not valid.";return $}function zO(w){let b=w;return b.nss=(w.uuid||"").toLowerCase(),b}var JJ={scheme:"http",domainHost:!0,parse:YJ,serialize:GJ},DO={scheme:"https",domainHost:JJ.domainHost,parse:YJ,serialize:GJ},q$={scheme:"ws",domainHost:!0,parse:XO,serialize:YO},UO={scheme:"wss",domainHost:q$.domainHost,parse:q$.parse,serialize:q$.serialize},AO={scheme:"urn",parse:GO,serialize:JO,skipNormalize:!0},LO={scheme:"urn:uuid",parse:HO,serialize:zO,skipNormalize:!0},Z$={http:JJ,https:DO,ws:q$,wss:UO,urn:AO,"urn:uuid":LO};Object.setPrototypeOf(Z$,null);function r6(w){return w&&(Z$[w]||Z$[w.toLowerCase()])||void 0}HJ.exports={wsIsSecure:t6,SCHEMES:Z$,isValidSchemeName:WO,getSchemeHandler:r6}});var AJ=I((wR,V$)=>{var{normalizeIPv6:FO,removeDotSegments:wb,recomposeAuthority:BO,normalizeComponentEncoding:P$,isIPv4:OO,nonSimpleDomain:MO}=d6(),{SCHEMES:KO,getSchemeHandler:DJ}=zJ();function qO(w,b){if(typeof w==="string")w=ew(H1(w,b),b);else if(typeof w==="object")w=H1(ew(w,b),b);return w}function ZO(w,b,$){let Q=$?Object.assign({scheme:"null"},$):{scheme:"null"},W=UJ(H1(w,Q),H1(b,Q),Q,!0);return Q.skipEscape=!0,ew(W,Q)}function UJ(w,b,$,Q){let W={};if(!Q)w=H1(ew(w,$),$),b=H1(ew(b,$),$);if($=$||{},!$.tolerant&&b.scheme)W.scheme=b.scheme,W.userinfo=b.userinfo,W.host=b.host,W.port=b.port,W.path=wb(b.path||""),W.query=b.query;else{if(b.userinfo!==void 0||b.host!==void 0||b.port!==void 0)W.userinfo=b.userinfo,W.host=b.host,W.port=b.port,W.path=wb(b.path||""),W.query=b.query;else{if(!b.path)if(W.path=w.path,b.query!==void 0)W.query=b.query;else W.query=w.query;else{if(b.path[0]==="/")W.path=wb(b.path);else{if((w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)&&!w.path)W.path="/"+b.path;else if(!w.path)W.path=b.path;else W.path=w.path.slice(0,w.path.lastIndexOf("/")+1)+b.path;W.path=wb(W.path)}W.query=b.query}W.userinfo=w.userinfo,W.host=w.host,W.port=w.port}W.scheme=w.scheme}return W.fragment=b.fragment,W}function PO(w,b,$){if(typeof w==="string")w=unescape(w),w=ew(P$(H1(w,$),!0),{...$,skipEscape:!0});else if(typeof w==="object")w=ew(P$(w,!0),{...$,skipEscape:!0});if(typeof b==="string")b=unescape(b),b=ew(P$(H1(b,$),!0),{...$,skipEscape:!0});else if(typeof b==="object")b=ew(P$(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:""},Q=Object.assign({},b),W=[],X=DJ(Q.scheme||$.scheme);if(X&&X.serialize)X.serialize($,Q);if($.path!==void 0)if(!Q.skipEscape){if($.path=escape($.path),$.scheme!==void 0)$.path=$.path.split("%3A").join(":")}else $.path=unescape($.path);if(Q.reference!=="suffix"&&$.scheme)W.push($.scheme,":");let Y=BO($);if(Y!==void 0){if(Q.reference!=="suffix")W.push("//");if(W.push(Y),$.path&&$.path[0]!=="/")W.push("/")}if($.path!==void 0){let G=$.path;if(!Q.absolutePath&&(!X||!X.absolutePath))G=wb(G);if(Y===void 0&&G[0]==="/"&&G[1]==="/")G="/%2F"+G.slice(2);W.push(G)}if($.query!==void 0)W.push("?",$.query);if($.fragment!==void 0)W.push("#",$.fragment);return W.join("")}var VO=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function H1(w,b){let $=Object.assign({},b),Q={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},W=!1;if($.reference==="suffix")if($.scheme)w=$.scheme+":"+w;else w="//"+w;let X=w.match(VO);if(X){if(Q.scheme=X[1],Q.userinfo=X[3],Q.host=X[4],Q.port=parseInt(X[5],10),Q.path=X[6]||"",Q.query=X[7],Q.fragment=X[8],isNaN(Q.port))Q.port=X[5];if(Q.host)if(OO(Q.host)===!1){let J=FO(Q.host);Q.host=J.host.toLowerCase(),W=J.isIPV6}else W=!0;if(Q.scheme===void 0&&Q.userinfo===void 0&&Q.host===void 0&&Q.port===void 0&&Q.query===void 0&&!Q.path)Q.reference="same-document";else if(Q.scheme===void 0)Q.reference="relative";else if(Q.fragment===void 0)Q.reference="absolute";else Q.reference="uri";if($.reference&&$.reference!=="suffix"&&$.reference!==Q.reference)Q.error=Q.error||"URI is not a "+$.reference+" reference.";let Y=DJ($.scheme||Q.scheme);if(!$.unicodeSupport&&(!Y||!Y.unicodeSupport)){if(Q.host&&($.domainHost||Y&&Y.domainHost)&&W===!1&&MO(Q.host))try{Q.host=URL.domainToASCII(Q.host.toLowerCase())}catch(G){Q.error=Q.error||"Host's domain name can not be converted to ASCII: "+G}}if(!Y||Y&&!Y.skipNormalize){if(w.indexOf("%")!==-1){if(Q.scheme!==void 0)Q.scheme=unescape(Q.scheme);if(Q.host!==void 0)Q.host=unescape(Q.host)}if(Q.path)Q.path=escape(unescape(Q.path));if(Q.fragment)Q.fragment=encodeURI(decodeURIComponent(Q.fragment))}if(Y&&Y.parse)Y.parse(Q,$)}else Q.error=Q.error||"URI can not be parsed.";return Q}var s6={SCHEMES:KO,normalize:qO,resolve:ZO,resolveComponent:UJ,equal:PO,serialize:ew,parse:H1};V$.exports=s6;V$.exports.default=s6;V$.exports.fastUri=s6});var BJ=I((FJ)=>{Object.defineProperty(FJ,"__esModule",{value:!0});var LJ=AJ();LJ.code='require("ajv/dist/runtime/uri").default';FJ.default=LJ});var jJ=I((z1)=>{Object.defineProperty(z1,"__esModule",{value:!0});z1.CodeGen=z1.Name=z1.nil=z1.stringify=z1.str=z1._=z1.KeywordCxt=void 0;var IO=s0();Object.defineProperty(z1,"KeywordCxt",{enumerable:!0,get:function(){return IO.KeywordCxt}});var $0=f();Object.defineProperty(z1,"_",{enumerable:!0,get:function(){return $0._}});Object.defineProperty(z1,"str",{enumerable:!0,get:function(){return $0.str}});Object.defineProperty(z1,"stringify",{enumerable:!0,get:function(){return $0.stringify}});Object.defineProperty(z1,"nil",{enumerable:!0,get:function(){return $0.nil}});Object.defineProperty(z1,"Name",{enumerable:!0,get:function(){return $0.Name}});Object.defineProperty(z1,"CodeGen",{enumerable:!0,get:function(){return $0.CodeGen}});var NO=O$(),ZJ=e0(),EO=S6(),bb=K$(),TO=f(),$b=d0(),j$=o0(),a6=d(),OJ=bJ(),RO=BJ(),PJ=(w,b)=>new RegExp(w,b);PJ.code="new RegExp";var SO=["removeAdditional","useDefaults","coerceTypes"],CO=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),vO={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."},_O={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},MJ=200;function kO(w){var b,$,Q,W,X,Y,G,J,H,z,D,A,L,O,K,j,V,_,R,m,k,tw,b1,Y4,G4;let B0=w.strict,J4=(b=w.code)===null||b===void 0?void 0:b.optimize,YQ=J4===!0||J4===void 0?1:J4||0,GQ=(Q=($=w.code)===null||$===void 0?void 0:$.regExp)!==null&&Q!==void 0?Q:PJ,C5=(W=w.uriResolver)!==null&&W!==void 0?W:RO.default;return{strictSchema:(Y=(X=w.strictSchema)!==null&&X!==void 0?X:B0)!==null&&Y!==void 0?Y:!0,strictNumbers:(J=(G=w.strictNumbers)!==null&&G!==void 0?G:B0)!==null&&J!==void 0?J:!0,strictTypes:(z=(H=w.strictTypes)!==null&&H!==void 0?H:B0)!==null&&z!==void 0?z:"log",strictTuples:(A=(D=w.strictTuples)!==null&&D!==void 0?D:B0)!==null&&A!==void 0?A:"log",strictRequired:(O=(L=w.strictRequired)!==null&&L!==void 0?L:B0)!==null&&O!==void 0?O:!1,code:w.code?{...w.code,optimize:YQ,regExp:GQ}:{optimize:YQ,regExp:GQ},loopRequired:(K=w.loopRequired)!==null&&K!==void 0?K:MJ,loopEnum:(j=w.loopEnum)!==null&&j!==void 0?j:MJ,meta:(V=w.meta)!==null&&V!==void 0?V:!0,messages:(_=w.messages)!==null&&_!==void 0?_:!0,inlineRefs:(R=w.inlineRefs)!==null&&R!==void 0?R:!0,schemaId:(m=w.schemaId)!==null&&m!==void 0?m:"$id",addUsedSchema:(k=w.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(tw=w.validateSchema)!==null&&tw!==void 0?tw:!0,validateFormats:(b1=w.validateFormats)!==null&&b1!==void 0?b1:!0,unicodeRegExp:(Y4=w.unicodeRegExp)!==null&&Y4!==void 0?Y4:!0,int32range:(G4=w.int32range)!==null&&G4!==void 0?G4:!0,uriResolver:C5}}class I${constructor(w={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,w=this.opts={...w,...kO(w)};let{es5:b,lines:$}=this.opts.code;this.scope=new TO.ValueScope({scope:{},prefixes:CO,es5:b,lines:$}),this.logger=cO(w.logger);let Q=w.validateFormats;if(w.validateFormats=!1,this.RULES=(0,EO.getRules)(),KJ.call(this,vO,w,"NOT SUPPORTED"),KJ.call(this,_O,w,"DEPRECATED","warn"),this._metaOpts=uO.call(this),w.formats)hO.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),w.keywords)yO.call(this,w.keywords);if(typeof w.meta=="object")this.addMetaSchema(w.meta);xO.call(this),w.validateFormats=Q}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:w,meta:b,schemaId:$}=this.opts,Q=OJ;if($==="id")Q={...OJ},Q.id=Q.$id,delete Q.$id;if(b&&w)this.addMetaSchema(Q,Q[$],!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 Q=$(b);if(!("$async"in $))this.errors=$.errors;return Q}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 Q.call(this,w,b);async function Q(H,z){await W.call(this,H.$schema);let D=this._addSchema(H,z);return D.validate||X.call(this,D)}async function W(H){if(H&&!this.getSchema(H))await Q.call(this,{$ref:H},!0)}async function X(H){try{return this._compileSchemaEnv(H)}catch(z){if(!(z instanceof ZJ.default))throw z;return Y.call(this,z),await G.call(this,z.missingSchema),X.call(this,H)}}function Y({missingSchema:H,missingRef:z}){if(this.refs[H])throw Error(`AnySchema ${H} is loaded but ${z} cannot be resolved`)}async function G(H){let z=await J.call(this,H);if(!this.refs[H])await W.call(this,z.$schema);if(!this.refs[H])this.addSchema(z,H,b)}async function J(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,$,Q=this.opts.validateSchema){if(Array.isArray(w)){for(let X of w)this.addSchema(X,void 0,$,Q);return this}let W;if(typeof w==="object"){let{schemaId:X}=this.opts;if(W=w[X],W!==void 0&&typeof W!="string")throw Error(`schema ${X} must be string`)}return b=(0,$b.normalizeId)(b||W),this._checkUnique(b),this.schemas[b]=this._addSchema(w,$,b,Q,!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 Q=this.validate($,w);if(!Q&&b){let W="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(W);else throw Error(W)}return Q}getSchema(w){let b;while(typeof(b=qJ.call(this,w))=="string")w=b;if(b===void 0){let{schemaId:$}=this.opts,Q=new bb.SchemaEnv({schema:{},schemaId:$});if(b=bb.resolveSchema.call(this,Q,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=qJ.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,$b.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(gO.call(this,$,b),!b)return(0,a6.eachItem)($,(W)=>e6.call(this,W)),this;iO.call(this,b);let Q={...b,type:(0,j$.getJSONTypes)(b.type),schemaType:(0,j$.getJSONTypes)(b.schemaType)};return(0,a6.eachItem)($,Q.type.length===0?(W)=>e6.call(this,W,Q):(W)=>Q.type.forEach((X)=>e6.call(this,W,Q,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 Q=$.rules.findIndex((W)=>W.keyword===w);if(Q>=0)$.rules.splice(Q,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((Q)=>`${$}${Q.instancePath} ${Q.message}`).reduce((Q,W)=>Q+b+W)}$dataMetaSchema(w,b){let $=this.RULES.all;w=JSON.parse(JSON.stringify(w));for(let Q of b){let W=Q.split("/").slice(1),X=w;for(let Y of W)X=X[Y];for(let Y in $){let G=$[Y];if(typeof G!="object")continue;let{$data:J}=G.definition,H=X[Y];if(J&&H)X[Y]=VJ(H)}}return w}_removeAllSchemas(w,b){for(let $ in w){let Q=w[$];if(!b||b.test($)){if(typeof Q=="string")delete w[$];else if(Q&&!Q.meta)this._cache.delete(Q.schema),delete w[$]}}}_addSchema(w,b,$,Q=this.opts.validateSchema,W=this.opts.addUsedSchema){let X,{schemaId:Y}=this.opts;if(typeof w=="object")X=w[Y];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 G=this._cache.get(w);if(G!==void 0)return G;$=(0,$b.normalizeId)(X||$);let J=$b.getSchemaRefs.call(this,w,$);if(G=new bb.SchemaEnv({schema:w,schemaId:Y,meta:b,baseId:$,localRefs:J}),this._cache.set(G.schema,G),W&&!$.startsWith("#")){if($)this._checkUnique($);this.refs[$]=G}if(Q)this.validateSchema(w,!0);return G}_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 bb.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{bb.compileSchema.call(this,w)}finally{this.opts=b}}}I$.ValidationError=NO.default;I$.MissingRefError=ZJ.default;z1.default=I$;function KJ(w,b,$,Q="error"){for(let W in w){let X=W;if(X in b)this.logger[Q](`${$}: option ${W}. ${w[X]}`)}}function qJ(w){return w=(0,$b.normalizeId)(w),this.schemas[w]||this.refs[w]}function xO(){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 hO(){for(let w in this.opts.formats){let b=this.opts.formats[w];if(b)this.addFormat(w,b)}}function yO(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 uO(){let w={...this.opts};for(let b of SO)delete w[b];return w}var fO={log(){},warn(){},error(){}};function cO(w){if(w===!1)return fO;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 mO=/^[a-z_$][a-z0-9_$:-]*$/i;function gO(w,b){let{RULES:$}=this;if((0,a6.eachItem)(w,(Q)=>{if($.keywords[Q])throw Error(`Keyword ${Q} is already defined`);if(!mO.test(Q))throw Error(`Keyword ${Q} 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 e6(w,b,$){var Q;let W=b===null||b===void 0?void 0:b.post;if($&&W)throw Error('keyword with "post" flag cannot have "type"');let{RULES:X}=this,Y=W?X.post:X.rules.find(({type:J})=>J===$);if(!Y)Y={type:$,rules:[]},X.rules.push(Y);if(X.keywords[w]=!0,!b)return;let G={keyword:w,definition:{...b,type:(0,j$.getJSONTypes)(b.type),schemaType:(0,j$.getJSONTypes)(b.schemaType)}};if(b.before)lO.call(this,Y,G,b.before);else Y.rules.push(G);X.all[w]=G,(Q=b.implements)===null||Q===void 0||Q.forEach((J)=>this.addKeyword(J))}function lO(w,b,$){let Q=w.rules.findIndex((W)=>W.keyword===$);if(Q>=0)w.rules.splice(Q,0,b);else w.rules.push(b),this.logger.warn(`rule ${$} is not defined`)}function iO(w){let{metaSchema:b}=w;if(b===void 0)return;if(w.$data&&this.opts.$data)b=VJ(b);w.validateSchema=this.compile(b,!0)}var nO={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function VJ(w){return{anyOf:[w,nO]}}});var NJ=I((IJ)=>{Object.defineProperty(IJ,"__esModule",{value:!0});var dO={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};IJ.default=dO});var vJ=I((SJ)=>{Object.defineProperty(SJ,"__esModule",{value:!0});SJ.callRef=SJ.getValidate=void 0;var rO=e0(),EJ=hw(),Ew=f(),Q0=G1(),TJ=K$(),N$=d(),sO={keyword:"$ref",schemaType:"string",code(w){let{gen:b,schema:$,it:Q}=w,{baseId:W,schemaEnv:X,validateName:Y,opts:G,self:J}=Q,{root:H}=X;if(($==="#"||$==="#/")&&W===H.baseId)return D();let z=TJ.resolveRef.call(J,H,W,$);if(z===void 0)throw new rO.default(Q.opts.uriResolver,W,$);if(z instanceof TJ.SchemaEnv)return A(z);return L(z);function D(){if(X===H)return E$(w,Y,X,X.$async);let O=b.scopeValue("root",{ref:H});return E$(w,Ew._`${O}.validate`,H,H.$async)}function A(O){let K=RJ(w,O);E$(w,K,O,O.$async)}function L(O){let K=b.scopeValue("schema",G.code.source===!0?{ref:O,code:(0,Ew.stringify)(O)}:{ref:O}),j=b.name("valid"),V=w.subschema({schema:O,dataTypes:[],schemaPath:Ew.nil,topSchemaRef:K,errSchemaPath:$},j);w.mergeEvaluated(V),w.ok(j)}}};function RJ(w,b){let{gen:$}=w;return b.validate?$.scopeValue("validate",{ref:b.validate}):Ew._`${$.scopeValue("wrapper",{ref:b})}.validate`}SJ.getValidate=RJ;function E$(w,b,$,Q){let{gen:W,it:X}=w,{allErrors:Y,schemaEnv:G,opts:J}=X,H=J.passContext?Q0.default.this:Ew.nil;if(Q)z();else D();function z(){if(!G.$async)throw Error("async schema referenced by sync schema");let O=W.let("valid");W.try(()=>{if(W.code(Ew._`await ${(0,EJ.callValidateCode)(w,b,H)}`),L(b),!Y)W.assign(O,!0)},(K)=>{if(W.if(Ew._`!(${K} instanceof ${X.ValidationError})`,()=>W.throw(K)),A(K),!Y)W.assign(O,!1)}),w.ok(O)}function D(){w.result((0,EJ.callValidateCode)(w,b,H),()=>L(b),()=>A(b))}function A(O){let K=Ew._`${O}.errors`;W.assign(Q0.default.vErrors,Ew._`${Q0.default.vErrors} === null ? ${K} : ${Q0.default.vErrors}.concat(${K})`),W.assign(Q0.default.errors,Ew._`${Q0.default.vErrors}.length`)}function L(O){var K;if(!X.opts.unevaluated)return;let j=(K=$===null||$===void 0?void 0:$.validate)===null||K===void 0?void 0:K.evaluated;if(X.props!==!0)if(j&&!j.dynamicProps){if(j.props!==void 0)X.props=N$.mergeEvaluated.props(W,j.props,X.props)}else{let V=W.var("props",Ew._`${O}.evaluated.props`);X.props=N$.mergeEvaluated.props(W,V,X.props,Ew.Name)}if(X.items!==!0)if(j&&!j.dynamicItems){if(j.items!==void 0)X.items=N$.mergeEvaluated.items(W,j.items,X.items)}else{let V=W.var("items",Ew._`${O}.evaluated.items`);X.items=N$.mergeEvaluated.items(W,V,X.items,Ew.Name)}}}SJ.callRef=E$;SJ.default=sO});var kJ=I((_J)=>{Object.defineProperty(_J,"__esModule",{value:!0});var wM=NJ(),bM=vJ(),$M=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",wM.default,bM.default];_J.default=$M});var hJ=I((xJ)=>{Object.defineProperty(xJ,"__esModule",{value:!0});var T$=f(),R1=T$.operators,R$={maximum:{okStr:"<=",ok:R1.LTE,fail:R1.GT},minimum:{okStr:">=",ok:R1.GTE,fail:R1.LT},exclusiveMaximum:{okStr:"<",ok:R1.LT,fail:R1.GTE},exclusiveMinimum:{okStr:">",ok:R1.GT,fail:R1.LTE}},WM={message:({keyword:w,schemaCode:b})=>T$.str`must be ${R$[w].okStr} ${b}`,params:({keyword:w,schemaCode:b})=>T$._`{comparison: ${R$[w].okStr}, limit: ${b}}`},XM={keyword:Object.keys(R$),type:"number",schemaType:"number",$data:!0,error:WM,code(w){let{keyword:b,data:$,schemaCode:Q}=w;w.fail$data(T$._`${$} ${R$[b].fail} ${Q} || isNaN(${$})`)}};xJ.default=XM});var uJ=I((yJ)=>{Object.defineProperty(yJ,"__esModule",{value:!0});var Qb=f(),GM={message:({schemaCode:w})=>Qb.str`must be multiple of ${w}`,params:({schemaCode:w})=>Qb._`{multipleOf: ${w}}`},JM={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:GM,code(w){let{gen:b,data:$,schemaCode:Q,it:W}=w,X=W.opts.multipleOfPrecision,Y=b.let("res"),G=X?Qb._`Math.abs(Math.round(${Y}) - ${Y}) > 1e-${X}`:Qb._`${Y} !== parseInt(${Y})`;w.fail$data(Qb._`(${Q} === 0 || (${Y} = ${$}/${Q}, ${G}))`)}};yJ.default=JM});var mJ=I((cJ)=>{Object.defineProperty(cJ,"__esModule",{value:!0});function fJ(w){let b=w.length,$=0,Q=0,W;while(Q<b)if($++,W=w.charCodeAt(Q++),W>=55296&&W<=56319&&Q<b){if(W=w.charCodeAt(Q),(W&64512)===56320)Q++}return $}cJ.default=fJ;fJ.code='require("ajv/dist/runtime/ucs2length").default'});var lJ=I((gJ)=>{Object.defineProperty(gJ,"__esModule",{value:!0});var u1=f(),DM=d(),UM=mJ(),AM={message({keyword:w,schemaCode:b}){let $=w==="maxLength"?"more":"fewer";return u1.str`must NOT have ${$} than ${b} characters`},params:({schemaCode:w})=>u1._`{limit: ${w}}`},LM={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:AM,code(w){let{keyword:b,data:$,schemaCode:Q,it:W}=w,X=b==="maxLength"?u1.operators.GT:u1.operators.LT,Y=W.opts.unicode===!1?u1._`${$}.length`:u1._`${(0,DM.useFunc)(w.gen,UM.default)}(${$})`;w.fail$data(u1._`${Y} ${X} ${Q}`)}};gJ.default=LM});var nJ=I((iJ)=>{Object.defineProperty(iJ,"__esModule",{value:!0});var BM=hw(),S$=f(),OM={message:({schemaCode:w})=>S$.str`must match pattern "${w}"`,params:({schemaCode:w})=>S$._`{pattern: ${w}}`},MM={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:OM,code(w){let{data:b,$data:$,schema:Q,schemaCode:W,it:X}=w,Y=X.opts.unicodeRegExp?"u":"",G=$?S$._`(new RegExp(${W}, ${Y}))`:(0,BM.usePattern)(w,Q);w.fail$data(S$._`!${G}.test(${b})`)}};iJ.default=MM});var oJ=I((pJ)=>{Object.defineProperty(pJ,"__esModule",{value:!0});var Wb=f(),qM={message({keyword:w,schemaCode:b}){let $=w==="maxProperties"?"more":"fewer";return Wb.str`must NOT have ${$} than ${b} properties`},params:({schemaCode:w})=>Wb._`{limit: ${w}}`},ZM={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:qM,code(w){let{keyword:b,data:$,schemaCode:Q}=w,W=b==="maxProperties"?Wb.operators.GT:Wb.operators.LT;w.fail$data(Wb._`Object.keys(${$}).length ${W} ${Q}`)}};pJ.default=ZM});var tJ=I((dJ)=>{Object.defineProperty(dJ,"__esModule",{value:!0});var Xb=hw(),Yb=f(),VM=d(),jM={message:({params:{missingProperty:w}})=>Yb.str`must have required property '${w}'`,params:({params:{missingProperty:w}})=>Yb._`{missingProperty: ${w}}`},IM={keyword:"required",type:"object",schemaType:"array",$data:!0,error:jM,code(w){let{gen:b,schema:$,schemaCode:Q,data:W,$data:X,it:Y}=w,{opts:G}=Y;if(!X&&$.length===0)return;let J=$.length>=G.loopRequired;if(Y.allErrors)H();else z();if(G.strictRequired){let L=w.parentSchema.properties,{definedProperties:O}=w.it;for(let K of $)if((L===null||L===void 0?void 0:L[K])===void 0&&!O.has(K)){let j=Y.schemaEnv.baseId+Y.errSchemaPath,V=`required property "${K}" is not defined at "${j}" (strictRequired)`;(0,VM.checkStrictMode)(Y,V,Y.opts.strictRequired)}}function H(){if(J||X)w.block$data(Yb.nil,D);else for(let L of $)(0,Xb.checkReportMissingProp)(w,L)}function z(){let L=b.let("missing");if(J||X){let O=b.let("valid",!0);w.block$data(O,()=>A(L,O)),w.ok(O)}else b.if((0,Xb.checkMissingProp)(w,$,L)),(0,Xb.reportMissingProp)(w,L),b.else()}function D(){b.forOf("prop",Q,(L)=>{w.setParams({missingProperty:L}),b.if((0,Xb.noPropertyInData)(b,W,L,G.ownProperties),()=>w.error())})}function A(L,O){w.setParams({missingProperty:L}),b.forOf(L,Q,()=>{b.assign(O,(0,Xb.propertyInData)(b,W,L,G.ownProperties)),b.if((0,Yb.not)(O),()=>{w.error(),b.break()})},Yb.nil)}}};dJ.default=IM});var sJ=I((rJ)=>{Object.defineProperty(rJ,"__esModule",{value:!0});var Gb=f(),EM={message({keyword:w,schemaCode:b}){let $=w==="maxItems"?"more":"fewer";return Gb.str`must NOT have ${$} than ${b} items`},params:({schemaCode:w})=>Gb._`{limit: ${w}}`},TM={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:EM,code(w){let{keyword:b,data:$,schemaCode:Q}=w,W=b==="maxItems"?Gb.operators.GT:Gb.operators.LT;w.fail$data(Gb._`${$}.length ${W} ${Q}`)}};rJ.default=TM});var C$=I((aJ)=>{Object.defineProperty(aJ,"__esModule",{value:!0});var eJ=u6();eJ.code='require("ajv/dist/runtime/equal").default';aJ.default=eJ});var b7=I((w7)=>{Object.defineProperty(w7,"__esModule",{value:!0});var w9=o0(),Kw=f(),CM=d(),vM=C$(),_M={message:({params:{i:w,j:b}})=>Kw.str`must NOT have duplicate items (items ## ${b} and ${w} are identical)`,params:({params:{i:w,j:b}})=>Kw._`{i: ${w}, j: ${b}}`},kM={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:_M,code(w){let{gen:b,data:$,$data:Q,schema:W,parentSchema:X,schemaCode:Y,it:G}=w;if(!Q&&!W)return;let J=b.let("valid"),H=X.items?(0,w9.getSchemaTypes)(X.items):[];w.block$data(J,z,Kw._`${Y} === false`),w.ok(J);function z(){let O=b.let("i",Kw._`${$}.length`),K=b.let("j");w.setParams({i:O,j:K}),b.assign(J,!0),b.if(Kw._`${O} > 1`,()=>(D()?A:L)(O,K))}function D(){return H.length>0&&!H.some((O)=>O==="object"||O==="array")}function A(O,K){let j=b.name("item"),V=(0,w9.checkDataTypes)(H,j,G.opts.strictNumbers,w9.DataType.Wrong),_=b.const("indices",Kw._`{}`);b.for(Kw._`;${O}--;`,()=>{if(b.let(j,Kw._`${$}[${O}]`),b.if(V,Kw._`continue`),H.length>1)b.if(Kw._`typeof ${j} == "string"`,Kw._`${j} += "_"`);b.if(Kw._`typeof ${_}[${j}] == "number"`,()=>{b.assign(K,Kw._`${_}[${j}]`),w.error(),b.assign(J,!1).break()}).code(Kw._`${_}[${j}] = ${O}`)})}function L(O,K){let j=(0,CM.useFunc)(b,vM.default),V=b.name("outer");b.label(V).for(Kw._`;${O}--;`,()=>b.for(Kw._`${K} = ${O}; ${K}--;`,()=>b.if(Kw._`${j}(${$}[${O}], ${$}[${K}])`,()=>{w.error(),b.assign(J,!1).break(V)})))}}};w7.default=kM});var Q7=I(($7)=>{Object.defineProperty($7,"__esModule",{value:!0});var b9=f(),hM=d(),yM=C$(),uM={message:"must be equal to constant",params:({schemaCode:w})=>b9._`{allowedValue: ${w}}`},fM={keyword:"const",$data:!0,error:uM,code(w){let{gen:b,data:$,$data:Q,schemaCode:W,schema:X}=w;if(Q||X&&typeof X=="object")w.fail$data(b9._`!${(0,hM.useFunc)(b,yM.default)}(${$}, ${W})`);else w.fail(b9._`${X} !== ${$}`)}};$7.default=fM});var X7=I((W7)=>{Object.defineProperty(W7,"__esModule",{value:!0});var Jb=f(),mM=d(),gM=C$(),lM={message:"must be equal to one of the allowed values",params:({schemaCode:w})=>Jb._`{allowedValues: ${w}}`},iM={keyword:"enum",schemaType:"array",$data:!0,error:lM,code(w){let{gen:b,data:$,$data:Q,schema:W,schemaCode:X,it:Y}=w;if(!Q&&W.length===0)throw Error("enum must have non-empty array");let G=W.length>=Y.opts.loopEnum,J,H=()=>J!==null&&J!==void 0?J:J=(0,mM.useFunc)(b,gM.default),z;if(G||Q)z=b.let("valid"),w.block$data(z,D);else{if(!Array.isArray(W))throw Error("ajv implementation error");let L=b.const("vSchema",X);z=(0,Jb.or)(...W.map((O,K)=>A(L,K)))}w.pass(z);function D(){b.assign(z,!1),b.forOf("v",X,(L)=>b.if(Jb._`${H()}(${$}, ${L})`,()=>b.assign(z,!0).break()))}function A(L,O){let K=W[O];return typeof K==="object"&&K!==null?Jb._`${H()}(${$}, ${L}[${O}])`:Jb._`${$} === ${K}`}}};W7.default=iM});var G7=I((Y7)=>{Object.defineProperty(Y7,"__esModule",{value:!0});var pM=hJ(),oM=uJ(),dM=lJ(),tM=nJ(),rM=oJ(),sM=tJ(),eM=sJ(),aM=b7(),wK=Q7(),bK=X7(),$K=[pM.default,oM.default,dM.default,tM.default,rM.default,sM.default,eM.default,aM.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},wK.default,bK.default];Y7.default=$K});var Q9=I((H7)=>{Object.defineProperty(H7,"__esModule",{value:!0});H7.validateAdditionalItems=void 0;var f1=f(),$9=d(),WK={message:({params:{len:w}})=>f1.str`must NOT have more than ${w} items`,params:({params:{len:w}})=>f1._`{limit: ${w}}`},XK={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:WK,code(w){let{parentSchema:b,it:$}=w,{items:Q}=b;if(!Array.isArray(Q)){(0,$9.checkStrictMode)($,'"additionalItems" is ignored when "items" is not an array of schemas');return}J7(w,Q)}};function J7(w,b){let{gen:$,schema:Q,data:W,keyword:X,it:Y}=w;Y.items=!0;let G=$.const("len",f1._`${W}.length`);if(Q===!1)w.setParams({len:b.length}),w.pass(f1._`${G} <= ${b.length}`);else if(typeof Q=="object"&&!(0,$9.alwaysValidSchema)(Y,Q)){let H=$.var("valid",f1._`${G} <= ${b.length}`);$.if((0,f1.not)(H),()=>J(H)),w.ok(H)}function J(H){$.forRange("i",b.length,G,(z)=>{if(w.subschema({keyword:X,dataProp:z,dataPropType:$9.Type.Num},H),!Y.allErrors)$.if((0,f1.not)(H),()=>$.break())})}}H7.validateAdditionalItems=J7;H7.default=XK});var W9=I((A7)=>{Object.defineProperty(A7,"__esModule",{value:!0});A7.validateTuple=void 0;var D7=f(),v$=d(),GK=hw(),JK={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,v$.alwaysValidSchema)($,b))return;w.ok((0,GK.validateArray)(w))}};function U7(w,b,$=w.schema){let{gen:Q,parentSchema:W,data:X,keyword:Y,it:G}=w;if(z(W),G.opts.unevaluated&&$.length&&G.items!==!0)G.items=v$.mergeEvaluated.items(Q,$.length,G.items);let J=Q.name("valid"),H=Q.const("len",D7._`${X}.length`);$.forEach((D,A)=>{if((0,v$.alwaysValidSchema)(G,D))return;Q.if(D7._`${H} > ${A}`,()=>w.subschema({keyword:Y,schemaProp:A,dataProp:A},J)),w.ok(J)});function z(D){let{opts:A,errSchemaPath:L}=G,O=$.length,K=O===D.minItems&&(O===D.maxItems||D[b]===!1);if(A.strictTuples&&!K){let j=`"${Y}" is ${O}-tuple, but minItems or maxItems/${b} are not specified or different at path "${L}"`;(0,v$.checkStrictMode)(G,j,A.strictTuples)}}}A7.validateTuple=U7;A7.default=JK});var B7=I((F7)=>{Object.defineProperty(F7,"__esModule",{value:!0});var zK=W9(),DK={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(w)=>(0,zK.validateTuple)(w,"items")};F7.default=DK});var K7=I((M7)=>{Object.defineProperty(M7,"__esModule",{value:!0});var O7=f(),AK=d(),LK=hw(),FK=Q9(),BK={message:({params:{len:w}})=>O7.str`must NOT have more than ${w} items`,params:({params:{len:w}})=>O7._`{limit: ${w}}`},OK={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:BK,code(w){let{schema:b,parentSchema:$,it:Q}=w,{prefixItems:W}=$;if(Q.items=!0,(0,AK.alwaysValidSchema)(Q,b))return;if(W)(0,FK.validateAdditionalItems)(w,W);else w.ok((0,LK.validateArray)(w))}};M7.default=OK});var Z7=I((q7)=>{Object.defineProperty(q7,"__esModule",{value:!0});var yw=f(),_$=d(),KK={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}}`},qK={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:KK,code(w){let{gen:b,schema:$,parentSchema:Q,data:W,it:X}=w,Y,G,{minContains:J,maxContains:H}=Q;if(X.opts.next)Y=J===void 0?1:J,G=H;else Y=1;let z=b.const("len",yw._`${W}.length`);if(w.setParams({min:Y,max:G}),G===void 0&&Y===0){(0,_$.checkStrictMode)(X,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(G!==void 0&&Y>G){(0,_$.checkStrictMode)(X,'"minContains" > "maxContains" is always invalid'),w.fail();return}if((0,_$.alwaysValidSchema)(X,$)){let K=yw._`${z} >= ${Y}`;if(G!==void 0)K=yw._`${K} && ${z} <= ${G}`;w.pass(K);return}X.items=!0;let D=b.name("valid");if(G===void 0&&Y===1)L(D,()=>b.if(D,()=>b.break()));else if(Y===0){if(b.let(D,!0),G!==void 0)b.if(yw._`${W}.length > 0`,A)}else b.let(D,!1),A();w.result(D,()=>w.reset());function A(){let K=b.name("_valid"),j=b.let("count",0);L(K,()=>b.if(K,()=>O(j)))}function L(K,j){b.forRange("i",0,z,(V)=>{w.subschema({keyword:"contains",dataProp:V,dataPropType:_$.Type.Num,compositeRule:!0},K),j()})}function O(K){if(b.code(yw._`${K}++`),G===void 0)b.if(yw._`${K} >= ${Y}`,()=>b.assign(D,!0).break());else if(b.if(yw._`${K} > ${G}`,()=>b.assign(D,!1).break()),Y===1)b.assign(D,!0);else b.if(yw._`${K} >= ${Y}`,()=>b.assign(D,!0))}}};q7.default=qK});var E7=I((j7)=>{Object.defineProperty(j7,"__esModule",{value:!0});j7.validateSchemaDeps=j7.validatePropertyDeps=j7.error=void 0;var X9=f(),PK=d(),Hb=hw();j7.error={message:({params:{property:w,depsCount:b,deps:$}})=>{let Q=b===1?"property":"properties";return X9.str`must have ${Q} ${$} when property ${w} is present`},params:({params:{property:w,depsCount:b,deps:$,missingProperty:Q}})=>X9._`{property: ${w},
|
|
7
|
+
missingProperty: ${Q},
|
|
8
8
|
depsCount: ${b},
|
|
9
|
-
deps: ${$}}`};var UM={keyword:"dependencies",type:"object",schemaType:"object",error:LH.error,code(w){let[b,$]=AM(w);UH(w,b),AH(w,$)}};function AM({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 UH(w,b=w.schema){let{gen:$,data:W,it:Q}=w;if(Object.keys(b).length===0)return;let G=$.let("missing");for(let X in b){let Y=b[X];if(Y.length===0)continue;let J=(0,Yb.propertyInData)($,W,X,Q.opts.ownProperties);if(w.setParams({property:X,depsCount:Y.length,deps:Y.join(", ")}),Q.allErrors)$.if(J,()=>{for(let H of Y)(0,Yb.checkReportMissingProp)(w,H)});else $.if(b9._`${J} && (${(0,Yb.checkMissingProp)(w,Y,G)})`),(0,Yb.reportMissingProp)(w,G),$.else()}}LH.validatePropertyDeps=UH;function AH(w,b=w.schema){let{gen:$,data:W,keyword:Q,it:G}=w,X=$.name("valid");for(let Y in b){if((0,DM.alwaysValidSchema)(G,b[Y]))continue;$.if((0,Yb.propertyInData)($,W,Y,G.opts.ownProperties),()=>{let J=w.subschema({keyword:Q,schemaProp:Y},X);w.mergeValidEvaluated(J,X)},()=>$.var(X,!0)),w.ok(X)}}LH.validateSchemaDeps=AH;LH.default=UM});var qH=I((MH)=>{Object.defineProperty(MH,"__esModule",{value:!0});var OH=f(),BM=d(),KM={message:"property name must be valid",params:({params:w})=>OH._`{propertyName: ${w.propertyName}}`},OM={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:KM,code(w){let{gen:b,schema:$,data:W,it:Q}=w;if((0,BM.alwaysValidSchema)(Q,$))return;let G=b.name("valid");b.forIn("key",W,(X)=>{w.setParams({propertyName:X}),w.subschema({keyword:"propertyNames",data:X,dataTypes:["string"],propertyName:X,compositeRule:!0},G),b.if((0,OH.not)(G),()=>{if(w.error(!0),!Q.allErrors)b.break()})}),w.ok(G)}};MH.default=OM});var $9=I((PH)=>{Object.defineProperty(PH,"__esModule",{value:!0});var v$=yw(),nw=f(),qM=Y1(),_$=d(),PM={message:"must NOT have additional properties",params:({params:w})=>nw._`{additionalProperty: ${w.additionalProperty}}`},ZM={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:PM,code(w){let{gen:b,schema:$,parentSchema:W,data:Q,errsCount:G,it:X}=w;if(!G)throw Error("ajv implementation error");let{allErrors:Y,opts:J}=X;if(X.props=!0,J.removeAdditional!=="all"&&(0,_$.alwaysValidSchema)(X,$))return;let H=(0,v$.allSchemaProperties)(W.properties),z=(0,v$.allSchemaProperties)(W.patternProperties);D(),w.ok(nw._`${G} === ${qM.default.errors}`);function D(){b.forIn("key",Q,(j)=>{if(!H.length&&!z.length)K(j);else b.if(A(j),()=>K(j))})}function A(j){let V;if(H.length>8){let C=(0,_$.schemaRefOrVal)(X,W.properties,"properties");V=(0,v$.isOwnProperty)(b,C,j)}else if(H.length)V=(0,nw.or)(...H.map((C)=>nw._`${j} === ${C}`));else V=nw.nil;if(z.length)V=(0,nw.or)(V,...z.map((C)=>nw._`${(0,v$.usePattern)(w,C)}.test(${j})`));return(0,nw.not)(V)}function L(j){b.code(nw._`delete ${Q}[${j}]`)}function K(j){if(J.removeAdditional==="all"||J.removeAdditional&&$===!1){L(j);return}if($===!1){if(w.setParams({additionalProperty:j}),w.error(),!Y)b.break();return}if(typeof $=="object"&&!(0,_$.alwaysValidSchema)(X,$)){let V=b.name("valid");if(J.removeAdditional==="failing")M(j,V,!1),b.if((0,nw.not)(V),()=>{w.reset(),L(j)});else if(M(j,V),!Y)b.if((0,nw.not)(V),()=>b.break())}}function M(j,V,C){let R={keyword:"additionalProperties",dataProp:j,dataPropType:_$.Type.Str};if(C===!1)Object.assign(R,{compositeRule:!0,createErrors:!1,allErrors:!1});w.subschema(R,V)}}};PH.default=ZM});var IH=I((jH)=>{Object.defineProperty(jH,"__esModule",{value:!0});var jM=t0(),ZH=yw(),W9=d(),VH=$9(),IM={keyword:"properties",type:"object",schemaType:"object",code(w){let{gen:b,schema:$,parentSchema:W,data:Q,it:G}=w;if(G.opts.removeAdditional==="all"&&W.additionalProperties===void 0)VH.default.code(new jM.KeywordCxt(G,VH.default,"additionalProperties"));let X=(0,ZH.allSchemaProperties)($);for(let D of X)G.definedProperties.add(D);if(G.opts.unevaluated&&X.length&&G.props!==!0)G.props=W9.mergeEvaluated.props(b,(0,W9.toHash)(X),G.props);let Y=X.filter((D)=>!(0,W9.alwaysValidSchema)(G,$[D]));if(Y.length===0)return;let J=b.name("valid");for(let D of Y){if(H(D))z(D);else{if(b.if((0,ZH.propertyInData)(b,Q,D,G.opts.ownProperties)),z(D),!G.allErrors)b.else().var(J,!0);b.endIf()}w.it.definedProperties.add(D),w.ok(J)}function H(D){return G.opts.useDefaults&&!G.compositeRule&&$[D].default!==void 0}function z(D){w.subschema({keyword:"properties",schemaProp:D,dataProp:D},J)}}};jH.default=IM});var SH=I((RH)=>{Object.defineProperty(RH,"__esModule",{value:!0});var NH=yw(),k$=f(),EH=d(),TH=d(),EM={keyword:"patternProperties",type:"object",schemaType:"object",code(w){let{gen:b,schema:$,data:W,parentSchema:Q,it:G}=w,{opts:X}=G,Y=(0,NH.allSchemaProperties)($),J=Y.filter((M)=>(0,EH.alwaysValidSchema)(G,$[M]));if(Y.length===0||J.length===Y.length&&(!G.opts.unevaluated||G.props===!0))return;let H=X.strictSchema&&!X.allowMatchingProperties&&Q.properties,z=b.name("valid");if(G.props!==!0&&!(G.props instanceof k$.Name))G.props=(0,TH.evaluatedPropsToName)(b,G.props);let{props:D}=G;A();function A(){for(let M of Y){if(H)L(M);if(G.allErrors)K(M);else b.var(z,!0),K(M),b.if(z)}}function L(M){for(let j in H)if(new RegExp(M).test(j))(0,EH.checkStrictMode)(G,`property ${j} matches pattern ${M} (use allowMatchingProperties)`)}function K(M){b.forIn("key",W,(j)=>{b.if(k$._`${(0,NH.usePattern)(w,M)}.test(${j})`,()=>{let V=J.includes(M);if(!V)w.subschema({keyword:"patternProperties",schemaProp:M,dataProp:j,dataPropType:TH.Type.Str},z);if(G.opts.unevaluated&&D!==!0)b.assign(k$._`${D}[${j}]`,!0);else if(!V&&!G.allErrors)b.if((0,k$.not)(z),()=>b.break())})})}}};RH.default=EM});var vH=I((CH)=>{Object.defineProperty(CH,"__esModule",{value:!0});var RM=d(),SM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(w){let{gen:b,schema:$,it:W}=w;if((0,RM.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"}};CH.default=SM});var kH=I((_H)=>{Object.defineProperty(_H,"__esModule",{value:!0});var vM=yw(),_M={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:vM.validateUnion,error:{message:"must match a schema in anyOf"}};_H.default=_M});var yH=I((xH)=>{Object.defineProperty(xH,"__esModule",{value:!0});var x$=f(),xM=d(),yM={message:"must match exactly one schema in oneOf",params:({params:w})=>x$._`{passingSchemas: ${w.passing}}`},hM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:yM,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 G=$,X=b.let("valid",!1),Y=b.let("passing",null),J=b.name("_valid");w.setParams({passing:Y}),b.block(H),w.result(X,()=>w.reset(),()=>w.error(!0));function H(){G.forEach((z,D)=>{let A;if((0,xM.alwaysValidSchema)(Q,z))b.var(J,!0);else A=w.subschema({keyword:"oneOf",schemaProp:D,compositeRule:!0},J);if(D>0)b.if(x$._`${J} && ${X}`).assign(X,!1).assign(Y,x$._`[${Y}, ${D}]`).else();b.if(J,()=>{if(b.assign(X,!0),b.assign(Y,D),A)w.mergeEvaluated(A,x$.Name)})})}}};xH.default=hM});var uH=I((hH)=>{Object.defineProperty(hH,"__esModule",{value:!0});var fM=d(),cM={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((G,X)=>{if((0,fM.alwaysValidSchema)(W,G))return;let Y=w.subschema({keyword:"allOf",schemaProp:X},Q);w.ok(Q),w.mergeEvaluated(Y)})}};hH.default=cM});var gH=I((mH)=>{Object.defineProperty(mH,"__esModule",{value:!0});var y$=f(),cH=d(),gM={message:({params:w})=>y$.str`must match "${w.ifClause}" schema`,params:({params:w})=>y$._`{failingKeyword: ${w.ifClause}}`},lM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:gM,code(w){let{gen:b,parentSchema:$,it:W}=w;if($.then===void 0&&$.else===void 0)(0,cH.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let Q=fH(W,"then"),G=fH(W,"else");if(!Q&&!G)return;let X=b.let("valid",!0),Y=b.name("_valid");if(J(),w.reset(),Q&&G){let z=b.let("ifClause");w.setParams({ifClause:z}),b.if(Y,H("then",z),H("else",z))}else if(Q)b.if(Y,H("then"));else b.if((0,y$.not)(Y),H("else"));w.pass(X,()=>w.error(!0));function J(){let z=w.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},Y);w.mergeEvaluated(z)}function H(z,D){return()=>{let A=w.subschema({keyword:z},Y);if(b.assign(X,Y),w.mergeValidEvaluated(A,X),D)b.assign(D,y$._`${z}`);else w.setParams({ifClause:z})}}}};function fH(w,b){let $=w.schema[b];return $!==void 0&&!(0,cH.alwaysValidSchema)(w,$)}mH.default=lM});var iH=I((lH)=>{Object.defineProperty(lH,"__esModule",{value:!0});var nM=d(),pM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:w,parentSchema:b,it:$}){if(b.if===void 0)(0,nM.checkStrictMode)($,`"${w}" without "if" is ignored`)}};lH.default=pM});var pH=I((nH)=>{Object.defineProperty(nH,"__esModule",{value:!0});var dM=a6(),tM=XH(),rM=w9(),sM=HH(),eM=DH(),aM=KH(),wq=qH(),bq=$9(),$q=IH(),Wq=SH(),Qq=vH(),Gq=kH(),Xq=yH(),Yq=uH(),Jq=gH(),Hq=iH();function zq(w=!1){let b=[Qq.default,Gq.default,Xq.default,Yq.default,Jq.default,Hq.default,wq.default,bq.default,aM.default,$q.default,Wq.default];if(w)b.push(tM.default,sM.default);else b.push(dM.default,rM.default);return b.push(eM.default),b}nH.default=zq});var dH=I((oH)=>{Object.defineProperty(oH,"__esModule",{value:!0});var Hw=f(),Uq={message:({schemaCode:w})=>Hw.str`must match format "${w}"`,params:({schemaCode:w})=>Hw._`{format: ${w}}`},Aq={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Uq,code(w,b){let{gen:$,data:W,$data:Q,schema:G,schemaCode:X,it:Y}=w,{opts:J,errSchemaPath:H,schemaEnv:z,self:D}=Y;if(!J.validateFormats)return;if(Q)A();else L();function A(){let K=$.scopeValue("formats",{ref:D.formats,code:J.code.formats}),M=$.const("fDef",Hw._`${K}[${X}]`),j=$.let("fType"),V=$.let("format");$.if(Hw._`typeof ${M} == "object" && !(${M} instanceof RegExp)`,()=>$.assign(j,Hw._`${M}.type || "string"`).assign(V,Hw._`${M}.validate`),()=>$.assign(j,Hw._`"string"`).assign(V,M)),w.fail$data((0,Hw.or)(C(),R()));function C(){if(J.strictSchema===!1)return Hw.nil;return Hw._`${X} && !${V}`}function R(){let m=z.$async?Hw._`(${M}.async ? await ${V}(${W}) : ${V}(${W}))`:Hw._`${V}(${W})`,_=Hw._`(typeof ${V} == "function" ? ${m} : ${V}.test(${W}))`;return Hw._`${V} && ${V} !== true && ${j} === ${b} && !${_}`}}function L(){let K=D.formats[G];if(!K){C();return}if(K===!0)return;let[M,j,V]=R(K);if(M===b)w.pass(m());function C(){if(J.strictSchema===!1){D.logger.warn(_());return}throw Error(_());function _(){return`unknown format "${G}" ignored in schema at path "${H}"`}}function R(_){let tw=_ instanceof RegExp?(0,Hw.regexpCode)(_):J.code.formats?Hw._`${J.code.formats}${(0,Hw.getProperty)(G)}`:void 0,b1=$.scopeValue("formats",{key:G,ref:_,code:tw});if(typeof _=="object"&&!(_ instanceof RegExp))return[_.type||"string",_.validate,Hw._`${b1}.validate`];return["string",_,b1]}function m(){if(typeof K=="object"&&!(K instanceof RegExp)&&K.async){if(!z.$async)throw Error("async format in sync schema");return Hw._`await ${V}(${W})`}return typeof j=="function"?Hw._`${V}(${W})`:Hw._`${V}.test(${W})`}}}};oH.default=Aq});var rH=I((tH)=>{Object.defineProperty(tH,"__esModule",{value:!0});var Fq=dH(),Bq=[Fq.default];tH.default=Bq});var aH=I((sH)=>{Object.defineProperty(sH,"__esModule",{value:!0});sH.contentVocabulary=sH.metadataVocabulary=void 0;sH.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];sH.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var $7=I((b7)=>{Object.defineProperty(b7,"__esModule",{value:!0});var Mq=jJ(),qq=sJ(),Pq=pH(),Zq=rH(),w7=aH(),Vq=[Mq.default,qq.default,(0,Pq.default)(),Zq.default,w7.metadataVocabulary,w7.contentVocabulary];b7.default=Vq});var X7=I((Q7)=>{Object.defineProperty(Q7,"__esModule",{value:!0});Q7.DiscrError=void 0;var W7;(function(w){w.Tag="tag",w.Mapping="mapping"})(W7||(Q7.DiscrError=W7={}))});var H7=I((J7)=>{Object.defineProperty(J7,"__esModule",{value:!0});var W0=f(),Q9=X7(),Y7=K$(),Iq=r0(),Nq=d(),Eq={message:({params:{discrError:w,tagName:b}})=>w===Q9.DiscrError.Tag?`tag "${b}" must be string`:`value of tag "${b}" must be in oneOf`,params:({params:{discrError:w,tag:b,tagName:$}})=>W0._`{error: ${w}, tag: ${$}, tagValue: ${b}}`},Tq={keyword:"discriminator",type:"object",schemaType:"object",error:Eq,code(w){let{gen:b,data:$,schema:W,parentSchema:Q,it:G}=w,{oneOf:X}=Q;if(!G.opts.discriminator)throw Error("discriminator: requires discriminator option");let Y=W.propertyName;if(typeof Y!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!X)throw Error("discriminator: requires oneOf keyword");let J=b.let("valid",!1),H=b.const("tag",W0._`${$}${(0,W0.getProperty)(Y)}`);b.if(W0._`typeof ${H} == "string"`,()=>z(),()=>w.error(!1,{discrError:Q9.DiscrError.Tag,tag:H,tagName:Y})),w.ok(J);function z(){let L=A();b.if(!1);for(let K in L)b.elseIf(W0._`${H} === ${K}`),b.assign(J,D(L[K]));b.else(),w.error(!1,{discrError:Q9.DiscrError.Mapping,tag:H,tagName:Y}),b.endIf()}function D(L){let K=b.name("valid"),M=w.subschema({keyword:"oneOf",schemaProp:L},K);return w.mergeEvaluated(M,W0.Name),K}function A(){var L;let K={},M=V(Q),j=!0;for(let m=0;m<X.length;m++){let _=X[m];if((_===null||_===void 0?void 0:_.$ref)&&!(0,Nq.schemaHasRulesButRef)(_,G.self.RULES)){let b1=_.$ref;if(_=Y7.resolveRef.call(G.self,G.schemaEnv.root,G.baseId,b1),_ instanceof Y7.SchemaEnv)_=_.schema;if(_===void 0)throw new Iq.default(G.opts.uriResolver,G.baseId,b1)}let tw=(L=_===null||_===void 0?void 0:_.properties)===null||L===void 0?void 0:L[Y];if(typeof tw!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${Y}"`);j=j&&(M||V(_)),C(tw,m)}if(!j)throw Error(`discriminator: "${Y}" must be required`);return K;function V({required:m}){return Array.isArray(m)&&m.includes(Y)}function C(m,_){if(m.const)R(m.const,_);else if(m.enum)for(let tw of m.enum)R(tw,_);else throw Error(`discriminator: "properties/${Y}" must have "const" or "enum"`)}function R(m,_){if(typeof m!="string"||m in K)throw Error(`discriminator: "${Y}" values must be unique strings`);K[m]=_}}}};J7.default=Tq});var z7=I((uR,Sq)=>{Sq.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 X9=I((Tw,G9)=>{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 Cq=LJ(),vq=$7(),_q=H7(),D7=z7(),kq=["/properties"],h$="http://json-schema.org/draft-07/schema";class Jb extends Cq.default{_addVocabularies(){if(super._addVocabularies(),vq.default.forEach((w)=>this.addVocabulary(w)),this.opts.discriminator)this.addKeyword(_q.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let w=this.opts.$data?this.$dataMetaSchema(D7,kq):D7;this.addMetaSchema(w,h$,!1),this.refs["http://json-schema.org/schema"]=h$}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(h$)?h$:void 0)}}Tw.Ajv=Jb;G9.exports=Tw=Jb;G9.exports.Ajv=Jb;Object.defineProperty(Tw,"__esModule",{value:!0});Tw.default=Jb;var xq=t0();Object.defineProperty(Tw,"KeywordCxt",{enumerable:!0,get:function(){return xq.KeywordCxt}});var Q0=f();Object.defineProperty(Tw,"_",{enumerable:!0,get:function(){return Q0._}});Object.defineProperty(Tw,"str",{enumerable:!0,get:function(){return Q0.str}});Object.defineProperty(Tw,"stringify",{enumerable:!0,get:function(){return Q0.stringify}});Object.defineProperty(Tw,"nil",{enumerable:!0,get:function(){return Q0.nil}});Object.defineProperty(Tw,"Name",{enumerable:!0,get:function(){return Q0.Name}});Object.defineProperty(Tw,"CodeGen",{enumerable:!0,get:function(){return Q0.CodeGen}});var yq=F$();Object.defineProperty(Tw,"ValidationError",{enumerable:!0,get:function(){return yq.default}});var hq=r0();Object.defineProperty(Tw,"MissingRefError",{enumerable:!0,get:function(){return hq.default}})});var P7=I((M7)=>{Object.defineProperty(M7,"__esModule",{value:!0});M7.formatNames=M7.fastFormats=M7.fullFormats=void 0;function aw(w,b){return{validate:w,compare:b}}M7.fullFormats={date:aw(F7,z9),time:aw(J9(!0),D9),"date-time":aw(U7(!0),K7),"iso-time":aw(J9(),B7),"iso-date-time":aw(U7(),O7),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:nq,"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:eq,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:pq,int32:{type:"number",validate:tq},int64:{type:"number",validate:rq},float:{type:"number",validate:L7},double:{type:"number",validate:L7},password:!0,binary:!0};M7.fastFormats={...M7.fullFormats,date:aw(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,z9),time:aw(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,D9),"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,K7),"iso-time":aw(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,B7),"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,O7),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};M7.formatNames=Object.keys(M7.fullFormats);function cq(w){return w%4===0&&(w%100!==0||w%400===0)}var mq=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,gq=[0,31,28,31,30,31,30,31,31,30,31,30,31];function F7(w){let b=mq.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&&cq($)?29:gq[W])}function z9(w,b){if(!(w&&b))return;if(w>b)return 1;if(w<b)return-1;return 0}var Y9=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function J9(w){return function($){let W=Y9.exec($);if(!W)return!1;let Q=+W[1],G=+W[2],X=+W[3],Y=W[4],J=W[5]==="-"?-1:1,H=+(W[6]||0),z=+(W[7]||0);if(H>23||z>59||w&&!Y)return!1;if(Q<=23&&G<=59&&X<60)return!0;let D=G-z*J,A=Q-H*J-(D<0?1:0);return(A===23||A===-1)&&(D===59||D===-1)&&X<61}}function D9(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 B7(w,b){if(!(w&&b))return;let $=Y9.exec(w),W=Y9.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 H9=/t|\s/i;function U7(w){let b=J9(w);return function(W){let Q=W.split(H9);return Q.length===2&&F7(Q[0])&&b(Q[1])}}function K7(w,b){if(!(w&&b))return;let $=new Date(w).valueOf(),W=new Date(b).valueOf();if(!($&&W))return;return $-W}function O7(w,b){if(!(w&&b))return;let[$,W]=w.split(H9),[Q,G]=b.split(H9),X=z9($,Q);if(X===void 0)return;return X||D9(W,G)}var lq=/\/|:/,iq=/^(?:[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 nq(w){return lq.test(w)&&iq.test(w)}var A7=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function pq(w){return A7.lastIndex=0,A7.test(w)}var oq=-2147483648,dq=2147483647;function tq(w){return Number.isInteger(w)&&w<=dq&&w>=oq}function rq(w){return Number.isInteger(w)}function L7(){return!0}var sq=/[^\\]\\Z/;function eq(w){if(sq.test(w))return!1;try{return new RegExp(w),!0}catch(b){return!1}}});var V7=I((Z7)=>{Object.defineProperty(Z7,"__esModule",{value:!0});Z7.formatLimitDefinition=void 0;var wP=X9(),pw=f(),S1=pw.operators,u$={formatMaximum:{okStr:"<=",ok:S1.LTE,fail:S1.GT},formatMinimum:{okStr:">=",ok:S1.GTE,fail:S1.LT},formatExclusiveMaximum:{okStr:"<",ok:S1.LT,fail:S1.GTE},formatExclusiveMinimum:{okStr:">",ok:S1.GT,fail:S1.LTE}},bP={message:({keyword:w,schemaCode:b})=>pw.str`should be ${u$[w].okStr} ${b}`,params:({keyword:w,schemaCode:b})=>pw._`{comparison: ${u$[w].okStr}, limit: ${b}}`};Z7.formatLimitDefinition={keyword:Object.keys(u$),type:"string",schemaType:"string",$data:!0,error:bP,code(w){let{gen:b,data:$,schemaCode:W,keyword:Q,it:G}=w,{opts:X,self:Y}=G;if(!X.validateFormats)return;let J=new wP.KeywordCxt(G,Y.RULES.all.format.definition,"format");if(J.$data)H();else z();function H(){let A=b.scopeValue("formats",{ref:Y.formats,code:X.code.formats}),L=b.const("fmt",pw._`${A}[${J.schemaCode}]`);w.fail$data((0,pw.or)(pw._`typeof ${L} != "object"`,pw._`${L} instanceof RegExp`,pw._`typeof ${L}.compare != "function"`,D(L)))}function z(){let A=J.schema,L=Y.formats[A];if(!L||L===!0)return;if(typeof L!="object"||L instanceof RegExp||typeof L.compare!="function")throw Error(`"${Q}": format "${A}" does not define "compare" function`);let K=b.scopeValue("formats",{key:A,ref:L,code:X.code.formats?pw._`${X.code.formats}${(0,pw.getProperty)(A)}`:void 0});w.fail$data(D(K))}function D(A){return pw._`${A}.compare(${$}, ${W}) ${u$[Q].fail} 0`}},dependencies:["format"]};var $P=(w)=>{return w.addKeyword(Z7.formatLimitDefinition),w};Z7.default=$P});var E7=I((Hb,N7)=>{Object.defineProperty(Hb,"__esModule",{value:!0});var G0=P7(),QP=V7(),L9=f(),j7=new L9.Name("fullFormats"),GP=new L9.Name("fastFormats"),F9=(w,b={keywords:!0})=>{if(Array.isArray(b))return I7(w,b,G0.fullFormats,j7),w;let[$,W]=b.mode==="fast"?[G0.fastFormats,GP]:[G0.fullFormats,j7],Q=b.formats||G0.formatNames;if(I7(w,Q,$,W),b.keywords)(0,QP.default)(w);return w};F9.get=(w,b="full")=>{let W=(b==="fast"?G0.fastFormats:G0.fullFormats)[w];if(!W)throw Error(`Unknown format "${w}"`);return W};function I7(w,b,$,W){var Q,G;(Q=(G=w.opts.code).formats)!==null&&Q!==void 0||(G.formats=L9._`require("ajv-formats/dist/formats").${W}`);for(let X of b)w.addFormat(X,$[X])}N7.exports=Hb=F9;Object.defineProperty(Hb,"__esModule",{value:!0});Hb.default=F9});import{AsyncLocalStorage as _5}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 S5(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 C5(w){let b=w.match(/api key is missing required scopes?:\s*(.+)$/i);if(!b?.[1])return[];return b[1].match(/[a-z_]+:[a-z_]+/gi)??[]}function v5(w){let b=S5(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 G=C5($);if(G.length>0){let X=G.map((J)=>`\`${J}\``).join(", "),Y=G.every((J)=>J.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 ${G.length===1?"scope":"scopes"}: ${X}.`,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 ${Y} including ${X}, 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 ${X}. 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 F1(w){let b=v5(w);return[`Sequenzy MCP error: ${b.title}`,`Description: ${b.description}`,`How to fix: ${b.howToFix}`,`Docs: ${b.docsUrl}`,`Details: ${b.details}`].join(`
|
|
10
|
-
`)}var k5="https://api.sequenzy.com",x5=new Set(["/api/v1/media/upload-bytes","/v1/media/upload-bytes"]),F0=new _5,wW=!1;function bW(){wW=!0}function Kb(){return wW}var $W=null;function B1(){let w=F0.getStore();if(w)return w.selectedCompanyId??null;return $W}function Ob(w){let b=F0.getStore();if(b){b.selectedCompanyId=w;return}$W=w}function X4(w,b){return F0.run(w,b)}function WW(){return F0.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??k5}function QW(){return F0.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function GW(w,b){let $=QW();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??B1();if(Q)W["x-company-id"]=Q;return W}function XW(){if(QW())return;console.error(F1(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 y5(w){if(w===void 0)return;if(typeof w==="string")return w.trim()||void 0;return JSON.stringify(w)}function YW(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,G=Rw(b,"howToFix")??Rw(b,"resolution"),X={...Rw(b,"title")?{title:Rw(b,"title")}:{},...Rw(b,"description")?{description:Rw(b,"description")}:{},...G?{howToFix:G}:{},...Rw(b,"docsUrl")?{docsUrl:Rw(b,"docsUrl")}:{}},Y=y5(b.details);if(Object.keys(X).length>0||Y)return{message:Q,...W?{code:W}:{},...Y?{details:Y}:{},...Object.keys(X).length>0?{context:X}:{}};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 U(w,b,$,W){let Q=GW("application/json",W),G;try{G=await fetch(`${WW()}${b}`,{method:w,headers:Q,body:$?JSON.stringify($):void 0})}catch(X){throw new rw(X instanceof Error?X.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!G.ok){let X=await G.text(),Y=YW(X);throw new rw(Y.message,G.status,Y.details??X,Y.code,Y.context)}return G.json()}async function JW(w,b,$,W){let Q=new URL(WW()).origin,G=new URL(w,`${Q}/`);if(G.origin!==Q){if(!x5.has(G.pathname))throw new rw("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");G=new URL(`${G.pathname}${G.search}`,`${Q}/`)}let X;try{X=await fetch(G,{method:"PUT",headers:GW($,W),body:b})}catch(Y){throw new rw(Y instanceof Error?Y.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!X.ok){let Y=await X.text(),J=YW(Y);throw new rw(J.message,X.status,J.details??Y,J.code,J.context)}}var IZ=Object.freeze({status:"aborted"});function O(w,b,$){function W(Y,J){var H;Object.defineProperty(Y,"_zod",{value:Y._zod??{},enumerable:!1}),(H=Y._zod).traits??(H.traits=new Set),Y._zod.traits.add(w),b(Y,J);for(let z in X.prototype)if(!(z in Y))Object.defineProperty(Y,z,{value:X.prototype[z].bind(Y)});Y._zod.constr=X,Y._zod.def=J}let Q=$?.Parent??Object;class G extends Q{}Object.defineProperty(G,"name",{value:w});function X(Y){var J;let H=$?.Parent?new G:this;W(H,Y),(J=H._zod).deferred??(J.deferred=[]);for(let z of H._zod.deferred)z();return H}return Object.defineProperty(X,"init",{value:W}),Object.defineProperty(X,Symbol.hasInstance,{value:(Y)=>{if($?.Parent&&Y instanceof $.Parent)return!0;return Y?._zod?.traits?.has(w)}}),Object.defineProperty(X,"name",{value:w}),X}var NZ=Symbol("zod_brand");class $1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class B0 extends Error{constructor(w){super(`Encountered unidirectional transform during encode: ${w}`);this.name="ZodEncodeError"}}var Mb={};function _w(w){if(w)Object.assign(Mb,w);return Mb}var o={};a9(o,{unwrapMessage:()=>K0,uint8ArrayToHex:()=>YD,uint8ArrayToBase64url:()=>GD,uint8ArrayToBase64:()=>FW,stringifyPrimitive:()=>Vb,shallowClone:()=>zW,safeExtend:()=>a5,required:()=>$D,randomString:()=>p5,propertyKeyTypes:()=>D4,promiseAllObject:()=>n5,primitiveTypes:()=>DW,prefixIssues:()=>Q1,pick:()=>r5,partial:()=>bD,optionalKeys:()=>U4,omit:()=>s5,objectClone:()=>g5,numKeys:()=>o5,nullish:()=>O0,normalizeParams:()=>S,mergeDefs:()=>O1,merge:()=>wD,jsonStringifyReplacer:()=>m1,joinValues:()=>qb,issue:()=>l1,isPlainObject:()=>M1,isObject:()=>v1,hexToUint8Array:()=>XD,getSizableOrigin:()=>AW,getParsedType:()=>d5,getLengthableOrigin:()=>q0,getEnumValues:()=>J4,getElementAtPath:()=>i5,floatSafeRemainder:()=>H4,finalizeIssue:()=>cw,extend:()=>e5,escapeRegex:()=>W1,esc:()=>Pb,defineLazy:()=>r,createTransparentProxy:()=>t5,cloneDef:()=>l5,clone:()=>fw,cleanRegex:()=>M0,cleanEnum:()=>WD,captureStackTrace:()=>Zb,cached:()=>g1,base64urlToUint8Array:()=>QD,base64ToUint8Array:()=>LW,assignProp:()=>K1,assertNotEqual:()=>u5,assertNever:()=>c5,assertIs:()=>f5,assertEqual:()=>h5,assert:()=>m5,allowsEval:()=>z4,aborted:()=>q1,NUMBER_FORMAT_RANGES:()=>A4,Class:()=>BW,BIGINT_FORMAT_RANGES:()=>UW});function h5(w){return w}function u5(w){return w}function f5(w){}function c5(w){throw Error()}function m5(w){}function J4(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 qb(w,b="|"){return w.map(($)=>Vb($)).join(b)}function m1(w,b){if(typeof b==="bigint")return b.toString();return b}function g1(w){return{get value(){{let $=w();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function O0(w){return w===null||w===void 0}function M0(w){let b=w.startsWith("^")?1:0,$=w.endsWith("$")?w.length-1:w.length;return w.slice(b,$)}function H4(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 J=W.match(/\d?e-(\d?)/);if(J?.[1])Q=Number.parseInt(J[1])}let G=$>Q?$:Q,X=Number.parseInt(w.toFixed(G).replace(".","")),Y=Number.parseInt(b.toFixed(G).replace(".",""));return X%Y/10**G}var HW=Symbol("evaluating");function r(w,b,$){let W=void 0;Object.defineProperty(w,b,{get(){if(W===HW)return;if(W===void 0)W=HW,W=$();return W},set(Q){Object.defineProperty(w,b,{value:Q})},configurable:!0})}function g5(w){return Object.create(Object.getPrototypeOf(w),Object.getOwnPropertyDescriptors(w))}function K1(w,b,$){Object.defineProperty(w,b,{value:$,writable:!0,enumerable:!0,configurable:!0})}function O1(...w){let b={};for(let $ of w){let W=Object.getOwnPropertyDescriptors($);Object.assign(b,W)}return Object.defineProperties({},b)}function l5(w){return O1(w._zod.def)}function i5(w,b){if(!b)return w;return b.reduce(($,W)=>$?.[W],w)}function n5(w){let b=Object.keys(w),$=b.map((W)=>w[W]);return Promise.all($).then((W)=>{let Q={};for(let G=0;G<b.length;G++)Q[b[G]]=W[G];return Q})}function p5(w=10){let $="";for(let W=0;W<w;W++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function Pb(w){return JSON.stringify(w)}var Zb="captureStackTrace"in Error?Error.captureStackTrace:(...w)=>{};function v1(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}var z4=g1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(w){return!1}});function M1(w){if(v1(w)===!1)return!1;let b=w.constructor;if(b===void 0)return!0;let $=b.prototype;if(v1($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function zW(w){if(M1(w))return{...w};if(Array.isArray(w))return[...w];return w}function o5(w){let b=0;for(let $ in w)if(Object.prototype.hasOwnProperty.call(w,$))b++;return b}var d5=(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}`)}},D4=new Set(["string","number","symbol"]),DW=new Set(["string","number","bigint","boolean","symbol","undefined"]);function W1(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 S(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 t5(w){let b;return new Proxy({},{get($,W,Q){return b??(b=w()),Reflect.get(b,W,Q)},set($,W,Q,G){return b??(b=w()),Reflect.set(b,W,Q,G)},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 U4(w){return Object.keys(w).filter((b)=>{return w[b]._zod.optin==="optional"&&w[b]._zod.optout==="optional"})}var A4={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]},UW={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function r5(w,b){let $=w._zod.def,W=O1(w._zod.def,{get shape(){let Q={};for(let G in b){if(!(G in $.shape))throw Error(`Unrecognized key: "${G}"`);if(!b[G])continue;Q[G]=$.shape[G]}return K1(this,"shape",Q),Q},checks:[]});return fw(w,W)}function s5(w,b){let $=w._zod.def,W=O1(w._zod.def,{get shape(){let Q={...w._zod.def.shape};for(let G in b){if(!(G in $.shape))throw Error(`Unrecognized key: "${G}"`);if(!b[G])continue;delete Q[G]}return K1(this,"shape",Q),Q},checks:[]});return fw(w,W)}function e5(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=O1(w._zod.def,{get shape(){let G={...w._zod.def.shape,...b};return K1(this,"shape",G),G},checks:[]});return fw(w,Q)}function a5(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 K1(this,"shape",W),W},checks:w._zod.def.checks};return fw(w,$)}function wD(w,b){let $=O1(w._zod.def,{get shape(){let W={...w._zod.def.shape,...b._zod.def.shape};return K1(this,"shape",W),W},get catchall(){return b._zod.def.catchall},checks:[]});return fw(w,$)}function bD(w,b,$){let W=O1(b._zod.def,{get shape(){let Q=b._zod.def.shape,G={...Q};if($)for(let X in $){if(!(X in Q))throw Error(`Unrecognized key: "${X}"`);if(!$[X])continue;G[X]=w?new w({type:"optional",innerType:Q[X]}):Q[X]}else for(let X in Q)G[X]=w?new w({type:"optional",innerType:Q[X]}):Q[X];return K1(this,"shape",G),G},checks:[]});return fw(b,W)}function $D(w,b,$){let W=O1(b._zod.def,{get shape(){let Q=b._zod.def.shape,G={...Q};if($)for(let X in $){if(!(X in G))throw Error(`Unrecognized key: "${X}"`);if(!$[X])continue;G[X]=new w({type:"nonoptional",innerType:Q[X]})}else for(let X in Q)G[X]=new w({type:"nonoptional",innerType:Q[X]});return K1(this,"shape",G),G},checks:[]});return fw(b,W)}function q1(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 Q1(w,b){return b.map(($)=>{var W;return(W=$).path??(W.path=[]),$.path.unshift(w),$})}function K0(w){return typeof w==="string"?w:w?.message}function cw(w,b,$){let W={...w,path:w.path??[]};if(!w.message){let Q=K0(w.inst?._zod.def?.error?.(w))??K0(b?.error?.(w))??K0($.customError?.(w))??K0($.localeError?.(w))??"Invalid input";W.message=Q}if(delete W.inst,delete W.continue,!b?.reportInput)delete W.input;return W}function AW(w){if(w instanceof Set)return"set";if(w instanceof Map)return"map";if(w instanceof File)return"file";return"unknown"}function q0(w){if(Array.isArray(w))return"array";if(typeof w==="string")return"string";return"unknown"}function l1(...w){let[b,$,W]=w;if(typeof b==="string")return{message:b,code:"custom",input:$,inst:W};return{...b}}function WD(w){return Object.entries(w).filter(([b,$])=>{return Number.isNaN(Number.parseInt(b,10))}).map((b)=>b[1])}function LW(w){let b=atob(w),$=new Uint8Array(b.length);for(let W=0;W<b.length;W++)$[W]=b.charCodeAt(W);return $}function FW(w){let b="";for(let $=0;$<w.length;$++)b+=String.fromCharCode(w[$]);return btoa(b)}function QD(w){let b=w.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-b.length%4)%4);return LW(b+$)}function GD(w){return FW(w).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function XD(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 YD(w){return Array.from(w).map((b)=>b.toString(16).padStart(2,"0")).join("")}class BW{constructor(...w){}}var KW=(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,m1,2),Object.defineProperty(w,"toString",{value:()=>w.message,enumerable:!1})},jb=O("$ZodError",KW),L4=O("$ZodError",KW,{Parent:Error});function OW(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 MW(w,b=($)=>$.message){let $={_errors:[]},W=(Q)=>{for(let G of Q.issues)if(G.code==="invalid_union"&&G.errors.length)G.errors.map((X)=>W({issues:X}));else if(G.code==="invalid_key")W({issues:G.issues});else if(G.code==="invalid_element")W({issues:G.issues});else if(G.path.length===0)$._errors.push(b(G));else{let X=$,Y=0;while(Y<G.path.length){let J=G.path[Y];if(Y!==G.path.length-1)X[J]=X[J]||{_errors:[]};else X[J]=X[J]||{_errors:[]},X[J]._errors.push(b(G));X=X[J],Y++}}};return W(w),$}var Ib=(w)=>(b,$,W,Q)=>{let G=W?Object.assign(W,{async:!1}):{async:!1},X=b._zod.run({value:$,issues:[]},G);if(X instanceof Promise)throw new $1;if(X.issues.length){let Y=new(Q?.Err??w)(X.issues.map((J)=>cw(J,G,_w())));throw Zb(Y,Q?.callee),Y}return X.value};var Nb=(w)=>async(b,$,W,Q)=>{let G=W?Object.assign(W,{async:!0}):{async:!0},X=b._zod.run({value:$,issues:[]},G);if(X instanceof Promise)X=await X;if(X.issues.length){let Y=new(Q?.Err??w)(X.issues.map((J)=>cw(J,G,_w())));throw Zb(Y,Q?.callee),Y}return X.value};var P0=(w)=>(b,$,W)=>{let Q=W?{...W,async:!1}:{async:!1},G=b._zod.run({value:$,issues:[]},Q);if(G instanceof Promise)throw new $1;return G.issues.length?{success:!1,error:new(w??jb)(G.issues.map((X)=>cw(X,Q,_w())))}:{success:!0,data:G.value}},Z0=P0(L4),V0=(w)=>async(b,$,W)=>{let Q=W?Object.assign(W,{async:!0}):{async:!0},G=b._zod.run({value:$,issues:[]},Q);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new w(G.issues.map((X)=>cw(X,Q,_w())))}:{success:!0,data:G.value}},Eb=V0(L4),qW=(w)=>(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return Ib(w)(b,$,Q)};var PW=(w)=>(b,$,W)=>{return Ib(w)(b,$,W)};var ZW=(w)=>async(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return Nb(w)(b,$,Q)};var VW=(w)=>async(b,$,W)=>{return Nb(w)(b,$,W)};var jW=(w)=>(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return P0(w)(b,$,Q)};var IW=(w)=>(b,$,W)=>{return P0(w)(b,$,W)};var NW=(w)=>async(b,$,W)=>{let Q=W?Object.assign(W,{direction:"backward"}):{direction:"backward"};return V0(w)(b,$,Q)};var EW=(w)=>async(b,$,W)=>{return V0(w)(b,$,W)};var TW=/^[cC][^\s-]{8,}$/,RW=/^[0-9a-z]+$/,SW=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,CW=/^[0-9a-vA-V]{20}$/,vW=/^[A-Za-z0-9]{27}$/,_W=/^[a-zA-Z0-9_-]{21}$/,kW=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var xW=/^([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})$/,F4=(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 yW=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function hW(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var uW=/^(?:(?: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])$/,fW=/^(([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}|:))$/,cW=/^((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])$/,mW=/^(([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])$/,gW=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,B4=/^[A-Za-z0-9_-]*$/,lW=/^(?=.{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 iW=/^\+(?:[0-9]){6,14}[0-9]$/,nW="(?:(?:\\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])))",pW=new RegExp(`^${nW}$`);function oW(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 dW(w){return new RegExp(`^${oW(w)}$`)}function tW(w){let b=oW({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(`^${nW}T(?:${W})$`)}var rW=(w)=>{let b=w?`[\\s\\S]{${w?.minimum??0},${w?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${b}$`)};var sW=/^-?\d+$/,eW=/^-?\d+(?:\.\d+)?/,aW=/^(?:true|false)$/i,wQ=/^null$/i;var bQ=/^[^A-Z]*$/,$Q=/^[^a-z]*$/;var Aw=O("$ZodCheck",(w,b)=>{var $;w._zod??(w._zod={}),w._zod.def=b,($=w._zod).onattach??($.onattach=[])}),WQ={number:"number",bigint:"bigint",object:"date"},K4=O("$ZodCheckLessThan",(w,b)=>{Aw.init(w,b);let $=WQ[typeof b.value];w._zod.onattach.push((W)=>{let Q=W._zod.bag,G=(b.inclusive?Q.maximum:Q.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(b.value<G)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})}}),O4=O("$ZodCheckGreaterThan",(w,b)=>{Aw.init(w,b);let $=WQ[typeof b.value];w._zod.onattach.push((W)=>{let Q=W._zod.bag,G=(b.inclusive?Q.minimum:Q.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(b.value>G)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})}}),QQ=O("$ZodCheckMultipleOf",(w,b)=>{Aw.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):H4($.value,b.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:b.value,input:$.value,inst:w,continue:!b.abort})}}),GQ=O("$ZodCheckNumberFormat",(w,b)=>{Aw.init(w,b),b.format=b.format||"float64";let $=b.format?.includes("int"),W=$?"int":"number",[Q,G]=A4[b.format];w._zod.onattach.push((X)=>{let Y=X._zod.bag;if(Y.format=b.format,Y.minimum=Q,Y.maximum=G,$)Y.pattern=sW}),w._zod.check=(X)=>{let Y=X.value;if($){if(!Number.isInteger(Y)){X.issues.push({expected:W,format:b.format,code:"invalid_type",continue:!1,input:Y,inst:w});return}if(!Number.isSafeInteger(Y)){if(Y>0)X.issues.push({input:Y,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 X.issues.push({input:Y,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(Y<Q)X.issues.push({origin:"number",input:Y,code:"too_small",minimum:Q,inclusive:!0,inst:w,continue:!b.abort});if(Y>G)X.issues.push({origin:"number",input:Y,code:"too_big",maximum:G,inst:w})}});var XQ=O("$ZodCheckMaxLength",(w,b)=>{var $;Aw.init(w,b),($=w._zod.def).when??($.when=(W)=>{let Q=W.value;return!O0(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 X=q0(Q);W.issues.push({origin:X,code:"too_big",maximum:b.maximum,inclusive:!0,input:Q,inst:w,continue:!b.abort})}}),YQ=O("$ZodCheckMinLength",(w,b)=>{var $;Aw.init(w,b),($=w._zod.def).when??($.when=(W)=>{let Q=W.value;return!O0(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 X=q0(Q);W.issues.push({origin:X,code:"too_small",minimum:b.minimum,inclusive:!0,input:Q,inst:w,continue:!b.abort})}}),JQ=O("$ZodCheckLengthEquals",(w,b)=>{var $;Aw.init(w,b),($=w._zod.def).when??($.when=(W)=>{let Q=W.value;return!O0(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,G=Q.length;if(G===b.length)return;let X=q0(Q),Y=G>b.length;W.issues.push({origin:X,...Y?{code:"too_big",maximum:b.length}:{code:"too_small",minimum:b.length},inclusive:!0,exact:!0,input:W.value,inst:w,continue:!b.abort})}}),j0=O("$ZodCheckStringFormat",(w,b)=>{var $,W;if(Aw.init(w,b),w._zod.onattach.push((Q)=>{let G=Q._zod.bag;if(G.format=b.format,b.pattern)G.patterns??(G.patterns=new Set),G.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=()=>{})}),HQ=O("$ZodCheckRegex",(w,b)=>{j0.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})}}),zQ=O("$ZodCheckLowerCase",(w,b)=>{b.pattern??(b.pattern=bQ),j0.init(w,b)}),DQ=O("$ZodCheckUpperCase",(w,b)=>{b.pattern??(b.pattern=$Q),j0.init(w,b)}),UQ=O("$ZodCheckIncludes",(w,b)=>{Aw.init(w,b);let $=W1(b.includes),W=new RegExp(typeof b.position==="number"?`^.{${b.position}}${$}`:$);b.pattern=W,w._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.patterns??(G.patterns=new Set),G.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})}}),AQ=O("$ZodCheckStartsWith",(w,b)=>{Aw.init(w,b);let $=new RegExp(`^${W1(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})}}),LQ=O("$ZodCheckEndsWith",(w,b)=>{Aw.init(w,b);let $=new RegExp(`.*${W1(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 FQ=O("$ZodCheckOverwrite",(w,b)=>{Aw.init(w,b),w._zod.check=($)=>{$.value=b.tx($.value)}});class M4{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
|
-
`).filter((
|
|
12
|
-
`))}}var
|
|
9
|
+
deps: ${$}}`};var VK={keyword:"dependencies",type:"object",schemaType:"object",error:j7.error,code(w){let[b,$]=jK(w);P7(w,b),V7(w,$)}};function jK({schema:w}){let b={},$={};for(let Q in w){if(Q==="__proto__")continue;let W=Array.isArray(w[Q])?b:$;W[Q]=w[Q]}return[b,$]}function P7(w,b=w.schema){let{gen:$,data:Q,it:W}=w;if(Object.keys(b).length===0)return;let X=$.let("missing");for(let Y in b){let G=b[Y];if(G.length===0)continue;let J=(0,Hb.propertyInData)($,Q,Y,W.opts.ownProperties);if(w.setParams({property:Y,depsCount:G.length,deps:G.join(", ")}),W.allErrors)$.if(J,()=>{for(let H of G)(0,Hb.checkReportMissingProp)(w,H)});else $.if(X9._`${J} && (${(0,Hb.checkMissingProp)(w,G,X)})`),(0,Hb.reportMissingProp)(w,X),$.else()}}j7.validatePropertyDeps=P7;function V7(w,b=w.schema){let{gen:$,data:Q,keyword:W,it:X}=w,Y=$.name("valid");for(let G in b){if((0,PK.alwaysValidSchema)(X,b[G]))continue;$.if((0,Hb.propertyInData)($,Q,G,X.opts.ownProperties),()=>{let J=w.subschema({keyword:W,schemaProp:G},Y);w.mergeValidEvaluated(J,Y)},()=>$.var(Y,!0)),w.ok(Y)}}j7.validateSchemaDeps=V7;j7.default=VK});var S7=I((R7)=>{Object.defineProperty(R7,"__esModule",{value:!0});var T7=f(),EK=d(),TK={message:"property name must be valid",params:({params:w})=>T7._`{propertyName: ${w.propertyName}}`},RK={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:TK,code(w){let{gen:b,schema:$,data:Q,it:W}=w;if((0,EK.alwaysValidSchema)(W,$))return;let X=b.name("valid");b.forIn("key",Q,(Y)=>{w.setParams({propertyName:Y}),w.subschema({keyword:"propertyNames",data:Y,dataTypes:["string"],propertyName:Y,compositeRule:!0},X),b.if((0,T7.not)(X),()=>{if(w.error(!0),!W.allErrors)b.break()})}),w.ok(X)}};R7.default=RK});var Y9=I((C7)=>{Object.defineProperty(C7,"__esModule",{value:!0});var k$=hw(),nw=f(),CK=G1(),x$=d(),vK={message:"must NOT have additional properties",params:({params:w})=>nw._`{additionalProperty: ${w.additionalProperty}}`},_K={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:vK,code(w){let{gen:b,schema:$,parentSchema:Q,data:W,errsCount:X,it:Y}=w;if(!X)throw Error("ajv implementation error");let{allErrors:G,opts:J}=Y;if(Y.props=!0,J.removeAdditional!=="all"&&(0,x$.alwaysValidSchema)(Y,$))return;let H=(0,k$.allSchemaProperties)(Q.properties),z=(0,k$.allSchemaProperties)(Q.patternProperties);D(),w.ok(nw._`${X} === ${CK.default.errors}`);function D(){b.forIn("key",W,(j)=>{if(!H.length&&!z.length)O(j);else b.if(A(j),()=>O(j))})}function A(j){let V;if(H.length>8){let _=(0,x$.schemaRefOrVal)(Y,Q.properties,"properties");V=(0,k$.isOwnProperty)(b,_,j)}else if(H.length)V=(0,nw.or)(...H.map((_)=>nw._`${j} === ${_}`));else V=nw.nil;if(z.length)V=(0,nw.or)(V,...z.map((_)=>nw._`${(0,k$.usePattern)(w,_)}.test(${j})`));return(0,nw.not)(V)}function L(j){b.code(nw._`delete ${W}[${j}]`)}function O(j){if(J.removeAdditional==="all"||J.removeAdditional&&$===!1){L(j);return}if($===!1){if(w.setParams({additionalProperty:j}),w.error(),!G)b.break();return}if(typeof $=="object"&&!(0,x$.alwaysValidSchema)(Y,$)){let V=b.name("valid");if(J.removeAdditional==="failing")K(j,V,!1),b.if((0,nw.not)(V),()=>{w.reset(),L(j)});else if(K(j,V),!G)b.if((0,nw.not)(V),()=>b.break())}}function K(j,V,_){let R={keyword:"additionalProperties",dataProp:j,dataPropType:x$.Type.Str};if(_===!1)Object.assign(R,{compositeRule:!0,createErrors:!1,allErrors:!1});w.subschema(R,V)}}};C7.default=_K});var x7=I((k7)=>{Object.defineProperty(k7,"__esModule",{value:!0});var xK=s0(),v7=hw(),G9=d(),_7=Y9(),hK={keyword:"properties",type:"object",schemaType:"object",code(w){let{gen:b,schema:$,parentSchema:Q,data:W,it:X}=w;if(X.opts.removeAdditional==="all"&&Q.additionalProperties===void 0)_7.default.code(new xK.KeywordCxt(X,_7.default,"additionalProperties"));let Y=(0,v7.allSchemaProperties)($);for(let D of Y)X.definedProperties.add(D);if(X.opts.unevaluated&&Y.length&&X.props!==!0)X.props=G9.mergeEvaluated.props(b,(0,G9.toHash)(Y),X.props);let G=Y.filter((D)=>!(0,G9.alwaysValidSchema)(X,$[D]));if(G.length===0)return;let J=b.name("valid");for(let D of G){if(H(D))z(D);else{if(b.if((0,v7.propertyInData)(b,W,D,X.opts.ownProperties)),z(D),!X.allErrors)b.else().var(J,!0);b.endIf()}w.it.definedProperties.add(D),w.ok(J)}function H(D){return X.opts.useDefaults&&!X.compositeRule&&$[D].default!==void 0}function z(D){w.subschema({keyword:"properties",schemaProp:D,dataProp:D},J)}}};k7.default=hK});var c7=I((f7)=>{Object.defineProperty(f7,"__esModule",{value:!0});var h7=hw(),h$=f(),y7=d(),u7=d(),uK={keyword:"patternProperties",type:"object",schemaType:"object",code(w){let{gen:b,schema:$,data:Q,parentSchema:W,it:X}=w,{opts:Y}=X,G=(0,h7.allSchemaProperties)($),J=G.filter((K)=>(0,y7.alwaysValidSchema)(X,$[K]));if(G.length===0||J.length===G.length&&(!X.opts.unevaluated||X.props===!0))return;let H=Y.strictSchema&&!Y.allowMatchingProperties&&W.properties,z=b.name("valid");if(X.props!==!0&&!(X.props instanceof h$.Name))X.props=(0,u7.evaluatedPropsToName)(b,X.props);let{props:D}=X;A();function A(){for(let K of G){if(H)L(K);if(X.allErrors)O(K);else b.var(z,!0),O(K),b.if(z)}}function L(K){for(let j in H)if(new RegExp(K).test(j))(0,y7.checkStrictMode)(X,`property ${j} matches pattern ${K} (use allowMatchingProperties)`)}function O(K){b.forIn("key",Q,(j)=>{b.if(h$._`${(0,h7.usePattern)(w,K)}.test(${j})`,()=>{let V=J.includes(K);if(!V)w.subschema({keyword:"patternProperties",schemaProp:K,dataProp:j,dataPropType:u7.Type.Str},z);if(X.opts.unevaluated&&D!==!0)b.assign(h$._`${D}[${j}]`,!0);else if(!V&&!X.allErrors)b.if((0,h$.not)(z),()=>b.break())})})}}};f7.default=uK});var g7=I((m7)=>{Object.defineProperty(m7,"__esModule",{value:!0});var cK=d(),mK={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(w){let{gen:b,schema:$,it:Q}=w;if((0,cK.alwaysValidSchema)(Q,$)){w.fail();return}let W=b.name("valid");w.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},W),w.failResult(W,()=>w.reset(),()=>w.error())},error:{message:"must NOT be valid"}};m7.default=mK});var i7=I((l7)=>{Object.defineProperty(l7,"__esModule",{value:!0});var lK=hw(),iK={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:lK.validateUnion,error:{message:"must match a schema in anyOf"}};l7.default=iK});var p7=I((n7)=>{Object.defineProperty(n7,"__esModule",{value:!0});var y$=f(),pK=d(),oK={message:"must match exactly one schema in oneOf",params:({params:w})=>y$._`{passingSchemas: ${w.passing}}`},dK={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:oK,code(w){let{gen:b,schema:$,parentSchema:Q,it:W}=w;if(!Array.isArray($))throw Error("ajv implementation error");if(W.opts.discriminator&&Q.discriminator)return;let X=$,Y=b.let("valid",!1),G=b.let("passing",null),J=b.name("_valid");w.setParams({passing:G}),b.block(H),w.result(Y,()=>w.reset(),()=>w.error(!0));function H(){X.forEach((z,D)=>{let A;if((0,pK.alwaysValidSchema)(W,z))b.var(J,!0);else A=w.subschema({keyword:"oneOf",schemaProp:D,compositeRule:!0},J);if(D>0)b.if(y$._`${J} && ${Y}`).assign(Y,!1).assign(G,y$._`[${G}, ${D}]`).else();b.if(J,()=>{if(b.assign(Y,!0),b.assign(G,D),A)w.mergeEvaluated(A,y$.Name)})})}}};n7.default=dK});var d7=I((o7)=>{Object.defineProperty(o7,"__esModule",{value:!0});var rK=d(),sK={keyword:"allOf",schemaType:"array",code(w){let{gen:b,schema:$,it:Q}=w;if(!Array.isArray($))throw Error("ajv implementation error");let W=b.name("valid");$.forEach((X,Y)=>{if((0,rK.alwaysValidSchema)(Q,X))return;let G=w.subschema({keyword:"allOf",schemaProp:Y},W);w.ok(W),w.mergeEvaluated(G)})}};o7.default=sK});var e7=I((s7)=>{Object.defineProperty(s7,"__esModule",{value:!0});var u$=f(),r7=d(),aK={message:({params:w})=>u$.str`must match "${w.ifClause}" schema`,params:({params:w})=>u$._`{failingKeyword: ${w.ifClause}}`},wq={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:aK,code(w){let{gen:b,parentSchema:$,it:Q}=w;if($.then===void 0&&$.else===void 0)(0,r7.checkStrictMode)(Q,'"if" without "then" and "else" is ignored');let W=t7(Q,"then"),X=t7(Q,"else");if(!W&&!X)return;let Y=b.let("valid",!0),G=b.name("_valid");if(J(),w.reset(),W&&X){let z=b.let("ifClause");w.setParams({ifClause:z}),b.if(G,H("then",z),H("else",z))}else if(W)b.if(G,H("then"));else b.if((0,u$.not)(G),H("else"));w.pass(Y,()=>w.error(!0));function J(){let z=w.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},G);w.mergeEvaluated(z)}function H(z,D){return()=>{let A=w.subschema({keyword:z},G);if(b.assign(Y,G),w.mergeValidEvaluated(A,Y),D)b.assign(D,u$._`${z}`);else w.setParams({ifClause:z})}}}};function t7(w,b){let $=w.schema[b];return $!==void 0&&!(0,r7.alwaysValidSchema)(w,$)}s7.default=wq});var wH=I((a7)=>{Object.defineProperty(a7,"__esModule",{value:!0});var $q=d(),Qq={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:w,parentSchema:b,it:$}){if(b.if===void 0)(0,$q.checkStrictMode)($,`"${w}" without "if" is ignored`)}};a7.default=Qq});var $H=I((bH)=>{Object.defineProperty(bH,"__esModule",{value:!0});var Xq=Q9(),Yq=B7(),Gq=W9(),Jq=K7(),Hq=Z7(),zq=E7(),Dq=S7(),Uq=Y9(),Aq=x7(),Lq=c7(),Fq=g7(),Bq=i7(),Oq=p7(),Mq=d7(),Kq=e7(),qq=wH();function Zq(w=!1){let b=[Fq.default,Bq.default,Oq.default,Mq.default,Kq.default,qq.default,Dq.default,Uq.default,zq.default,Aq.default,Lq.default];if(w)b.push(Yq.default,Jq.default);else b.push(Xq.default,Gq.default);return b.push(Hq.default),b}bH.default=Zq});var WH=I((QH)=>{Object.defineProperty(QH,"__esModule",{value:!0});var Hw=f(),Vq={message:({schemaCode:w})=>Hw.str`must match format "${w}"`,params:({schemaCode:w})=>Hw._`{format: ${w}}`},jq={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Vq,code(w,b){let{gen:$,data:Q,$data:W,schema:X,schemaCode:Y,it:G}=w,{opts:J,errSchemaPath:H,schemaEnv:z,self:D}=G;if(!J.validateFormats)return;if(W)A();else L();function A(){let O=$.scopeValue("formats",{ref:D.formats,code:J.code.formats}),K=$.const("fDef",Hw._`${O}[${Y}]`),j=$.let("fType"),V=$.let("format");$.if(Hw._`typeof ${K} == "object" && !(${K} instanceof RegExp)`,()=>$.assign(j,Hw._`${K}.type || "string"`).assign(V,Hw._`${K}.validate`),()=>$.assign(j,Hw._`"string"`).assign(V,K)),w.fail$data((0,Hw.or)(_(),R()));function _(){if(J.strictSchema===!1)return Hw.nil;return Hw._`${Y} && !${V}`}function R(){let m=z.$async?Hw._`(${K}.async ? await ${V}(${Q}) : ${V}(${Q}))`:Hw._`${V}(${Q})`,k=Hw._`(typeof ${V} == "function" ? ${m} : ${V}.test(${Q}))`;return Hw._`${V} && ${V} !== true && ${j} === ${b} && !${k}`}}function L(){let O=D.formats[X];if(!O){_();return}if(O===!0)return;let[K,j,V]=R(O);if(K===b)w.pass(m());function _(){if(J.strictSchema===!1){D.logger.warn(k());return}throw Error(k());function k(){return`unknown format "${X}" ignored in schema at path "${H}"`}}function R(k){let tw=k instanceof RegExp?(0,Hw.regexpCode)(k):J.code.formats?Hw._`${J.code.formats}${(0,Hw.getProperty)(X)}`:void 0,b1=$.scopeValue("formats",{key:X,ref:k,code:tw});if(typeof k=="object"&&!(k instanceof RegExp))return[k.type||"string",k.validate,Hw._`${b1}.validate`];return["string",k,b1]}function m(){if(typeof O=="object"&&!(O instanceof RegExp)&&O.async){if(!z.$async)throw Error("async format in sync schema");return Hw._`await ${V}(${Q})`}return typeof j=="function"?Hw._`${V}(${Q})`:Hw._`${V}.test(${Q})`}}}};QH.default=jq});var YH=I((XH)=>{Object.defineProperty(XH,"__esModule",{value:!0});var Nq=WH(),Eq=[Nq.default];XH.default=Eq});var HH=I((GH)=>{Object.defineProperty(GH,"__esModule",{value:!0});GH.contentVocabulary=GH.metadataVocabulary=void 0;GH.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];GH.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var UH=I((DH)=>{Object.defineProperty(DH,"__esModule",{value:!0});var Sq=kJ(),Cq=G7(),vq=$H(),_q=YH(),zH=HH(),kq=[Sq.default,Cq.default,(0,vq.default)(),_q.default,zH.metadataVocabulary,zH.contentVocabulary];DH.default=kq});var BH=I((LH)=>{Object.defineProperty(LH,"__esModule",{value:!0});LH.DiscrError=void 0;var AH;(function(w){w.Tag="tag",w.Mapping="mapping"})(AH||(LH.DiscrError=AH={}))});var KH=I((MH)=>{Object.defineProperty(MH,"__esModule",{value:!0});var W0=f(),J9=BH(),OH=K$(),hq=e0(),yq=d(),uq={message:({params:{discrError:w,tagName:b}})=>w===J9.DiscrError.Tag?`tag "${b}" must be string`:`value of tag "${b}" must be in oneOf`,params:({params:{discrError:w,tag:b,tagName:$}})=>W0._`{error: ${w}, tag: ${$}, tagValue: ${b}}`},fq={keyword:"discriminator",type:"object",schemaType:"object",error:uq,code(w){let{gen:b,data:$,schema:Q,parentSchema:W,it:X}=w,{oneOf:Y}=W;if(!X.opts.discriminator)throw Error("discriminator: requires discriminator option");let G=Q.propertyName;if(typeof G!="string")throw Error("discriminator: requires propertyName");if(Q.mapping)throw Error("discriminator: mapping is not supported");if(!Y)throw Error("discriminator: requires oneOf keyword");let J=b.let("valid",!1),H=b.const("tag",W0._`${$}${(0,W0.getProperty)(G)}`);b.if(W0._`typeof ${H} == "string"`,()=>z(),()=>w.error(!1,{discrError:J9.DiscrError.Tag,tag:H,tagName:G})),w.ok(J);function z(){let L=A();b.if(!1);for(let O in L)b.elseIf(W0._`${H} === ${O}`),b.assign(J,D(L[O]));b.else(),w.error(!1,{discrError:J9.DiscrError.Mapping,tag:H,tagName:G}),b.endIf()}function D(L){let O=b.name("valid"),K=w.subschema({keyword:"oneOf",schemaProp:L},O);return w.mergeEvaluated(K,W0.Name),O}function A(){var L;let O={},K=V(W),j=!0;for(let m=0;m<Y.length;m++){let k=Y[m];if((k===null||k===void 0?void 0:k.$ref)&&!(0,yq.schemaHasRulesButRef)(k,X.self.RULES)){let b1=k.$ref;if(k=OH.resolveRef.call(X.self,X.schemaEnv.root,X.baseId,b1),k instanceof OH.SchemaEnv)k=k.schema;if(k===void 0)throw new hq.default(X.opts.uriResolver,X.baseId,b1)}let tw=(L=k===null||k===void 0?void 0:k.properties)===null||L===void 0?void 0:L[G];if(typeof tw!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${G}"`);j=j&&(K||V(k)),_(tw,m)}if(!j)throw Error(`discriminator: "${G}" must be required`);return O;function V({required:m}){return Array.isArray(m)&&m.includes(G)}function _(m,k){if(m.const)R(m.const,k);else if(m.enum)for(let tw of m.enum)R(tw,k);else throw Error(`discriminator: "properties/${G}" must have "const" or "enum"`)}function R(m,k){if(typeof m!="string"||m in O)throw Error(`discriminator: "${G}" values must be unique strings`);O[m]=k}}}};MH.default=fq});var qH=I((dR,mq)=>{mq.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 z9=I((Tw,H9)=>{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 gq=jJ(),lq=UH(),iq=KH(),ZH=qH(),nq=["/properties"],f$="http://json-schema.org/draft-07/schema";class zb extends gq.default{_addVocabularies(){if(super._addVocabularies(),lq.default.forEach((w)=>this.addVocabulary(w)),this.opts.discriminator)this.addKeyword(iq.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let w=this.opts.$data?this.$dataMetaSchema(ZH,nq):ZH;this.addMetaSchema(w,f$,!1),this.refs["http://json-schema.org/schema"]=f$}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(f$)?f$:void 0)}}Tw.Ajv=zb;H9.exports=Tw=zb;H9.exports.Ajv=zb;Object.defineProperty(Tw,"__esModule",{value:!0});Tw.default=zb;var pq=s0();Object.defineProperty(Tw,"KeywordCxt",{enumerable:!0,get:function(){return pq.KeywordCxt}});var X0=f();Object.defineProperty(Tw,"_",{enumerable:!0,get:function(){return X0._}});Object.defineProperty(Tw,"str",{enumerable:!0,get:function(){return X0.str}});Object.defineProperty(Tw,"stringify",{enumerable:!0,get:function(){return X0.stringify}});Object.defineProperty(Tw,"nil",{enumerable:!0,get:function(){return X0.nil}});Object.defineProperty(Tw,"Name",{enumerable:!0,get:function(){return X0.Name}});Object.defineProperty(Tw,"CodeGen",{enumerable:!0,get:function(){return X0.CodeGen}});var oq=O$();Object.defineProperty(Tw,"ValidationError",{enumerable:!0,get:function(){return oq.default}});var dq=e0();Object.defineProperty(Tw,"MissingRefError",{enumerable:!0,get:function(){return dq.default}})});var CH=I((RH)=>{Object.defineProperty(RH,"__esModule",{value:!0});RH.formatNames=RH.fastFormats=RH.fullFormats=void 0;function aw(w,b){return{validate:w,compare:b}}RH.fullFormats={date:aw(IH,L9),time:aw(U9(!0),F9),"date-time":aw(PH(!0),EH),"iso-time":aw(U9(),NH),"iso-date-time":aw(PH(),TH),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:$Z,"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:HZ,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:QZ,int32:{type:"number",validate:YZ},int64:{type:"number",validate:GZ},float:{type:"number",validate:jH},double:{type:"number",validate:jH},password:!0,binary:!0};RH.fastFormats={...RH.fullFormats,date:aw(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,L9),time:aw(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,F9),"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,EH),"iso-time":aw(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,NH),"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,TH),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};RH.formatNames=Object.keys(RH.fullFormats);function sq(w){return w%4===0&&(w%100!==0||w%400===0)}var eq=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,aq=[0,31,28,31,30,31,30,31,31,30,31,30,31];function IH(w){let b=eq.exec(w);if(!b)return!1;let $=+b[1],Q=+b[2],W=+b[3];return Q>=1&&Q<=12&&W>=1&&W<=(Q===2&&sq($)?29:aq[Q])}function L9(w,b){if(!(w&&b))return;if(w>b)return 1;if(w<b)return-1;return 0}var D9=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function U9(w){return function($){let Q=D9.exec($);if(!Q)return!1;let W=+Q[1],X=+Q[2],Y=+Q[3],G=Q[4],J=Q[5]==="-"?-1:1,H=+(Q[6]||0),z=+(Q[7]||0);if(H>23||z>59||w&&!G)return!1;if(W<=23&&X<=59&&Y<60)return!0;let D=X-z*J,A=W-H*J-(D<0?1:0);return(A===23||A===-1)&&(D===59||D===-1)&&Y<61}}function F9(w,b){if(!(w&&b))return;let $=new Date("2020-01-01T"+w).valueOf(),Q=new Date("2020-01-01T"+b).valueOf();if(!($&&Q))return;return $-Q}function NH(w,b){if(!(w&&b))return;let $=D9.exec(w),Q=D9.exec(b);if(!($&&Q))return;if(w=$[1]+$[2]+$[3],b=Q[1]+Q[2]+Q[3],w>b)return 1;if(w<b)return-1;return 0}var A9=/t|\s/i;function PH(w){let b=U9(w);return function(Q){let W=Q.split(A9);return W.length===2&&IH(W[0])&&b(W[1])}}function EH(w,b){if(!(w&&b))return;let $=new Date(w).valueOf(),Q=new Date(b).valueOf();if(!($&&Q))return;return $-Q}function TH(w,b){if(!(w&&b))return;let[$,Q]=w.split(A9),[W,X]=b.split(A9),Y=L9($,W);if(Y===void 0)return;return Y||F9(Q,X)}var wZ=/\/|:/,bZ=/^(?:[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 $Z(w){return wZ.test(w)&&bZ.test(w)}var VH=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function QZ(w){return VH.lastIndex=0,VH.test(w)}var WZ=-2147483648,XZ=2147483647;function YZ(w){return Number.isInteger(w)&&w<=XZ&&w>=WZ}function GZ(w){return Number.isInteger(w)}function jH(){return!0}var JZ=/[^\\]\\Z/;function HZ(w){if(JZ.test(w))return!1;try{return new RegExp(w),!0}catch(b){return!1}}});var _H=I((vH)=>{Object.defineProperty(vH,"__esModule",{value:!0});vH.formatLimitDefinition=void 0;var DZ=z9(),pw=f(),S1=pw.operators,c$={formatMaximum:{okStr:"<=",ok:S1.LTE,fail:S1.GT},formatMinimum:{okStr:">=",ok:S1.GTE,fail:S1.LT},formatExclusiveMaximum:{okStr:"<",ok:S1.LT,fail:S1.GTE},formatExclusiveMinimum:{okStr:">",ok:S1.GT,fail:S1.LTE}},UZ={message:({keyword:w,schemaCode:b})=>pw.str`should be ${c$[w].okStr} ${b}`,params:({keyword:w,schemaCode:b})=>pw._`{comparison: ${c$[w].okStr}, limit: ${b}}`};vH.formatLimitDefinition={keyword:Object.keys(c$),type:"string",schemaType:"string",$data:!0,error:UZ,code(w){let{gen:b,data:$,schemaCode:Q,keyword:W,it:X}=w,{opts:Y,self:G}=X;if(!Y.validateFormats)return;let J=new DZ.KeywordCxt(X,G.RULES.all.format.definition,"format");if(J.$data)H();else z();function H(){let A=b.scopeValue("formats",{ref:G.formats,code:Y.code.formats}),L=b.const("fmt",pw._`${A}[${J.schemaCode}]`);w.fail$data((0,pw.or)(pw._`typeof ${L} != "object"`,pw._`${L} instanceof RegExp`,pw._`typeof ${L}.compare != "function"`,D(L)))}function z(){let A=J.schema,L=G.formats[A];if(!L||L===!0)return;if(typeof L!="object"||L instanceof RegExp||typeof L.compare!="function")throw Error(`"${W}": format "${A}" does not define "compare" function`);let O=b.scopeValue("formats",{key:A,ref:L,code:Y.code.formats?pw._`${Y.code.formats}${(0,pw.getProperty)(A)}`:void 0});w.fail$data(D(O))}function D(A){return pw._`${A}.compare(${$}, ${Q}) ${c$[W].fail} 0`}},dependencies:["format"]};var AZ=(w)=>{return w.addKeyword(vH.formatLimitDefinition),w};vH.default=AZ});var yH=I((Db,hH)=>{Object.defineProperty(Db,"__esModule",{value:!0});var Y0=CH(),FZ=_H(),M9=f(),kH=new M9.Name("fullFormats"),BZ=new M9.Name("fastFormats"),K9=(w,b={keywords:!0})=>{if(Array.isArray(b))return xH(w,b,Y0.fullFormats,kH),w;let[$,Q]=b.mode==="fast"?[Y0.fastFormats,BZ]:[Y0.fullFormats,kH],W=b.formats||Y0.formatNames;if(xH(w,W,$,Q),b.keywords)(0,FZ.default)(w);return w};K9.get=(w,b="full")=>{let Q=(b==="fast"?Y0.fastFormats:Y0.fullFormats)[w];if(!Q)throw Error(`Unknown format "${w}"`);return Q};function xH(w,b,$,Q){var W,X;(W=(X=w.opts.code).formats)!==null&&W!==void 0||(X.formats=M9._`require("ajv-formats/dist/formats").${Q}`);for(let Y of b)w.addFormat(Y,$[Y])}hH.exports=Db=K9;Object.defineProperty(Db,"__esModule",{value:!0});Db.default=K9});import{AsyncLocalStorage as i5}from"node:async_hooks";class rw extends Error{statusCode;rawDetails;code;context;constructor(w,b,$,Q,W){super(w);this.statusCode=b;this.rawDetails=$;this.code=Q;this.context=W;this.name="McpApiError"}}function m5(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 g5(w){let b=w.match(/api key is missing required scopes?:\s*(.+)$/i);if(!b?.[1])return[];return b[1].match(/[a-z_]+:[a-z_]+/gi)??[]}function l5(w){let b=m5(w),$=b.message.trim()||"Unknown error",Q=$.toLowerCase(),W=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:W};if(b.code==="MCP_AUTH_REQUIRED"||Q.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:W};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:W};let X=g5($);if(X.length>0){let Y=X.map((J)=>`\`${J}\``).join(", "),G=X.every((J)=>J.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"}: ${Y}.`,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 ${G} including ${Y}, 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 ${Y}. Existing key permissions cannot be edited in place.`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:W}}if(b.statusCode===403||Q.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:W};if(Q.includes("no company available")||Q.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:W};if(b.statusCode===404||Q.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:W};if(Q.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:W};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:W};if(b.statusCode===429||Q.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:W};if(b.code==="NETWORK_ERROR"||Q.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:W};if(Q.includes("unknown tool")||Q.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:W};if(Q.includes("is required")||Q.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:W};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:W};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:W}}function F1(w){let b=l5(w);return[`Sequenzy MCP error: ${b.title}`,`Description: ${b.description}`,`How to fix: ${b.howToFix}`,`Docs: ${b.docsUrl}`,`Details: ${b.details}`].join(`
|
|
10
|
+
`)}var n5="https://api.sequenzy.com",p5=new Set(["/api/v1/media/upload-bytes","/v1/media/upload-bytes"]),O0=new i5,zQ=!1;function DQ(){zQ=!0}function Kb(){return zQ}var UQ=null;function B1(){let w=O0.getStore();if(w)return w.selectedCompanyId??null;return UQ}function qb(w){let b=O0.getStore();if(b){b.selectedCompanyId=w;return}UQ=w}function z4(w,b){return O0.run(w,b)}function AQ(){return O0.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??n5}function LQ(){return O0.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function FQ(w,b){let $=LQ();if(!$)throw new rw("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let Q={"Content-Type":w,Authorization:`Bearer ${$}`},W=b??B1();if(W)Q["x-company-id"]=W;return Q}function BQ(){if(LQ())return;console.error(F1(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 o5(w){if(w===void 0)return;if(typeof w==="string")return w.trim()||void 0;return JSON.stringify(w)}function OQ(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,Q=Rw(b,"code")??($?Rw($,"code"):void 0),W=(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"),Y={...Rw(b,"title")?{title:Rw(b,"title")}:{},...Rw(b,"description")?{description:Rw(b,"description")}:{},...X?{howToFix:X}:{},...Rw(b,"docsUrl")?{docsUrl:Rw(b,"docsUrl")}:{}},G=o5(b.details);if(Object.keys(Y).length>0||G)return{message:W,...Q?{code:Q}:{},...G?{details:G}:{},...Object.keys(Y).length>0?{context:Y}:{}};if(typeof b.error==="string")return{message:b.error,...Q?{code:Q}:{}};if($)return{message:W,...Q?{code:Q}:{}};return{message:W,...Q?{code:Q}:{}}}catch{return{message:w}}}async function U(w,b,$,Q){let W=FQ("application/json",Q),X;try{X=await fetch(`${AQ()}${b}`,{method:w,headers:W,body:$?JSON.stringify($):void 0})}catch(Y){throw new rw(Y instanceof Error?Y.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!X.ok){let Y=await X.text(),G=OQ(Y);throw new rw(G.message,X.status,G.details??Y,G.code,G.context)}return X.json()}async function MQ(w,b,$,Q){let W=new URL(AQ()).origin,X=new URL(w,`${W}/`);if(X.origin!==W){if(!p5.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}`,`${W}/`)}let Y;try{Y=await fetch(X,{method:"PUT",headers:FQ($,Q),body:b})}catch(G){throw new rw(G instanceof Error?G.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!Y.ok){let G=await Y.text(),J=OQ(G);throw new rw(J.message,Y.status,J.details??G,J.code,J.context)}}var xP=Object.freeze({status:"aborted"});function M(w,b,$){function Q(G,J){var H;Object.defineProperty(G,"_zod",{value:G._zod??{},enumerable:!1}),(H=G._zod).traits??(H.traits=new Set),G._zod.traits.add(w),b(G,J);for(let z in Y.prototype)if(!(z in G))Object.defineProperty(G,z,{value:Y.prototype[z].bind(G)});G._zod.constr=Y,G._zod.def=J}let W=$?.Parent??Object;class X extends W{}Object.defineProperty(X,"name",{value:w});function Y(G){var J;let H=$?.Parent?new X:this;Q(H,G),(J=H._zod).deferred??(J.deferred=[]);for(let z of H._zod.deferred)z();return H}return Object.defineProperty(Y,"init",{value:Q}),Object.defineProperty(Y,Symbol.hasInstance,{value:(G)=>{if($?.Parent&&G instanceof $.Parent)return!0;return G?._zod?.traits?.has(w)}}),Object.defineProperty(Y,"name",{value:w}),Y}var hP=Symbol("zod_brand");class $1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class M0 extends Error{constructor(w){super(`Encountered unidirectional transform during encode: ${w}`);this.name="ZodEncodeError"}}var Zb={};function _w(w){if(w)Object.assign(Zb,w);return Zb}var o={};HQ(o,{unwrapMessage:()=>K0,uint8ArrayToHex:()=>M3,uint8ArrayToBase64url:()=>B3,uint8ArrayToBase64:()=>IQ,stringifyPrimitive:()=>Ib,shallowClone:()=>qQ,safeExtend:()=>z3,required:()=>A3,randomString:()=>Q3,propertyKeyTypes:()=>F4,promiseAllObject:()=>$3,primitiveTypes:()=>ZQ,prefixIssues:()=>W1,pick:()=>G3,partial:()=>U3,optionalKeys:()=>B4,omit:()=>J3,objectClone:()=>a5,numKeys:()=>W3,nullish:()=>q0,normalizeParams:()=>C,mergeDefs:()=>M1,merge:()=>D3,jsonStringifyReplacer:()=>g1,joinValues:()=>Pb,issue:()=>i1,isPlainObject:()=>K1,isObject:()=>v1,hexToUint8Array:()=>O3,getSizableOrigin:()=>VQ,getParsedType:()=>X3,getLengthableOrigin:()=>P0,getEnumValues:()=>U4,getElementAtPath:()=>b3,floatSafeRemainder:()=>A4,finalizeIssue:()=>cw,extend:()=>H3,escapeRegex:()=>Q1,esc:()=>Vb,defineLazy:()=>r,createTransparentProxy:()=>Y3,cloneDef:()=>w3,clone:()=>fw,cleanRegex:()=>Z0,cleanEnum:()=>L3,captureStackTrace:()=>jb,cached:()=>l1,base64urlToUint8Array:()=>F3,base64ToUint8Array:()=>jQ,assignProp:()=>O1,assertNotEqual:()=>t5,assertNever:()=>s5,assertIs:()=>r5,assertEqual:()=>d5,assert:()=>e5,allowsEval:()=>L4,aborted:()=>q1,NUMBER_FORMAT_RANGES:()=>O4,Class:()=>NQ,BIGINT_FORMAT_RANGES:()=>PQ});function d5(w){return w}function t5(w){return w}function r5(w){}function s5(w){throw Error()}function e5(w){}function U4(w){let b=Object.values(w).filter((Q)=>typeof Q==="number");return Object.entries(w).filter(([Q,W])=>b.indexOf(+Q)===-1).map(([Q,W])=>W)}function Pb(w,b="|"){return w.map(($)=>Ib($)).join(b)}function g1(w,b){if(typeof b==="bigint")return b.toString();return b}function l1(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 Z0(w){let b=w.startsWith("^")?1:0,$=w.endsWith("$")?w.length-1:w.length;return w.slice(b,$)}function A4(w,b){let $=(w.toString().split(".")[1]||"").length,Q=b.toString(),W=(Q.split(".")[1]||"").length;if(W===0&&/\d?e-\d?/.test(Q)){let J=Q.match(/\d?e-(\d?)/);if(J?.[1])W=Number.parseInt(J[1])}let X=$>W?$:W,Y=Number.parseInt(w.toFixed(X).replace(".","")),G=Number.parseInt(b.toFixed(X).replace(".",""));return Y%G/10**X}var KQ=Symbol("evaluating");function r(w,b,$){let Q=void 0;Object.defineProperty(w,b,{get(){if(Q===KQ)return;if(Q===void 0)Q=KQ,Q=$();return Q},set(W){Object.defineProperty(w,b,{value:W})},configurable:!0})}function a5(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 M1(...w){let b={};for(let $ of w){let Q=Object.getOwnPropertyDescriptors($);Object.assign(b,Q)}return Object.defineProperties({},b)}function w3(w){return M1(w._zod.def)}function b3(w,b){if(!b)return w;return b.reduce(($,Q)=>$?.[Q],w)}function $3(w){let b=Object.keys(w),$=b.map((Q)=>w[Q]);return Promise.all($).then((Q)=>{let W={};for(let X=0;X<b.length;X++)W[b[X]]=Q[X];return W})}function Q3(w=10){let $="";for(let Q=0;Q<w;Q++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function Vb(w){return JSON.stringify(w)}var jb="captureStackTrace"in Error?Error.captureStackTrace:(...w)=>{};function v1(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}var L4=l1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(w){return!1}});function K1(w){if(v1(w)===!1)return!1;let b=w.constructor;if(b===void 0)return!0;let $=b.prototype;if(v1($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function qQ(w){if(K1(w))return{...w};if(Array.isArray(w))return[...w];return w}function W3(w){let b=0;for(let $ in w)if(Object.prototype.hasOwnProperty.call(w,$))b++;return b}var X3=(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}`)}},F4=new Set(["string","number","symbol"]),ZQ=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Q1(w){return w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fw(w,b,$){let Q=new w._zod.constr(b??w._zod.def);if(!b||$?.parent)Q._zod.parent=w;return Q}function C(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 Y3(w){let b;return new Proxy({},{get($,Q,W){return b??(b=w()),Reflect.get(b,Q,W)},set($,Q,W,X){return b??(b=w()),Reflect.set(b,Q,W,X)},has($,Q){return b??(b=w()),Reflect.has(b,Q)},deleteProperty($,Q){return b??(b=w()),Reflect.deleteProperty(b,Q)},ownKeys($){return b??(b=w()),Reflect.ownKeys(b)},getOwnPropertyDescriptor($,Q){return b??(b=w()),Reflect.getOwnPropertyDescriptor(b,Q)},defineProperty($,Q,W){return b??(b=w()),Reflect.defineProperty(b,Q,W)}})}function Ib(w){if(typeof w==="bigint")return w.toString()+"n";if(typeof w==="string")return`"${w}"`;return`${w}`}function B4(w){return Object.keys(w).filter((b)=>{return w[b]._zod.optin==="optional"&&w[b]._zod.optout==="optional"})}var O4={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]},PQ={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function G3(w,b){let $=w._zod.def,Q=M1(w._zod.def,{get shape(){let W={};for(let X in b){if(!(X in $.shape))throw Error(`Unrecognized key: "${X}"`);if(!b[X])continue;W[X]=$.shape[X]}return O1(this,"shape",W),W},checks:[]});return fw(w,Q)}function J3(w,b){let $=w._zod.def,Q=M1(w._zod.def,{get shape(){let W={...w._zod.def.shape};for(let X in b){if(!(X in $.shape))throw Error(`Unrecognized key: "${X}"`);if(!b[X])continue;delete W[X]}return O1(this,"shape",W),W},checks:[]});return fw(w,Q)}function H3(w,b){if(!K1(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 W=M1(w._zod.def,{get shape(){let X={...w._zod.def.shape,...b};return O1(this,"shape",X),X},checks:[]});return fw(w,W)}function z3(w,b){if(!K1(b))throw Error("Invalid input to safeExtend: expected a plain object");let $={...w._zod.def,get shape(){let Q={...w._zod.def.shape,...b};return O1(this,"shape",Q),Q},checks:w._zod.def.checks};return fw(w,$)}function D3(w,b){let $=M1(w._zod.def,{get shape(){let Q={...w._zod.def.shape,...b._zod.def.shape};return O1(this,"shape",Q),Q},get catchall(){return b._zod.def.catchall},checks:[]});return fw(w,$)}function U3(w,b,$){let Q=M1(b._zod.def,{get shape(){let W=b._zod.def.shape,X={...W};if($)for(let Y in $){if(!(Y in W))throw Error(`Unrecognized key: "${Y}"`);if(!$[Y])continue;X[Y]=w?new w({type:"optional",innerType:W[Y]}):W[Y]}else for(let Y in W)X[Y]=w?new w({type:"optional",innerType:W[Y]}):W[Y];return O1(this,"shape",X),X},checks:[]});return fw(b,Q)}function A3(w,b,$){let Q=M1(b._zod.def,{get shape(){let W=b._zod.def.shape,X={...W};if($)for(let Y in $){if(!(Y in X))throw Error(`Unrecognized key: "${Y}"`);if(!$[Y])continue;X[Y]=new w({type:"nonoptional",innerType:W[Y]})}else for(let Y in W)X[Y]=new w({type:"nonoptional",innerType:W[Y]});return O1(this,"shape",X),X},checks:[]});return fw(b,Q)}function q1(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 W1(w,b){return b.map(($)=>{var Q;return(Q=$).path??(Q.path=[]),$.path.unshift(w),$})}function K0(w){return typeof w==="string"?w:w?.message}function cw(w,b,$){let Q={...w,path:w.path??[]};if(!w.message){let W=K0(w.inst?._zod.def?.error?.(w))??K0(b?.error?.(w))??K0($.customError?.(w))??K0($.localeError?.(w))??"Invalid input";Q.message=W}if(delete Q.inst,delete Q.continue,!b?.reportInput)delete Q.input;return Q}function VQ(w){if(w instanceof Set)return"set";if(w instanceof Map)return"map";if(w instanceof File)return"file";return"unknown"}function P0(w){if(Array.isArray(w))return"array";if(typeof w==="string")return"string";return"unknown"}function i1(...w){let[b,$,Q]=w;if(typeof b==="string")return{message:b,code:"custom",input:$,inst:Q};return{...b}}function L3(w){return Object.entries(w).filter(([b,$])=>{return Number.isNaN(Number.parseInt(b,10))}).map((b)=>b[1])}function jQ(w){let b=atob(w),$=new Uint8Array(b.length);for(let Q=0;Q<b.length;Q++)$[Q]=b.charCodeAt(Q);return $}function IQ(w){let b="";for(let $=0;$<w.length;$++)b+=String.fromCharCode(w[$]);return btoa(b)}function F3(w){let b=w.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-b.length%4)%4);return jQ(b+$)}function B3(w){return IQ(w).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function O3(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 Q=0;Q<b.length;Q+=2)$[Q/2]=Number.parseInt(b.slice(Q,Q+2),16);return $}function M3(w){return Array.from(w).map((b)=>b.toString(16).padStart(2,"0")).join("")}class NQ{constructor(...w){}}var EQ=(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,g1,2),Object.defineProperty(w,"toString",{value:()=>w.message,enumerable:!1})},Nb=M("$ZodError",EQ),M4=M("$ZodError",EQ,{Parent:Error});function TQ(w,b=($)=>$.message){let $={},Q=[];for(let W of w.issues)if(W.path.length>0)$[W.path[0]]=$[W.path[0]]||[],$[W.path[0]].push(b(W));else Q.push(b(W));return{formErrors:Q,fieldErrors:$}}function RQ(w,b=($)=>$.message){let $={_errors:[]},Q=(W)=>{for(let X of W.issues)if(X.code==="invalid_union"&&X.errors.length)X.errors.map((Y)=>Q({issues:Y}));else if(X.code==="invalid_key")Q({issues:X.issues});else if(X.code==="invalid_element")Q({issues:X.issues});else if(X.path.length===0)$._errors.push(b(X));else{let Y=$,G=0;while(G<X.path.length){let J=X.path[G];if(G!==X.path.length-1)Y[J]=Y[J]||{_errors:[]};else Y[J]=Y[J]||{_errors:[]},Y[J]._errors.push(b(X));Y=Y[J],G++}}};return Q(w),$}var Eb=(w)=>(b,$,Q,W)=>{let X=Q?Object.assign(Q,{async:!1}):{async:!1},Y=b._zod.run({value:$,issues:[]},X);if(Y instanceof Promise)throw new $1;if(Y.issues.length){let G=new(W?.Err??w)(Y.issues.map((J)=>cw(J,X,_w())));throw jb(G,W?.callee),G}return Y.value};var Tb=(w)=>async(b,$,Q,W)=>{let X=Q?Object.assign(Q,{async:!0}):{async:!0},Y=b._zod.run({value:$,issues:[]},X);if(Y instanceof Promise)Y=await Y;if(Y.issues.length){let G=new(W?.Err??w)(Y.issues.map((J)=>cw(J,X,_w())));throw jb(G,W?.callee),G}return Y.value};var V0=(w)=>(b,$,Q)=>{let W=Q?{...Q,async:!1}:{async:!1},X=b._zod.run({value:$,issues:[]},W);if(X instanceof Promise)throw new $1;return X.issues.length?{success:!1,error:new(w??Nb)(X.issues.map((Y)=>cw(Y,W,_w())))}:{success:!0,data:X.value}},j0=V0(M4),I0=(w)=>async(b,$,Q)=>{let W=Q?Object.assign(Q,{async:!0}):{async:!0},X=b._zod.run({value:$,issues:[]},W);if(X instanceof Promise)X=await X;return X.issues.length?{success:!1,error:new w(X.issues.map((Y)=>cw(Y,W,_w())))}:{success:!0,data:X.value}},Rb=I0(M4),SQ=(w)=>(b,$,Q)=>{let W=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return Eb(w)(b,$,W)};var CQ=(w)=>(b,$,Q)=>{return Eb(w)(b,$,Q)};var vQ=(w)=>async(b,$,Q)=>{let W=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return Tb(w)(b,$,W)};var _Q=(w)=>async(b,$,Q)=>{return Tb(w)(b,$,Q)};var kQ=(w)=>(b,$,Q)=>{let W=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return V0(w)(b,$,W)};var xQ=(w)=>(b,$,Q)=>{return V0(w)(b,$,Q)};var hQ=(w)=>async(b,$,Q)=>{let W=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return I0(w)(b,$,W)};var yQ=(w)=>async(b,$,Q)=>{return I0(w)(b,$,Q)};var uQ=/^[cC][^\s-]{8,}$/,fQ=/^[0-9a-z]+$/,cQ=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,mQ=/^[0-9a-vA-V]{20}$/,gQ=/^[A-Za-z0-9]{27}$/,lQ=/^[a-zA-Z0-9_-]{21}$/,iQ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var nQ=/^([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})$/,K4=(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 pQ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function oQ(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var dQ=/^(?:(?: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])$/,tQ=/^(([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}|:))$/,rQ=/^((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])$/,sQ=/^(([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])$/,eQ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,q4=/^[A-Za-z0-9_-]*$/,aQ=/^(?=.{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 wW=/^\+(?:[0-9]){6,14}[0-9]$/,bW="(?:(?:\\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])))",$W=new RegExp(`^${bW}$`);function QW(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 WW(w){return new RegExp(`^${QW(w)}$`)}function XW(w){let b=QW({precision:w.precision}),$=["Z"];if(w.local)$.push("");if(w.offset)$.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Q=`${b}(?:${$.join("|")})`;return new RegExp(`^${bW}T(?:${Q})$`)}var YW=(w)=>{let b=w?`[\\s\\S]{${w?.minimum??0},${w?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${b}$`)};var GW=/^-?\d+$/,JW=/^-?\d+(?:\.\d+)?/,HW=/^(?:true|false)$/i,zW=/^null$/i;var DW=/^[^A-Z]*$/,UW=/^[^a-z]*$/;var Lw=M("$ZodCheck",(w,b)=>{var $;w._zod??(w._zod={}),w._zod.def=b,($=w._zod).onattach??($.onattach=[])}),AW={number:"number",bigint:"bigint",object:"date"},Z4=M("$ZodCheckLessThan",(w,b)=>{Lw.init(w,b);let $=AW[typeof b.value];w._zod.onattach.push((Q)=>{let W=Q._zod.bag,X=(b.inclusive?W.maximum:W.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(b.value<X)if(b.inclusive)W.maximum=b.value;else W.exclusiveMaximum=b.value}),w._zod.check=(Q)=>{if(b.inclusive?Q.value<=b.value:Q.value<b.value)return;Q.issues.push({origin:$,code:"too_big",maximum:b.value,input:Q.value,inclusive:b.inclusive,inst:w,continue:!b.abort})}}),P4=M("$ZodCheckGreaterThan",(w,b)=>{Lw.init(w,b);let $=AW[typeof b.value];w._zod.onattach.push((Q)=>{let W=Q._zod.bag,X=(b.inclusive?W.minimum:W.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(b.value>X)if(b.inclusive)W.minimum=b.value;else W.exclusiveMinimum=b.value}),w._zod.check=(Q)=>{if(b.inclusive?Q.value>=b.value:Q.value>b.value)return;Q.issues.push({origin:$,code:"too_small",minimum:b.value,input:Q.value,inclusive:b.inclusive,inst:w,continue:!b.abort})}}),LW=M("$ZodCheckMultipleOf",(w,b)=>{Lw.init(w,b),w._zod.onattach.push(($)=>{var Q;(Q=$._zod.bag).multipleOf??(Q.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):A4($.value,b.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:b.value,input:$.value,inst:w,continue:!b.abort})}}),FW=M("$ZodCheckNumberFormat",(w,b)=>{Lw.init(w,b),b.format=b.format||"float64";let $=b.format?.includes("int"),Q=$?"int":"number",[W,X]=O4[b.format];w._zod.onattach.push((Y)=>{let G=Y._zod.bag;if(G.format=b.format,G.minimum=W,G.maximum=X,$)G.pattern=GW}),w._zod.check=(Y)=>{let G=Y.value;if($){if(!Number.isInteger(G)){Y.issues.push({expected:Q,format:b.format,code:"invalid_type",continue:!1,input:G,inst:w});return}if(!Number.isSafeInteger(G)){if(G>0)Y.issues.push({input:G,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:w,origin:Q,continue:!b.abort});else Y.issues.push({input:G,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:w,origin:Q,continue:!b.abort});return}}if(G<W)Y.issues.push({origin:"number",input:G,code:"too_small",minimum:W,inclusive:!0,inst:w,continue:!b.abort});if(G>X)Y.issues.push({origin:"number",input:G,code:"too_big",maximum:X,inst:w})}});var BW=M("$ZodCheckMaxLength",(w,b)=>{var $;Lw.init(w,b),($=w._zod.def).when??($.when=(Q)=>{let W=Q.value;return!q0(W)&&W.length!==void 0}),w._zod.onattach.push((Q)=>{let W=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(b.maximum<W)Q._zod.bag.maximum=b.maximum}),w._zod.check=(Q)=>{let W=Q.value;if(W.length<=b.maximum)return;let Y=P0(W);Q.issues.push({origin:Y,code:"too_big",maximum:b.maximum,inclusive:!0,input:W,inst:w,continue:!b.abort})}}),OW=M("$ZodCheckMinLength",(w,b)=>{var $;Lw.init(w,b),($=w._zod.def).when??($.when=(Q)=>{let W=Q.value;return!q0(W)&&W.length!==void 0}),w._zod.onattach.push((Q)=>{let W=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(b.minimum>W)Q._zod.bag.minimum=b.minimum}),w._zod.check=(Q)=>{let W=Q.value;if(W.length>=b.minimum)return;let Y=P0(W);Q.issues.push({origin:Y,code:"too_small",minimum:b.minimum,inclusive:!0,input:W,inst:w,continue:!b.abort})}}),MW=M("$ZodCheckLengthEquals",(w,b)=>{var $;Lw.init(w,b),($=w._zod.def).when??($.when=(Q)=>{let W=Q.value;return!q0(W)&&W.length!==void 0}),w._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.minimum=b.length,W.maximum=b.length,W.length=b.length}),w._zod.check=(Q)=>{let W=Q.value,X=W.length;if(X===b.length)return;let Y=P0(W),G=X>b.length;Q.issues.push({origin:Y,...G?{code:"too_big",maximum:b.length}:{code:"too_small",minimum:b.length},inclusive:!0,exact:!0,input:Q.value,inst:w,continue:!b.abort})}}),N0=M("$ZodCheckStringFormat",(w,b)=>{var $,Q;if(Lw.init(w,b),w._zod.onattach.push((W)=>{let X=W._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=(W)=>{if(b.pattern.lastIndex=0,b.pattern.test(W.value))return;W.issues.push({origin:"string",code:"invalid_format",format:b.format,input:W.value,...b.pattern?{pattern:b.pattern.toString()}:{},inst:w,continue:!b.abort})});else(Q=w._zod).check??(Q.check=()=>{})}),KW=M("$ZodCheckRegex",(w,b)=>{N0.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})}}),qW=M("$ZodCheckLowerCase",(w,b)=>{b.pattern??(b.pattern=DW),N0.init(w,b)}),ZW=M("$ZodCheckUpperCase",(w,b)=>{b.pattern??(b.pattern=UW),N0.init(w,b)}),PW=M("$ZodCheckIncludes",(w,b)=>{Lw.init(w,b);let $=Q1(b.includes),Q=new RegExp(typeof b.position==="number"?`^.{${b.position}}${$}`:$);b.pattern=Q,w._zod.onattach.push((W)=>{let X=W._zod.bag;X.patterns??(X.patterns=new Set),X.patterns.add(Q)}),w._zod.check=(W)=>{if(W.value.includes(b.includes,b.position))return;W.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:b.includes,input:W.value,inst:w,continue:!b.abort})}}),VW=M("$ZodCheckStartsWith",(w,b)=>{Lw.init(w,b);let $=new RegExp(`^${Q1(b.prefix)}.*`);b.pattern??(b.pattern=$),w._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add($)}),w._zod.check=(Q)=>{if(Q.value.startsWith(b.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:b.prefix,input:Q.value,inst:w,continue:!b.abort})}}),jW=M("$ZodCheckEndsWith",(w,b)=>{Lw.init(w,b);let $=new RegExp(`.*${Q1(b.suffix)}$`);b.pattern??(b.pattern=$),w._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add($)}),w._zod.check=(Q)=>{if(Q.value.endsWith(b.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:b.suffix,input:Q.value,inst:w,continue:!b.abort})}});var IW=M("$ZodCheckOverwrite",(w,b)=>{Lw.init(w,b),w._zod.check=($)=>{$.value=b.tx($.value)}});class V4{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
|
+
`).filter((X)=>X),Q=Math.min(...$.map((X)=>X.length-X.trimStart().length)),W=$.map((X)=>X.slice(Q)).map((X)=>" ".repeat(this.indent*2)+X);for(let X of W)this.content.push(X)}compile(){let w=Function,b=this?.args,Q=[...(this?.content??[""]).map((W)=>` ${W}`)];return new w(...b,Q.join(`
|
|
12
|
+
`))}}var EW={major:4,minor:1,patch:12};var a=M("$ZodType",(w,b)=>{var $;w??(w={}),w._zod.def=b,w._zod.bag=w._zod.bag||{},w._zod.version=EW;let Q=[...w._zod.def.checks??[]];if(w._zod.traits.has("$ZodCheck"))Q.unshift(w);for(let W of Q)for(let X of W._zod.onattach)X(w);if(Q.length===0)($=w._zod).deferred??($.deferred=[]),w._zod.deferred?.push(()=>{w._zod.run=w._zod.parse});else{let W=(Y,G,J)=>{let H=q1(Y),z;for(let D of G){if(D._zod.def.when){if(!D._zod.def.when(Y))continue}else if(H)continue;let A=Y.issues.length,L=D._zod.check(Y);if(L instanceof Promise&&J?.async===!1)throw new $1;if(z||L instanceof Promise)z=(z??Promise.resolve()).then(async()=>{if(await L,Y.issues.length===A)return;if(!H)H=q1(Y,A)});else{if(Y.issues.length===A)continue;if(!H)H=q1(Y,A)}}if(z)return z.then(()=>{return Y});return Y},X=(Y,G,J)=>{if(q1(Y))return Y.aborted=!0,Y;let H=W(G,Q,J);if(H instanceof Promise){if(J.async===!1)throw new $1;return H.then((z)=>w._zod.parse(z,J))}return w._zod.parse(H,J)};w._zod.run=(Y,G)=>{if(G.skipChecks)return w._zod.parse(Y,G);if(G.direction==="backward"){let H=w._zod.parse({value:Y.value,issues:[]},{...G,skipChecks:!0});if(H instanceof Promise)return H.then((z)=>{return X(z,Y,G)});return X(H,Y,G)}let J=w._zod.parse(Y,G);if(J instanceof Promise){if(G.async===!1)throw new $1;return J.then((H)=>W(H,Q,G))}return W(J,Q,G)}}w["~standard"]={validate:(W)=>{try{let X=j0(w,W);return X.success?{value:X.data}:{issues:X.error?.issues}}catch(X){return Rb(w,W).then((Y)=>Y.success?{value:Y.data}:{issues:Y.error?.issues})}},vendor:"zod",version:1}}),_b=M("$ZodString",(w,b)=>{a.init(w,b),w._zod.pattern=[...w?._zod.bag?.patterns??[]].pop()??YW(w._zod.bag),w._zod.parse=($,Q)=>{if(b.coerce)try{$.value=String($.value)}catch(W){}if(typeof $.value==="string")return $;return $.issues.push({expected:"string",code:"invalid_type",input:$.value,inst:w}),$}}),ww=M("$ZodStringFormat",(w,b)=>{N0.init(w,b),_b.init(w,b)}),hW=M("$ZodGUID",(w,b)=>{b.pattern??(b.pattern=nQ),ww.init(w,b)}),yW=M("$ZodUUID",(w,b)=>{if(b.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[b.version];if(Q===void 0)throw Error(`Invalid UUID version: "${b.version}"`);b.pattern??(b.pattern=K4(Q))}else b.pattern??(b.pattern=K4());ww.init(w,b)}),uW=M("$ZodEmail",(w,b)=>{b.pattern??(b.pattern=pQ),ww.init(w,b)}),fW=M("$ZodURL",(w,b)=>{ww.init(w,b),w._zod.check=($)=>{try{let Q=$.value.trim(),W=new URL(Q);if(b.hostname){if(b.hostname.lastIndex=0,!b.hostname.test(W.hostname))$.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:aQ.source,input:$.value,inst:w,continue:!b.abort})}if(b.protocol){if(b.protocol.lastIndex=0,!b.protocol.test(W.protocol.endsWith(":")?W.protocol.slice(0,-1):W.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=W.href;else $.value=Q;return}catch(Q){$.issues.push({code:"invalid_format",format:"url",input:$.value,inst:w,continue:!b.abort})}}}),cW=M("$ZodEmoji",(w,b)=>{b.pattern??(b.pattern=oQ()),ww.init(w,b)}),mW=M("$ZodNanoID",(w,b)=>{b.pattern??(b.pattern=lQ),ww.init(w,b)}),gW=M("$ZodCUID",(w,b)=>{b.pattern??(b.pattern=uQ),ww.init(w,b)}),lW=M("$ZodCUID2",(w,b)=>{b.pattern??(b.pattern=fQ),ww.init(w,b)}),iW=M("$ZodULID",(w,b)=>{b.pattern??(b.pattern=cQ),ww.init(w,b)}),nW=M("$ZodXID",(w,b)=>{b.pattern??(b.pattern=mQ),ww.init(w,b)}),pW=M("$ZodKSUID",(w,b)=>{b.pattern??(b.pattern=gQ),ww.init(w,b)}),oW=M("$ZodISODateTime",(w,b)=>{b.pattern??(b.pattern=XW(b)),ww.init(w,b)}),dW=M("$ZodISODate",(w,b)=>{b.pattern??(b.pattern=$W),ww.init(w,b)}),tW=M("$ZodISOTime",(w,b)=>{b.pattern??(b.pattern=WW(b)),ww.init(w,b)}),rW=M("$ZodISODuration",(w,b)=>{b.pattern??(b.pattern=iQ),ww.init(w,b)}),sW=M("$ZodIPv4",(w,b)=>{b.pattern??(b.pattern=dQ),ww.init(w,b),w._zod.onattach.push(($)=>{let Q=$._zod.bag;Q.format="ipv4"})}),eW=M("$ZodIPv6",(w,b)=>{b.pattern??(b.pattern=tQ),ww.init(w,b),w._zod.onattach.push(($)=>{let Q=$._zod.bag;Q.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})}}}),aW=M("$ZodCIDRv4",(w,b)=>{b.pattern??(b.pattern=rQ),ww.init(w,b)}),w8=M("$ZodCIDRv6",(w,b)=>{b.pattern??(b.pattern=sQ),ww.init(w,b),w._zod.check=($)=>{let Q=$.value.split("/");try{if(Q.length!==2)throw Error();let[W,X]=Q;if(!X)throw Error();let Y=Number(X);if(`${Y}`!==X)throw Error();if(Y<0||Y>128)throw Error();new URL(`http://[${W}]`)}catch{$.issues.push({code:"invalid_format",format:"cidrv6",input:$.value,inst:w,continue:!b.abort})}}});function b8(w){if(w==="")return!0;if(w.length%4!==0)return!1;try{return atob(w),!0}catch{return!1}}var $8=M("$ZodBase64",(w,b)=>{b.pattern??(b.pattern=eQ),ww.init(w,b),w._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),w._zod.check=($)=>{if(b8($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:w,continue:!b.abort})}});function P3(w){if(!q4.test(w))return!1;let b=w.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),$=b.padEnd(Math.ceil(b.length/4)*4,"=");return b8($)}var Q8=M("$ZodBase64URL",(w,b)=>{b.pattern??(b.pattern=q4),ww.init(w,b),w._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),w._zod.check=($)=>{if(P3($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:w,continue:!b.abort})}}),W8=M("$ZodE164",(w,b)=>{b.pattern??(b.pattern=wW),ww.init(w,b)});function V3(w,b=null){try{let $=w.split(".");if($.length!==3)return!1;let[Q]=$;if(!Q)return!1;let W=JSON.parse(atob(Q));if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(b&&(!("alg"in W)||W.alg!==b))return!1;return!0}catch{return!1}}var X8=M("$ZodJWT",(w,b)=>{ww.init(w,b),w._zod.check=($)=>{if(V3($.value,b.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:w,continue:!b.abort})}});var I4=M("$ZodNumber",(w,b)=>{a.init(w,b),w._zod.pattern=w._zod.bag.pattern??JW,w._zod.parse=($,Q)=>{if(b.coerce)try{$.value=Number($.value)}catch(Y){}let W=$.value;if(typeof W==="number"&&!Number.isNaN(W)&&Number.isFinite(W))return $;let X=typeof W==="number"?Number.isNaN(W)?"NaN":!Number.isFinite(W)?"Infinity":void 0:void 0;return $.issues.push({expected:"number",code:"invalid_type",input:W,inst:w,...X?{received:X}:{}}),$}}),Y8=M("$ZodNumber",(w,b)=>{FW.init(w,b),I4.init(w,b)}),G8=M("$ZodBoolean",(w,b)=>{a.init(w,b),w._zod.pattern=HW,w._zod.parse=($,Q)=>{if(b.coerce)try{$.value=Boolean($.value)}catch(X){}let W=$.value;if(typeof W==="boolean")return $;return $.issues.push({expected:"boolean",code:"invalid_type",input:W,inst:w}),$}});var J8=M("$ZodNull",(w,b)=>{a.init(w,b),w._zod.pattern=zW,w._zod.values=new Set([null]),w._zod.parse=($,Q)=>{let W=$.value;if(W===null)return $;return $.issues.push({expected:"null",code:"invalid_type",input:W,inst:w}),$}});var H8=M("$ZodUnknown",(w,b)=>{a.init(w,b),w._zod.parse=($)=>$}),z8=M("$ZodNever",(w,b)=>{a.init(w,b),w._zod.parse=($,Q)=>{return $.issues.push({expected:"never",code:"invalid_type",input:$.value,inst:w}),$}});function TW(w,b,$){if(w.issues.length)b.issues.push(...W1($,w.issues));b.value[$]=w.value}var D8=M("$ZodArray",(w,b)=>{a.init(w,b),w._zod.parse=($,Q)=>{let W=$.value;if(!Array.isArray(W))return $.issues.push({expected:"array",code:"invalid_type",input:W,inst:w}),$;$.value=Array(W.length);let X=[];for(let Y=0;Y<W.length;Y++){let G=W[Y],J=b.element._zod.run({value:G,issues:[]},Q);if(J instanceof Promise)X.push(J.then((H)=>TW(H,$,Y)));else TW(J,$,Y)}if(X.length)return Promise.all(X).then(()=>$);return $}});function vb(w,b,$,Q){if(w.issues.length)b.issues.push(...W1($,w.issues));if(w.value===void 0){if($ in Q)b.value[$]=void 0}else b.value[$]=w.value}function U8(w){let b=Object.keys(w.shape);for(let Q of b)if(!w.shape?.[Q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Q}": expected a Zod schema`);let $=B4(w.shape);return{...w,keys:b,keySet:new Set(b),numKeys:b.length,optionalKeys:new Set($)}}function A8(w,b,$,Q,W,X){let Y=[],G=W.keySet,J=W.catchall._zod,H=J.def.type;for(let z of Object.keys(b)){if(G.has(z))continue;if(H==="never"){Y.push(z);continue}let D=J.run({value:b[z],issues:[]},Q);if(D instanceof Promise)w.push(D.then((A)=>vb(A,$,z,b)));else vb(D,$,z,b)}if(Y.length)$.issues.push({code:"unrecognized_keys",keys:Y,input:b,inst:X});if(!w.length)return $;return Promise.all(w).then(()=>{return $})}var j3=M("$ZodObject",(w,b)=>{if(a.init(w,b),!Object.getOwnPropertyDescriptor(b,"shape")?.get){let G=b.shape;Object.defineProperty(b,"shape",{get:()=>{let J={...G};return Object.defineProperty(b,"shape",{value:J}),J}})}let Q=l1(()=>U8(b));r(w._zod,"propValues",()=>{let G=b.shape,J={};for(let H in G){let z=G[H]._zod;if(z.values){J[H]??(J[H]=new Set);for(let D of z.values)J[H].add(D)}}return J});let W=v1,X=b.catchall,Y;w._zod.parse=(G,J)=>{Y??(Y=Q.value);let H=G.value;if(!W(H))return G.issues.push({expected:"object",code:"invalid_type",input:H,inst:w}),G;G.value={};let z=[],D=Y.shape;for(let A of Y.keys){let O=D[A]._zod.run({value:H[A],issues:[]},J);if(O instanceof Promise)z.push(O.then((K)=>vb(K,G,A,H)));else vb(O,G,A,H)}if(!X)return z.length?Promise.all(z).then(()=>G):G;return A8(z,H,G,J,Q.value,w)}}),L8=M("$ZodObjectJIT",(w,b)=>{j3.init(w,b);let $=w._zod.parse,Q=l1(()=>U8(b)),W=(A)=>{let L=new V4(["shape","payload","ctx"]),O=Q.value,K=(R)=>{let m=Vb(R);return`shape[${m}]._zod.run({ value: input[${m}], issues: [] }, ctx)`};L.write("const input = payload.value;");let j=Object.create(null),V=0;for(let R of O.keys)j[R]=`key_${V++}`;L.write("const newResult = {};");for(let R of O.keys){let m=j[R],k=Vb(R);L.write(`const ${m} = ${K(R)};`),L.write(`
|
|
13
13
|
if (${m}.issues.length) {
|
|
14
14
|
payload.issues = payload.issues.concat(${m}.issues.map(iss => ({
|
|
15
15
|
...iss,
|
|
16
|
-
path: iss.path ? [${
|
|
16
|
+
path: iss.path ? [${k}, ...iss.path] : [${k}]
|
|
17
17
|
})));
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
|
|
21
21
|
if (${m}.value === undefined) {
|
|
22
|
-
if (${
|
|
23
|
-
newResult[${
|
|
22
|
+
if (${k} in input) {
|
|
23
|
+
newResult[${k}] = undefined;
|
|
24
24
|
}
|
|
25
25
|
} else {
|
|
26
|
-
newResult[${
|
|
26
|
+
newResult[${k}] = ${m}.value;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
`)}L.write("payload.value = newResult;"),L.write("return payload;");let C=L.compile();return(R,m)=>C(A,R,m)},G,X=v1,Y=!Mb.jitless,H=Y&&z4.value,z=b.catchall,D;w._zod.parse=(A,L)=>{D??(D=W.value);let K=A.value;if(!X(K))return A.issues.push({expected:"object",code:"invalid_type",input:K,inst:w}),A;if(Y&&H&&L?.async===!1&&L.jitless!==!0){if(!G)G=Q(b.shape);if(A=G(A,L),!z)return A;return W8([],K,A,L,D,w)}return $(A,L)}});function MQ(w,b,$,W){for(let G of w)if(G.issues.length===0)return b.value=G.value,b;let Q=w.filter((G)=>!q1(G));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((G)=>G.issues.map((X)=>cw(X,W,_w())))}),b}var Z4=O("$ZodUnion",(w,b)=>{a.init(w,b),r(w._zod,"optin",()=>b.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),r(w._zod,"optout",()=>b.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),r(w._zod,"values",()=>{if(b.options.every((Q)=>Q._zod.values))return new Set(b.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),r(w._zod,"pattern",()=>{if(b.options.every((Q)=>Q._zod.pattern)){let Q=b.options.map((G)=>G._zod.pattern);return new RegExp(`^(${Q.map((G)=>M0(G.source)).join("|")})$`)}return});let $=b.options.length===1,W=b.options[0]._zod.run;w._zod.parse=(Q,G)=>{if($)return W(Q,G);let X=!1,Y=[];for(let J of b.options){let H=J._zod.run({value:Q.value,issues:[]},G);if(H instanceof Promise)Y.push(H),X=!0;else{if(H.issues.length===0)return H;Y.push(H)}}if(!X)return MQ(Y,Q,w,G);return Promise.all(Y).then((J)=>{return MQ(J,Q,w,G)})}}),G8=O("$ZodDiscriminatedUnion",(w,b)=>{Z4.init(w,b);let $=w._zod.parse;r(w._zod,"propValues",()=>{let Q={};for(let G of b.options){let X=G._zod.propValues;if(!X||Object.keys(X).length===0)throw Error(`Invalid discriminated union option at index "${b.options.indexOf(G)}"`);for(let[Y,J]of Object.entries(X)){if(!Q[Y])Q[Y]=new Set;for(let H of J)Q[Y].add(H)}}return Q});let W=g1(()=>{let Q=b.options,G=new Map;for(let X of Q){let Y=X._zod.propValues?.[b.discriminator];if(!Y||Y.size===0)throw Error(`Invalid discriminated union option at index "${b.options.indexOf(X)}"`);for(let J of Y){if(G.has(J))throw Error(`Duplicate discriminator value "${String(J)}"`);G.set(J,X)}}return G});w._zod.parse=(Q,G)=>{let X=Q.value;if(!v1(X))return Q.issues.push({code:"invalid_type",expected:"object",input:X,inst:w}),Q;let Y=W.value.get(X?.[b.discriminator]);if(Y)return Y._zod.run(Q,G);if(b.unionFallback)return $(Q,G);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:b.discriminator,input:X,path:[b.discriminator],inst:w}),Q}}),X8=O("$ZodIntersection",(w,b)=>{a.init(w,b),w._zod.parse=($,W)=>{let Q=$.value,G=b.left._zod.run({value:Q,issues:[]},W),X=b.right._zod.run({value:Q,issues:[]},W);if(G instanceof Promise||X instanceof Promise)return Promise.all([G,X]).then(([J,H])=>{return qQ($,J,H)});return qQ($,G,X)}});function q4(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((G)=>$.indexOf(G)!==-1),Q={...w,...b};for(let G of W){let X=q4(w[G],b[G]);if(!X.valid)return{valid:!1,mergeErrorPath:[G,...X.mergeErrorPath]};Q[G]=X.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],G=b[W],X=q4(Q,G);if(!X.valid)return{valid:!1,mergeErrorPath:[W,...X.mergeErrorPath]};$.push(X.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function qQ(w,b,$){if(b.issues.length)w.issues.push(...b.issues);if($.issues.length)w.issues.push(...$.issues);if(q1(w))return w;let W=q4(b.value,$.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return w.value=W.data,w}var Y8=O("$ZodRecord",(w,b)=>{a.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 G=[];if(b.keyType._zod.values){let X=b.keyType._zod.values;$.value={};for(let J of X)if(typeof J==="string"||typeof J==="number"||typeof J==="symbol"){let H=b.valueType._zod.run({value:Q[J],issues:[]},W);if(H instanceof Promise)G.push(H.then((z)=>{if(z.issues.length)$.issues.push(...Q1(J,z.issues));$.value[J]=z.value}));else{if(H.issues.length)$.issues.push(...Q1(J,H.issues));$.value[J]=H.value}}let Y;for(let J in Q)if(!X.has(J))Y=Y??[],Y.push(J);if(Y&&Y.length>0)$.issues.push({code:"unrecognized_keys",input:Q,inst:w,keys:Y})}else{$.value={};for(let X of Reflect.ownKeys(Q)){if(X==="__proto__")continue;let Y=b.keyType._zod.run({value:X,issues:[]},W);if(Y instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(Y.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:Y.issues.map((H)=>cw(H,W,_w())),input:X,path:[X],inst:w}),$.value[Y.value]=Y.value;continue}let J=b.valueType._zod.run({value:Q[X],issues:[]},W);if(J instanceof Promise)G.push(J.then((H)=>{if(H.issues.length)$.issues.push(...Q1(X,H.issues));$.value[Y.value]=H.value}));else{if(J.issues.length)$.issues.push(...Q1(X,J.issues));$.value[Y.value]=J.value}}}if(G.length)return Promise.all(G).then(()=>$);return $}});var J8=O("$ZodEnum",(w,b)=>{a.init(w,b);let $=J4(b.entries),W=new Set($);w._zod.values=W,w._zod.pattern=new RegExp(`^(${$.filter((Q)=>D4.has(typeof Q)).map((Q)=>typeof Q==="string"?W1(Q):Q.toString()).join("|")})$`),w._zod.parse=(Q,G)=>{let X=Q.value;if(W.has(X))return Q;return Q.issues.push({code:"invalid_value",values:$,input:X,inst:w}),Q}}),H8=O("$ZodLiteral",(w,b)=>{if(a.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"?W1($):$?W1($.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 z8=O("$ZodTransform",(w,b)=>{a.init(w,b),w._zod.parse=($,W)=>{if(W.direction==="backward")throw new B0(w.constructor.name);let Q=b.transform($.value,$);if(W.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((X)=>{return $.value=X,$});if(Q instanceof Promise)throw new $1;return $.value=Q,$}});function PQ(w,b){if(w.issues.length&&b===void 0)return{issues:[],value:void 0};return w}var D8=O("$ZodOptional",(w,b)=>{a.init(w,b),w._zod.optin="optional",w._zod.optout="optional",r(w._zod,"values",()=>{return b.innerType._zod.values?new Set([...b.innerType._zod.values,void 0]):void 0}),r(w._zod,"pattern",()=>{let $=b.innerType._zod.pattern;return $?new RegExp(`^(${M0($.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((G)=>PQ(G,$.value));return PQ(Q,$.value)}if($.value===void 0)return $;return b.innerType._zod.run($,W)}}),U8=O("$ZodNullable",(w,b)=>{a.init(w,b),r(w._zod,"optin",()=>b.innerType._zod.optin),r(w._zod,"optout",()=>b.innerType._zod.optout),r(w._zod,"pattern",()=>{let $=b.innerType._zod.pattern;return $?new RegExp(`^(${M0($.source)}|null)$`):void 0}),r(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)}}),A8=O("$ZodDefault",(w,b)=>{a.init(w,b),w._zod.optin="optional",r(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((G)=>ZQ(G,b));return ZQ(Q,b)}});function ZQ(w,b){if(w.value===void 0)w.value=b.defaultValue;return w}var L8=O("$ZodPrefault",(w,b)=>{a.init(w,b),w._zod.optin="optional",r(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)}}),F8=O("$ZodNonOptional",(w,b)=>{a.init(w,b),r(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((G)=>VQ(G,w));return VQ(Q,w)}});function VQ(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 B8=O("$ZodCatch",(w,b)=>{a.init(w,b),r(w._zod,"optin",()=>b.innerType._zod.optin),r(w._zod,"optout",()=>b.innerType._zod.optout),r(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((G)=>{if($.value=G.value,G.issues.length)$.value=b.catchValue({...$,error:{issues:G.issues.map((X)=>cw(X,W,_w()))},input:$.value}),$.issues=[];return $});if($.value=Q.value,Q.issues.length)$.value=b.catchValue({...$,error:{issues:Q.issues.map((G)=>cw(G,W,_w()))},input:$.value}),$.issues=[];return $}});var K8=O("$ZodPipe",(w,b)=>{a.init(w,b),r(w._zod,"values",()=>b.in._zod.values),r(w._zod,"optin",()=>b.in._zod.optin),r(w._zod,"optout",()=>b.out._zod.optout),r(w._zod,"propValues",()=>b.in._zod.propValues),w._zod.parse=($,W)=>{if(W.direction==="backward"){let G=b.out._zod.run($,W);if(G instanceof Promise)return G.then((X)=>Rb(X,b.in,W));return Rb(G,b.in,W)}let Q=b.in._zod.run($,W);if(Q instanceof Promise)return Q.then((G)=>Rb(G,b.out,W));return Rb(Q,b.out,W)}});function Rb(w,b,$){if(w.issues.length)return w.aborted=!0,w;return b._zod.run({value:w.value,issues:w.issues},$)}var O8=O("$ZodReadonly",(w,b)=>{a.init(w,b),r(w._zod,"propValues",()=>b.innerType._zod.propValues),r(w._zod,"values",()=>b.innerType._zod.values),r(w._zod,"optin",()=>b.innerType._zod.optin),r(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(jQ);return jQ(Q)}});function jQ(w){return w.value=Object.freeze(w.value),w}var M8=O("$ZodCustom",(w,b)=>{Aw.init(w,b),a.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((G)=>IQ(G,$,W,w));IQ(Q,$,W,w);return}});function IQ(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(l1(Q))}}var LD=(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},FD=()=>{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 ${LD(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${Vb(W.values[0])}`;return`Invalid option: expected one of ${qb(W.values,"|")}`;case"too_big":{let Q=W.inclusive?"<=":"<",G=b(W.origin);if(G)return`Too big: expected ${W.origin??"value"} to have ${Q}${W.maximum.toString()} ${G.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${Q}${W.maximum.toString()}`}case"too_small":{let Q=W.inclusive?">=":">",G=b(W.origin);if(G)return`Too small: expected ${W.origin} to have ${Q}${W.minimum.toString()} ${G.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":""}: ${qb(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:FD()}}var cZ=Symbol("ZodOutput"),mZ=Symbol("ZodInput");class q8{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 BD(){return new q8}var I0=BD();function P8(w,b){return new w({type:"string",...S(b)})}function Z8(w,b){return new w({type:"string",format:"email",check:"string_format",abort:!1,...S(b)})}function j4(w,b){return new w({type:"string",format:"guid",check:"string_format",abort:!1,...S(b)})}function V8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,...S(b)})}function j8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...S(b)})}function I8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...S(b)})}function N8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...S(b)})}function E8(w,b){return new w({type:"string",format:"url",check:"string_format",abort:!1,...S(b)})}function T8(w,b){return new w({type:"string",format:"emoji",check:"string_format",abort:!1,...S(b)})}function R8(w,b){return new w({type:"string",format:"nanoid",check:"string_format",abort:!1,...S(b)})}function S8(w,b){return new w({type:"string",format:"cuid",check:"string_format",abort:!1,...S(b)})}function C8(w,b){return new w({type:"string",format:"cuid2",check:"string_format",abort:!1,...S(b)})}function v8(w,b){return new w({type:"string",format:"ulid",check:"string_format",abort:!1,...S(b)})}function _8(w,b){return new w({type:"string",format:"xid",check:"string_format",abort:!1,...S(b)})}function k8(w,b){return new w({type:"string",format:"ksuid",check:"string_format",abort:!1,...S(b)})}function x8(w,b){return new w({type:"string",format:"ipv4",check:"string_format",abort:!1,...S(b)})}function y8(w,b){return new w({type:"string",format:"ipv6",check:"string_format",abort:!1,...S(b)})}function h8(w,b){return new w({type:"string",format:"cidrv4",check:"string_format",abort:!1,...S(b)})}function u8(w,b){return new w({type:"string",format:"cidrv6",check:"string_format",abort:!1,...S(b)})}function f8(w,b){return new w({type:"string",format:"base64",check:"string_format",abort:!1,...S(b)})}function c8(w,b){return new w({type:"string",format:"base64url",check:"string_format",abort:!1,...S(b)})}function m8(w,b){return new w({type:"string",format:"e164",check:"string_format",abort:!1,...S(b)})}function g8(w,b){return new w({type:"string",format:"jwt",check:"string_format",abort:!1,...S(b)})}function l8(w,b){return new w({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...S(b)})}function i8(w,b){return new w({type:"string",format:"date",check:"string_format",...S(b)})}function n8(w,b){return new w({type:"string",format:"time",check:"string_format",precision:null,...S(b)})}function p8(w,b){return new w({type:"string",format:"duration",check:"string_format",...S(b)})}function o8(w,b){return new w({type:"number",checks:[],...S(b)})}function d8(w,b){return new w({type:"number",check:"number_format",abort:!1,format:"safeint",...S(b)})}function t8(w,b){return new w({type:"boolean",...S(b)})}function r8(w,b){return new w({type:"null",...S(b)})}function s8(w){return new w({type:"unknown"})}function e8(w,b){return new w({type:"never",...S(b)})}function vb(w,b){return new K4({check:"less_than",...S(b),value:w,inclusive:!1})}function N0(w,b){return new K4({check:"less_than",...S(b),value:w,inclusive:!0})}function _b(w,b){return new O4({check:"greater_than",...S(b),value:w,inclusive:!1})}function E0(w,b){return new O4({check:"greater_than",...S(b),value:w,inclusive:!0})}function kb(w,b){return new QQ({check:"multiple_of",...S(b),value:w})}function xb(w,b){return new XQ({check:"max_length",...S(b),maximum:w})}function i1(w,b){return new YQ({check:"min_length",...S(b),minimum:w})}function yb(w,b){return new JQ({check:"length_equals",...S(b),length:w})}function I4(w,b){return new HQ({check:"string_format",format:"regex",...S(b),pattern:w})}function N4(w){return new zQ({check:"string_format",format:"lowercase",...S(w)})}function E4(w){return new DQ({check:"string_format",format:"uppercase",...S(w)})}function T4(w,b){return new UQ({check:"string_format",format:"includes",...S(b),includes:w})}function R4(w,b){return new AQ({check:"string_format",format:"starts_with",...S(b),prefix:w})}function S4(w,b){return new LQ({check:"string_format",format:"ends_with",...S(b),suffix:w})}function _1(w){return new FQ({check:"overwrite",tx:w})}function C4(w){return _1((b)=>b.normalize(w))}function v4(){return _1((w)=>w.trim())}function _4(){return _1((w)=>w.toLowerCase())}function k4(){return _1((w)=>w.toUpperCase())}function a8(w,b,$){return new w({type:"array",element:b,...S($)})}function wG(w,b,$){let W=S($);return W.abort??(W.abort=!0),new w({type:"custom",check:"custom",fn:b,...W})}function bG(w,b,$){return new w({type:"custom",check:"custom",fn:b,...S($)})}function $G(w){let b=KD(($)=>{return $.addIssue=(W)=>{if(typeof W==="string")$.issues.push(l1(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(l1(Q))}},w($.value,$)});return b}function KD(w,b){let $=new Aw({check:"custom",...S(b)});return $._zod.check=w,$}function n1(w){return!!w._zod}function P1(w,b){if(n1(w))return Z0(w,b);return w.safeParse(b)}function hb(w){if(!w)return;let b;if(n1(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 WG(w){if(n1(w)){let G=w._zod?.def;if(G){if(G.value!==void 0)return G.value;if(Array.isArray(G.values)&&G.values.length>0)return G.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 R0={};a9(R0,{time:()=>h4,duration:()=>u4,datetime:()=>x4,date:()=>y4,ZodISOTime:()=>XG,ZodISODuration:()=>YG,ZodISODateTime:()=>QG,ZodISODate:()=>GG});var QG=O("ZodISODateTime",(w,b)=>{hQ.init(w,b),$w.init(w,b)});function x4(w){return l8(QG,w)}var GG=O("ZodISODate",(w,b)=>{uQ.init(w,b),$w.init(w,b)});function y4(w){return i8(GG,w)}var XG=O("ZodISOTime",(w,b)=>{fQ.init(w,b),$w.init(w,b)});function h4(w){return n8(XG,w)}var YG=O("ZodISODuration",(w,b)=>{cQ.init(w,b),$w.init(w,b)});function u4(w){return p8(YG,w)}var JG=(w,b)=>{jb.init(w,b),w.name="ZodError",Object.defineProperties(w,{format:{value:($)=>MW(w,$)},flatten:{value:($)=>OW(w,$)},addIssue:{value:($)=>{w.issues.push($),w.message=JSON.stringify(w.issues,m1,2)}},addIssues:{value:($)=>{w.issues.push(...$),w.message=JSON.stringify(w.issues,m1,2)}},isEmpty:{get(){return w.issues.length===0}}})},NV=O("ZodError",JG),Sw=O("ZodError",JG,{Parent:Error});var HG=Ib(Sw),zG=Nb(Sw),DG=P0(Sw),UG=V0(Sw),AG=qW(Sw),LG=PW(Sw),FG=ZW(Sw),BG=VW(Sw),KG=jW(Sw),OG=IW(Sw),MG=NW(Sw),qG=EW(Sw);var Yw=O("ZodType",(w,b)=>{return a.init(w,b),w.def=b,w.type=b.type,Object.defineProperty(w,"_def",{value:b}),w.check=(...$)=>{return w.clone(o.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)=>HG(w,$,W,{callee:w.parse}),w.safeParse=($,W)=>DG(w,$,W),w.parseAsync=async($,W)=>zG(w,$,W,{callee:w.parseAsync}),w.safeParseAsync=async($,W)=>UG(w,$,W),w.spa=w.safeParseAsync,w.encode=($,W)=>AG(w,$,W),w.decode=($,W)=>LG(w,$,W),w.encodeAsync=async($,W)=>FG(w,$,W),w.decodeAsync=async($,W)=>BG(w,$,W),w.safeEncode=($,W)=>KG(w,$,W),w.safeDecode=($,W)=>OG(w,$,W),w.safeEncodeAsync=async($,W)=>MG(w,$,W),w.safeDecodeAsync=async($,W)=>qG(w,$,W),w.refine=($,W)=>w.check(AU($,W)),w.superRefine=($)=>w.check(LU($)),w.overwrite=($)=>w.check(_1($)),w.optional=()=>Xw(w),w.nullable=()=>VG(w),w.nullish=()=>Xw(VG(w)),w.nonoptional=($)=>YU(w,$),w.array=()=>g(w),w.or=($)=>e([w,$]),w.and=($)=>fb(w,$),w.transform=($)=>c4(w,TG($)),w.default=($)=>QU(w,$),w.prefault=($)=>XU(w,$),w.catch=($)=>HU(w,$),w.pipe=($)=>c4(w,$),w.readonly=()=>UU(w),w.describe=($)=>{let W=w.clone();return I0.add(W,{description:$}),W},Object.defineProperty(w,"description",{get(){return I0.get(w)?.description},configurable:!0}),w.meta=(...$)=>{if($.length===0)return I0.get(w);let W=w.clone();return I0.add(W,$[0]),W},w.isOptional=()=>w.safeParse(void 0).success,w.isNullable=()=>w.safeParse(null).success,w}),jG=O("_ZodString",(w,b)=>{Cb.init(w,b),Yw.init(w,b);let $=w._zod.bag;w.format=$.format??null,w.minLength=$.minimum??null,w.maxLength=$.maximum??null,w.regex=(...W)=>w.check(I4(...W)),w.includes=(...W)=>w.check(T4(...W)),w.startsWith=(...W)=>w.check(R4(...W)),w.endsWith=(...W)=>w.check(S4(...W)),w.min=(...W)=>w.check(i1(...W)),w.max=(...W)=>w.check(xb(...W)),w.length=(...W)=>w.check(yb(...W)),w.nonempty=(...W)=>w.check(i1(1,...W)),w.lowercase=(W)=>w.check(N4(W)),w.uppercase=(W)=>w.check(E4(W)),w.trim=()=>w.check(v4()),w.normalize=(...W)=>w.check(C4(...W)),w.toLowerCase=()=>w.check(_4()),w.toUpperCase=()=>w.check(k4())}),ND=O("ZodString",(w,b)=>{Cb.init(w,b),jG.init(w,b),w.email=($)=>w.check(Z8(ED,$)),w.url=($)=>w.check(E8(TD,$)),w.jwt=($)=>w.check(g8(lD,$)),w.emoji=($)=>w.check(T8(RD,$)),w.guid=($)=>w.check(j4(PG,$)),w.uuid=($)=>w.check(V8(ub,$)),w.uuidv4=($)=>w.check(j8(ub,$)),w.uuidv6=($)=>w.check(I8(ub,$)),w.uuidv7=($)=>w.check(N8(ub,$)),w.nanoid=($)=>w.check(R8(SD,$)),w.guid=($)=>w.check(j4(PG,$)),w.cuid=($)=>w.check(S8(CD,$)),w.cuid2=($)=>w.check(C8(vD,$)),w.ulid=($)=>w.check(v8(_D,$)),w.base64=($)=>w.check(f8(cD,$)),w.base64url=($)=>w.check(c8(mD,$)),w.xid=($)=>w.check(_8(kD,$)),w.ksuid=($)=>w.check(k8(xD,$)),w.ipv4=($)=>w.check(x8(yD,$)),w.ipv6=($)=>w.check(y8(hD,$)),w.cidrv4=($)=>w.check(h8(uD,$)),w.cidrv6=($)=>w.check(u8(fD,$)),w.e164=($)=>w.check(m8(gD,$)),w.datetime=($)=>w.check(x4($)),w.date=($)=>w.check(y4($)),w.time=($)=>w.check(h4($)),w.duration=($)=>w.check(u4($))});function B(w){return P8(ND,w)}var $w=O("ZodStringFormat",(w,b)=>{ww.init(w,b),jG.init(w,b)}),ED=O("ZodEmail",(w,b)=>{TQ.init(w,b),$w.init(w,b)});var PG=O("ZodGUID",(w,b)=>{NQ.init(w,b),$w.init(w,b)});var ub=O("ZodUUID",(w,b)=>{EQ.init(w,b),$w.init(w,b)});var TD=O("ZodURL",(w,b)=>{RQ.init(w,b),$w.init(w,b)});var RD=O("ZodEmoji",(w,b)=>{SQ.init(w,b),$w.init(w,b)});var SD=O("ZodNanoID",(w,b)=>{CQ.init(w,b),$w.init(w,b)});var CD=O("ZodCUID",(w,b)=>{vQ.init(w,b),$w.init(w,b)});var vD=O("ZodCUID2",(w,b)=>{_Q.init(w,b),$w.init(w,b)});var _D=O("ZodULID",(w,b)=>{kQ.init(w,b),$w.init(w,b)});var kD=O("ZodXID",(w,b)=>{xQ.init(w,b),$w.init(w,b)});var xD=O("ZodKSUID",(w,b)=>{yQ.init(w,b),$w.init(w,b)});var yD=O("ZodIPv4",(w,b)=>{mQ.init(w,b),$w.init(w,b)});var hD=O("ZodIPv6",(w,b)=>{gQ.init(w,b),$w.init(w,b)});var uD=O("ZodCIDRv4",(w,b)=>{lQ.init(w,b),$w.init(w,b)});var fD=O("ZodCIDRv6",(w,b)=>{iQ.init(w,b),$w.init(w,b)});var cD=O("ZodBase64",(w,b)=>{pQ.init(w,b),$w.init(w,b)});var mD=O("ZodBase64URL",(w,b)=>{oQ.init(w,b),$w.init(w,b)});var gD=O("ZodE164",(w,b)=>{dQ.init(w,b),$w.init(w,b)});var lD=O("ZodJWT",(w,b)=>{tQ.init(w,b),$w.init(w,b)});var IG=O("ZodNumber",(w,b)=>{P4.init(w,b),Yw.init(w,b),w.gt=(W,Q)=>w.check(_b(W,Q)),w.gte=(W,Q)=>w.check(E0(W,Q)),w.min=(W,Q)=>w.check(E0(W,Q)),w.lt=(W,Q)=>w.check(vb(W,Q)),w.lte=(W,Q)=>w.check(N0(W,Q)),w.max=(W,Q)=>w.check(N0(W,Q)),w.int=(W)=>w.check(ZG(W)),w.safe=(W)=>w.check(ZG(W)),w.positive=(W)=>w.check(_b(0,W)),w.nonnegative=(W)=>w.check(E0(0,W)),w.negative=(W)=>w.check(vb(0,W)),w.nonpositive=(W)=>w.check(N0(0,W)),w.multipleOf=(W,Q)=>w.check(kb(W,Q)),w.step=(W,Q)=>w.check(kb(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 t(w){return o8(IG,w)}var iD=O("ZodNumberFormat",(w,b)=>{rQ.init(w,b),IG.init(w,b)});function ZG(w){return d8(iD,w)}var nD=O("ZodBoolean",(w,b)=>{sQ.init(w,b),Yw.init(w,b)});function Uw(w){return t8(nD,w)}var pD=O("ZodNull",(w,b)=>{eQ.init(w,b),Yw.init(w,b)});function m4(w){return r8(pD,w)}var oD=O("ZodUnknown",(w,b)=>{aQ.init(w,b),Yw.init(w,b)});function Ww(){return s8(oD)}var dD=O("ZodNever",(w,b)=>{w8.init(w,b),Yw.init(w,b)});function tD(w){return e8(dD,w)}var rD=O("ZodArray",(w,b)=>{b8.init(w,b),Yw.init(w,b),w.element=b.element,w.min=($,W)=>w.check(i1($,W)),w.nonempty=($)=>w.check(i1(1,$)),w.max=($,W)=>w.check(xb($,W)),w.length=($,W)=>w.check(yb($,W)),w.unwrap=()=>w.element});function g(w,b){return a8(rD,w,b)}var NG=O("ZodObject",(w,b)=>{Q8.init(w,b),Yw.init(w,b),o.defineLazy(w,"shape",()=>{return b.shape}),w.keyof=()=>jw(Object.keys(w._zod.def.shape)),w.catchall=($)=>w.clone({...w._zod.def,catchall:$}),w.passthrough=()=>w.clone({...w._zod.def,catchall:Ww()}),w.loose=()=>w.clone({...w._zod.def,catchall:Ww()}),w.strict=()=>w.clone({...w._zod.def,catchall:tD()}),w.strip=()=>w.clone({...w._zod.def,catchall:void 0}),w.extend=($)=>{return o.extend(w,$)},w.safeExtend=($)=>{return o.safeExtend(w,$)},w.merge=($)=>o.merge(w,$),w.pick=($)=>o.pick(w,$),w.omit=($)=>o.omit(w,$),w.partial=(...$)=>o.partial(RG,w,$[0]),w.required=(...$)=>o.required(SG,w,$[0])});function N(w,b){let $={type:"object",shape:w??{},...o.normalizeParams(b)};return new NG($)}function Pw(w,b){return new NG({type:"object",shape:w,catchall:Ww(),...o.normalizeParams(b)})}var EG=O("ZodUnion",(w,b)=>{Z4.init(w,b),Yw.init(w,b),w.options=b.options});function e(w,b){return new EG({type:"union",options:w,...o.normalizeParams(b)})}var sD=O("ZodDiscriminatedUnion",(w,b)=>{EG.init(w,b),G8.init(w,b)});function g4(w,b,$){return new sD({type:"union",options:b,discriminator:w,...o.normalizeParams($)})}var eD=O("ZodIntersection",(w,b)=>{X8.init(w,b),Yw.init(w,b)});function fb(w,b){return new eD({type:"intersection",left:w,right:b})}var aD=O("ZodRecord",(w,b)=>{Y8.init(w,b),Yw.init(w,b),w.keyType=b.keyType,w.valueType=b.valueType});function Qw(w,b,$){return new aD({type:"record",keyType:w,valueType:b,...o.normalizeParams($)})}var f4=O("ZodEnum",(w,b)=>{J8.init(w,b),Yw.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 G={};for(let X of W)if($.has(X))G[X]=b.entries[X];else throw Error(`Key ${X} not found in enum`);return new f4({...b,checks:[],...o.normalizeParams(Q),entries:G})},w.exclude=(W,Q)=>{let G={...b.entries};for(let X of W)if($.has(X))delete G[X];else throw Error(`Key ${X} not found in enum`);return new f4({...b,checks:[],...o.normalizeParams(Q),entries:G})}});function jw(w,b){let $=Array.isArray(w)?Object.fromEntries(w.map((W)=>[W,W])):w;return new f4({type:"enum",entries:$,...o.normalizeParams(b)})}var wU=O("ZodLiteral",(w,b)=>{H8.init(w,b),Yw.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 E(w,b){return new wU({type:"literal",values:Array.isArray(w)?w:[w],...o.normalizeParams(b)})}var bU=O("ZodTransform",(w,b)=>{z8.init(w,b),Yw.init(w,b),w._zod.parse=($,W)=>{if(W.direction==="backward")throw new B0(w.constructor.name);$.addIssue=(G)=>{if(typeof G==="string")$.issues.push(o.issue(G,$.value,b));else{let X=G;if(X.fatal)X.continue=!1;X.code??(X.code="custom"),X.input??(X.input=$.value),X.inst??(X.inst=w),$.issues.push(o.issue(X))}};let Q=b.transform($.value,$);if(Q instanceof Promise)return Q.then((G)=>{return $.value=G,$});return $.value=Q,$}});function TG(w){return new bU({type:"transform",transform:w})}var RG=O("ZodOptional",(w,b)=>{D8.init(w,b),Yw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function Xw(w){return new RG({type:"optional",innerType:w})}var $U=O("ZodNullable",(w,b)=>{U8.init(w,b),Yw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function VG(w){return new $U({type:"nullable",innerType:w})}var WU=O("ZodDefault",(w,b)=>{A8.init(w,b),Yw.init(w,b),w.unwrap=()=>w._zod.def.innerType,w.removeDefault=w.unwrap});function QU(w,b){return new WU({type:"default",innerType:w,get defaultValue(){return typeof b==="function"?b():o.shallowClone(b)}})}var GU=O("ZodPrefault",(w,b)=>{L8.init(w,b),Yw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function XU(w,b){return new GU({type:"prefault",innerType:w,get defaultValue(){return typeof b==="function"?b():o.shallowClone(b)}})}var SG=O("ZodNonOptional",(w,b)=>{F8.init(w,b),Yw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function YU(w,b){return new SG({type:"nonoptional",innerType:w,...o.normalizeParams(b)})}var JU=O("ZodCatch",(w,b)=>{B8.init(w,b),Yw.init(w,b),w.unwrap=()=>w._zod.def.innerType,w.removeCatch=w.unwrap});function HU(w,b){return new JU({type:"catch",innerType:w,catchValue:typeof b==="function"?b:()=>b})}var zU=O("ZodPipe",(w,b)=>{K8.init(w,b),Yw.init(w,b),w.in=b.in,w.out=b.out});function c4(w,b){return new zU({type:"pipe",in:w,out:b})}var DU=O("ZodReadonly",(w,b)=>{O8.init(w,b),Yw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function UU(w){return new DU({type:"readonly",innerType:w})}var CG=O("ZodCustom",(w,b)=>{M8.init(w,b),Yw.init(w,b)});function vG(w,b){return wG(CG,w??(()=>!0),b)}function AU(w,b={}){return bG(CG,w,b)}function LU(w){return $G(w)}function l4(w,b){return c4(TG(w),b)}_w(V4());var i4="2025-11-25";var _G=[i4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Z1="io.modelcontextprotocol/related-task",mb="2.0",Lw=vG((w)=>w!==null&&(typeof w==="object"||typeof w==="function")),kG=e([B(),t().int()]),xG=B(),Pj=Pw({ttl:e([t(),m4()]).optional(),pollInterval:t().optional()}),FU=N({ttl:t().optional()}),BU=N({taskId:B()}),n4=Pw({progressToken:kG.optional(),[Z1]:BU.optional()}),Cw=N({_meta:n4.optional()}),S0=Cw.extend({task:FU.optional()}),yG=(w)=>S0.safeParse(w).success,Fw=N({method:B(),params:Cw.loose().optional()}),kw=N({_meta:n4.optional()}),xw=N({method:B(),params:kw.loose().optional()}),Bw=Pw({_meta:n4.optional()}),gb=e([B(),t().int()]),hG=N({jsonrpc:E(mb),id:gb,...Fw.shape}).strict(),p4=(w)=>hG.safeParse(w).success,uG=N({jsonrpc:E(mb),...xw.shape}).strict(),fG=(w)=>uG.safeParse(w).success,o4=N({jsonrpc:E(mb),id:gb,result:Bw}).strict(),C0=(w)=>o4.safeParse(w).success;var l;(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"})(l||(l={}));var d4=N({jsonrpc:E(mb),id:gb.optional(),error:N({code:t().int(),message:B(),data:Ww().optional()})}).strict();var cG=(w)=>d4.safeParse(w).success;var mG=e([hG,uG,o4,d4]),Zj=e([o4,d4]),lb=Bw.strict(),KU=kw.extend({requestId:gb.optional(),reason:B().optional()}),ib=xw.extend({method:E("notifications/cancelled"),params:KU}),OU=N({src:B(),mimeType:B().optional(),sizes:g(B()).optional(),theme:jw(["light","dark"]).optional()}),v0=N({icons:g(OU).optional()}),p1=N({name:B(),title:B().optional()}),gG=p1.extend({...p1.shape,...v0.shape,version:B(),websiteUrl:B().optional(),description:B().optional()}),MU=fb(N({applyDefaults:Uw().optional()}),Qw(B(),Ww())),qU=l4((w)=>{if(w&&typeof w==="object"&&!Array.isArray(w)){if(Object.keys(w).length===0)return{form:{}}}return w},fb(N({form:MU.optional(),url:Lw.optional()}),Qw(B(),Ww()).optional())),PU=Pw({list:Lw.optional(),cancel:Lw.optional(),requests:Pw({sampling:Pw({createMessage:Lw.optional()}).optional(),elicitation:Pw({create:Lw.optional()}).optional()}).optional()}),ZU=Pw({list:Lw.optional(),cancel:Lw.optional(),requests:Pw({tools:Pw({call:Lw.optional()}).optional()}).optional()}),VU=N({experimental:Qw(B(),Lw).optional(),sampling:N({context:Lw.optional(),tools:Lw.optional()}).optional(),elicitation:qU.optional(),roots:N({listChanged:Uw().optional()}).optional(),tasks:PU.optional()}),jU=Cw.extend({protocolVersion:B(),capabilities:VU,clientInfo:gG}),t4=Fw.extend({method:E("initialize"),params:jU});var IU=N({experimental:Qw(B(),Lw).optional(),logging:Lw.optional(),completions:Lw.optional(),prompts:N({listChanged:Uw().optional()}).optional(),resources:N({subscribe:Uw().optional(),listChanged:Uw().optional()}).optional(),tools:N({listChanged:Uw().optional()}).optional(),tasks:ZU.optional()}),NU=Bw.extend({protocolVersion:B(),capabilities:IU,serverInfo:gG,instructions:B().optional()}),r4=xw.extend({method:E("notifications/initialized"),params:kw.optional()});var nb=Fw.extend({method:E("ping"),params:Cw.optional()}),EU=N({progress:t(),total:Xw(t()),message:Xw(B())}),TU=N({...kw.shape,...EU.shape,progressToken:kG}),pb=xw.extend({method:E("notifications/progress"),params:TU}),RU=Cw.extend({cursor:xG.optional()}),_0=Fw.extend({params:RU.optional()}),k0=Bw.extend({nextCursor:xG.optional()}),SU=jw(["working","input_required","completed","failed","cancelled"]),x0=N({taskId:B(),status:SU,ttl:e([t(),m4()]),createdAt:B(),lastUpdatedAt:B(),pollInterval:Xw(t()),statusMessage:Xw(B())}),o1=Bw.extend({task:x0}),CU=kw.merge(x0),y0=xw.extend({method:E("notifications/tasks/status"),params:CU}),ob=Fw.extend({method:E("tasks/get"),params:Cw.extend({taskId:B()})}),db=Bw.merge(x0),tb=Fw.extend({method:E("tasks/result"),params:Cw.extend({taskId:B()})}),Vj=Bw.loose(),rb=_0.extend({method:E("tasks/list")}),sb=k0.extend({tasks:g(x0)}),eb=Fw.extend({method:E("tasks/cancel"),params:Cw.extend({taskId:B()})}),lG=Bw.merge(x0),iG=N({uri:B(),mimeType:Xw(B()),_meta:Qw(B(),Ww()).optional()}),nG=iG.extend({text:B()}),s4=B().refine((w)=>{try{return atob(w),!0}catch{return!1}},{message:"Invalid Base64 string"}),pG=iG.extend({blob:s4}),h0=jw(["user","assistant"]),d1=N({audience:g(h0).optional(),priority:t().min(0).max(1).optional(),lastModified:R0.datetime({offset:!0}).optional()}),oG=N({...p1.shape,...v0.shape,uri:B(),description:Xw(B()),mimeType:Xw(B()),annotations:d1.optional(),_meta:Xw(Pw({}))}),vU=N({...p1.shape,...v0.shape,uriTemplate:B(),description:Xw(B()),mimeType:Xw(B()),annotations:d1.optional(),_meta:Xw(Pw({}))}),e4=_0.extend({method:E("resources/list")}),_U=k0.extend({resources:g(oG)}),kU=_0.extend({method:E("resources/templates/list")}),xU=k0.extend({resourceTemplates:g(vU)}),a4=Cw.extend({uri:B()}),yU=a4,w6=Fw.extend({method:E("resources/read"),params:yU}),hU=Bw.extend({contents:g(e([nG,pG]))}),uU=xw.extend({method:E("notifications/resources/list_changed"),params:kw.optional()}),fU=a4,cU=Fw.extend({method:E("resources/subscribe"),params:fU}),mU=a4,gU=Fw.extend({method:E("resources/unsubscribe"),params:mU}),lU=kw.extend({uri:B()}),iU=xw.extend({method:E("notifications/resources/updated"),params:lU}),nU=N({name:B(),description:Xw(B()),required:Xw(Uw())}),pU=N({...p1.shape,...v0.shape,description:Xw(B()),arguments:Xw(g(nU)),_meta:Xw(Pw({}))}),oU=_0.extend({method:E("prompts/list")}),dU=k0.extend({prompts:g(pU)}),tU=Cw.extend({name:B(),arguments:Qw(B(),B()).optional()}),rU=Fw.extend({method:E("prompts/get"),params:tU}),b6=N({type:E("text"),text:B(),annotations:d1.optional(),_meta:Qw(B(),Ww()).optional()}),$6=N({type:E("image"),data:s4,mimeType:B(),annotations:d1.optional(),_meta:Qw(B(),Ww()).optional()}),W6=N({type:E("audio"),data:s4,mimeType:B(),annotations:d1.optional(),_meta:Qw(B(),Ww()).optional()}),sU=N({type:E("tool_use"),name:B(),id:B(),input:Qw(B(),Ww()),_meta:Qw(B(),Ww()).optional()}),eU=N({type:E("resource"),resource:e([nG,pG]),annotations:d1.optional(),_meta:Qw(B(),Ww()).optional()}),aU=oG.extend({type:E("resource_link")}),Q6=e([b6,$6,W6,aU,eU]),w3=N({role:h0,content:Q6}),b3=Bw.extend({description:B().optional(),messages:g(w3)}),$3=xw.extend({method:E("notifications/prompts/list_changed"),params:kw.optional()}),W3=N({title:B().optional(),readOnlyHint:Uw().optional(),destructiveHint:Uw().optional(),idempotentHint:Uw().optional(),openWorldHint:Uw().optional()}),Q3=N({taskSupport:jw(["required","optional","forbidden"]).optional()}),dG=N({...p1.shape,...v0.shape,description:B().optional(),inputSchema:N({type:E("object"),properties:Qw(B(),Lw).optional(),required:g(B()).optional()}).catchall(Ww()),outputSchema:N({type:E("object"),properties:Qw(B(),Lw).optional(),required:g(B()).optional()}).catchall(Ww()).optional(),annotations:W3.optional(),execution:Q3.optional(),_meta:Qw(B(),Ww()).optional()}),G6=_0.extend({method:E("tools/list")}),G3=k0.extend({tools:g(dG)}),ab=Bw.extend({content:g(Q6).default([]),structuredContent:Qw(B(),Ww()).optional(),isError:Uw().optional()}),jj=ab.or(Bw.extend({toolResult:Ww()})),X3=S0.extend({name:B(),arguments:Qw(B(),Ww()).optional()}),u0=Fw.extend({method:E("tools/call"),params:X3}),Y3=xw.extend({method:E("notifications/tools/list_changed"),params:kw.optional()}),Ij=N({autoRefresh:Uw().default(!0),debounceMs:t().int().nonnegative().default(300)}),f0=jw(["debug","info","notice","warning","error","critical","alert","emergency"]),J3=Cw.extend({level:f0}),X6=Fw.extend({method:E("logging/setLevel"),params:J3}),H3=kw.extend({level:f0,logger:B().optional(),data:Ww()}),z3=xw.extend({method:E("notifications/message"),params:H3}),D3=N({name:B().optional()}),U3=N({hints:g(D3).optional(),costPriority:t().min(0).max(1).optional(),speedPriority:t().min(0).max(1).optional(),intelligencePriority:t().min(0).max(1).optional()}),A3=N({mode:jw(["auto","required","none"]).optional()}),L3=N({type:E("tool_result"),toolUseId:B().describe("The unique identifier for the corresponding tool call."),content:g(Q6).default([]),structuredContent:N({}).loose().optional(),isError:Uw().optional(),_meta:Qw(B(),Ww()).optional()}),F3=g4("type",[b6,$6,W6]),cb=g4("type",[b6,$6,W6,sU,L3]),B3=N({role:h0,content:e([cb,g(cb)]),_meta:Qw(B(),Ww()).optional()}),K3=S0.extend({messages:g(B3),modelPreferences:U3.optional(),systemPrompt:B().optional(),includeContext:jw(["none","thisServer","allServers"]).optional(),temperature:t().optional(),maxTokens:t().int(),stopSequences:g(B()).optional(),metadata:Lw.optional(),tools:g(dG).optional(),toolChoice:A3.optional()}),O3=Fw.extend({method:E("sampling/createMessage"),params:K3}),Y6=Bw.extend({model:B(),stopReason:Xw(jw(["endTurn","stopSequence","maxTokens"]).or(B())),role:h0,content:F3}),J6=Bw.extend({model:B(),stopReason:Xw(jw(["endTurn","stopSequence","maxTokens","toolUse"]).or(B())),role:h0,content:e([cb,g(cb)])}),M3=N({type:E("boolean"),title:B().optional(),description:B().optional(),default:Uw().optional()}),q3=N({type:E("string"),title:B().optional(),description:B().optional(),minLength:t().optional(),maxLength:t().optional(),format:jw(["email","uri","date","date-time"]).optional(),default:B().optional()}),P3=N({type:jw(["number","integer"]),title:B().optional(),description:B().optional(),minimum:t().optional(),maximum:t().optional(),default:t().optional()}),Z3=N({type:E("string"),title:B().optional(),description:B().optional(),enum:g(B()),default:B().optional()}),V3=N({type:E("string"),title:B().optional(),description:B().optional(),oneOf:g(N({const:B(),title:B()})),default:B().optional()}),j3=N({type:E("string"),title:B().optional(),description:B().optional(),enum:g(B()),enumNames:g(B()).optional(),default:B().optional()}),I3=e([Z3,V3]),N3=N({type:E("array"),title:B().optional(),description:B().optional(),minItems:t().optional(),maxItems:t().optional(),items:N({type:E("string"),enum:g(B())}),default:g(B()).optional()}),E3=N({type:E("array"),title:B().optional(),description:B().optional(),minItems:t().optional(),maxItems:t().optional(),items:N({anyOf:g(N({const:B(),title:B()}))}),default:g(B()).optional()}),T3=e([N3,E3]),R3=e([j3,I3,T3]),S3=e([R3,M3,q3,P3]),C3=S0.extend({mode:E("form").optional(),message:B(),requestedSchema:N({type:E("object"),properties:Qw(B(),S3),required:g(B()).optional()})}),v3=S0.extend({mode:E("url"),message:B(),elicitationId:B(),url:B().url()}),_3=e([C3,v3]),k3=Fw.extend({method:E("elicitation/create"),params:_3}),x3=kw.extend({elicitationId:B()}),y3=xw.extend({method:E("notifications/elicitation/complete"),params:x3}),w$=Bw.extend({action:jw(["accept","decline","cancel"]),content:l4((w)=>w===null?void 0:w,Qw(B(),e([B(),t(),Uw(),g(B())])).optional())}),h3=N({type:E("ref/resource"),uri:B()});var u3=N({type:E("ref/prompt"),name:B()}),f3=Cw.extend({ref:e([u3,h3]),argument:N({name:B(),value:B()}),context:N({arguments:Qw(B(),B()).optional()}).optional()}),c3=Fw.extend({method:E("completion/complete"),params:f3});var m3=Bw.extend({completion:Pw({values:g(B()).max(100),total:Xw(t().int()),hasMore:Xw(Uw())})}),g3=N({uri:B().startsWith("file://"),name:B().optional(),_meta:Qw(B(),Ww()).optional()}),l3=Fw.extend({method:E("roots/list"),params:Cw.optional()}),H6=Bw.extend({roots:g(g3)}),i3=xw.extend({method:E("notifications/roots/list_changed"),params:kw.optional()}),Nj=e([nb,t4,c3,X6,rU,oU,e4,kU,w6,cU,gU,u0,G6,ob,tb,rb,eb]),Ej=e([ib,pb,r4,i3,y0]),Tj=e([lb,Y6,J6,w$,H6,db,sb,o1]),Rj=e([nb,O3,k3,l3,ob,tb,rb,eb]),Sj=e([ib,pb,z3,iU,uU,Y3,$3,y0,y3]),Cj=e([lb,NU,m3,b3,dU,_U,xU,hU,ab,G3,db,sb,o1]);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===l.UrlElicitationRequired&&$){let W=$;if(W.elicitations)return new tG(W.elicitations,b)}return new u(w,b,$)}}class tG extends u{constructor(w,b=`URL elicitation${w.length>1?"s":""} required`){super(l.UrlElicitationRequired,b,{elicitations:w})}get elicitations(){return this.data?.elicitations??[]}}function V1(w){return w==="completed"||w==="failed"||w==="cancelled"}var n3=Symbol("Let zodToJsonSchema decide on which parser to use");var zI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function z6(w){let $=hb(w)?.method;if(!$)throw Error("Schema is missing a method literal");let W=WG($);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function D6(w,b){let $=P1(w,b);if(!$.success)throw $.error;return $.data}var s3=60000;class U6{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(ib,(b)=>{this._oncancel(b)}),this.setNotificationHandler(pb,(b)=>{this._onprogress(b)}),this.setRequestHandler(nb,(b)=>({})),this._taskStore=w?.taskStore,this._taskMessageQueue=w?.taskMessageQueue,this._taskStore)this.setRequestHandler(ob,async(b,$)=>{let W=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!W)throw new u(l.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(tb,async(b,$)=>{let W=async()=>{let Q=b.params.taskId;if(this._taskMessageQueue){let X;while(X=await this._taskMessageQueue.dequeue(Q,$.sessionId)){if(X.type==="response"||X.type==="error"){let Y=X.message,J=Y.id,H=this._requestResolvers.get(J);if(H)if(this._requestResolvers.delete(J),X.type==="response")H(Y);else{let z=Y,D=new u(z.error.code,z.error.message,z.error.data);H(D)}else{let z=X.type==="response"?"Response":"Error";this._onerror(Error(`${z} handler missing for request ${J}`))}continue}await this._transport?.send(X.message,{relatedRequestId:$.requestId})}}let G=await this._taskStore.getTask(Q,$.sessionId);if(!G)throw new u(l.InvalidParams,`Task not found: ${Q}`);if(!V1(G.status))return await this._waitForTaskUpdate(Q,$.signal),await W();if(V1(G.status)){let X=await this._taskStore.getTaskResult(Q,$.sessionId);return this._clearTaskQueue(Q),{...X,_meta:{...X._meta,[Z1]:{taskId:Q}}}}return await W()};return await W()}),this.setRequestHandler(rb,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(l.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(eb,async(b,$)=>{try{let W=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!W)throw new u(l.InvalidParams,`Task not found: ${b.params.taskId}`);if(V1(W.status))throw new u(l.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(l.InvalidParams,`Task not found after cancellation: ${b.params.taskId}`);return{_meta:{},...Q}}catch(W){if(W instanceof u)throw W;throw new u(l.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(l.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,G)=>{if(W?.(Q,G),C0(Q)||cG(Q))this._onresponse(Q);else if(p4(Q))this._onrequest(Q,G);else if(fG(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(l.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?.[Z1]?.taskId;if($===void 0){let H={jsonrpc:"2.0",id:w.id,error:{code:l.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 G=new AbortController;this._requestHandlerAbortControllers.set(w.id,G);let X=yG(w.params)?w.params.task:void 0,Y=this._taskStore?this.requestTaskStore(w,W?.sessionId):void 0,J={signal:G.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,D)=>{let A={...D,relatedRequestId:w.id};if(Q&&!A.relatedTask)A.relatedTask={taskId:Q};let L=A.relatedTask?.taskId??Q;if(L&&Y)await Y.updateTaskStatus(L,"input_required");return await this.request(H,z,A)},authInfo:b?.authInfo,requestId:w.id,requestInfo:b?.requestInfo,taskId:Q,taskStore:Y,taskRequestedTtl:X?.ttl,closeSSEStream:b?.closeSSEStream,closeStandaloneSSEStream:b?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(X)this.assertTaskHandlerCapability(w.method)}).then(()=>$(w,J)).then(async(H)=>{if(G.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(G.signal.aborted)return;let z={jsonrpc:"2.0",id:w.id,error:{code:Number.isSafeInteger(H.code)?H.code:l.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 G=this._responseHandlers.get(W),X=this._timeoutInfo.get(W);if(X&&G&&X.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(Y){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),G(Y);return}Q($)}_onresponse(w){let b=Number(w.id),$=this._requestResolvers.get(b);if($){if(this._requestResolvers.delete(b),C0(w))$(w);else{let G=new u(w.error.code,w.error.message,w.error.data);$(G)}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(C0(w)&&w.result&&typeof w.result==="object"){let G=w.result;if(G.task&&typeof G.task==="object"){let X=G.task;if(typeof X.taskId==="string")Q=!0,this._taskProgressTokens.set(X.taskId,b)}}if(!Q)this._progressHandlers.delete(b);if(C0(w))W(w);else{let G=u.fromError(w.error.code,w.error.message,w.error.data);W(G)}}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(G){yield{type:"error",error:G instanceof u?G:new u(l.InternalError,String(G))}}return}let Q;try{let G=await this.request(w,o1,$);if(G.task)Q=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new u(l.InternalError,"Task creation did not return a task");while(!0){let X=await this.getTask({taskId:Q},$);if(yield{type:"taskStatus",task:X},V1(X.status)){if(X.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Q},b,$)};else if(X.status==="failed")yield{type:"error",error:new u(l.InternalError,`Task ${Q} failed`)};else if(X.status==="cancelled")yield{type:"error",error:new u(l.InternalError,`Task ${Q} was cancelled`)};return}if(X.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Q},b,$)};return}let Y=X.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((J)=>setTimeout(J,Y)),$?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof u?G:new u(l.InternalError,String(G))}}}request(w,b,$){let{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G,task:X,relatedTask:Y}=$??{};return new Promise((J,H)=>{let z=(V)=>{H(V)};if(!this._transport){z(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(w.method),X)this.assertTaskCapability(w.method)}catch(V){z(V);return}$?.signal?.throwIfAborted();let D=this._requestMessageId++,A={...w,jsonrpc:"2.0",id:D};if($?.onprogress)this._progressHandlers.set(D,$.onprogress),A.params={...w.params,_meta:{...w.params?._meta||{},progressToken:D}};if(X)A.params={...A.params,task:X};if(Y)A.params={...A.params,_meta:{...A.params?._meta||{},[Z1]:Y}};let L=(V)=>{this._responseHandlers.delete(D),this._progressHandlers.delete(D),this._cleanupTimeout(D),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:D,reason:String(V)}},{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((R)=>this._onerror(Error(`Failed to send cancellation: ${R}`)));let C=V instanceof u?V:new u(l.RequestTimeout,String(V));H(C)};this._responseHandlers.set(D,(V)=>{if($?.signal?.aborted)return;if(V instanceof Error)return H(V);try{let C=P1(b,V.result);if(!C.success)H(C.error);else J(C.data)}catch(C){H(C)}}),$?.signal?.addEventListener("abort",()=>{L($?.signal?.reason)});let K=$?.timeout??s3,M=()=>L(u.fromError(l.RequestTimeout,"Request timed out",{timeout:K}));this._setupTimeout(D,K,$?.maxTotalTimeout,M,$?.resetTimeoutOnProgress??!1);let j=Y?.taskId;if(j){let V=(C)=>{let R=this._responseHandlers.get(D);if(R)R(C);else this._onerror(Error(`Response handler missing for side-channeled request ${D}`))};this._requestResolvers.set(D,V),this._enqueueTaskMessage(j,{type:"request",message:A,timestamp:Date.now()}).catch((C)=>{this._cleanupTimeout(D),H(C)})}else this._transport.send(A,{relatedRequestId:W,resumptionToken:Q,onresumptiontoken:G}).catch((V)=>{this._cleanupTimeout(D),H(V)})})}async getTask(w,b){return this.request({method:"tasks/get",params:w},db,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},sb,b)}async cancelTask(w,b){return this.request({method:"tasks/cancel",params:w},lG,b)}async notification(w,b){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(w.method);let $=b?.relatedTask?.taskId;if($){let X={...w,jsonrpc:"2.0",params:{...w.params,_meta:{...w.params?._meta||{},[Z1]:b.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:X,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 X={...w,jsonrpc:"2.0"};if(b?.relatedTask)X={...X,params:{...X.params,_meta:{...X.params?._meta||{},[Z1]:b.relatedTask}}};this._transport?.send(X,b).catch((Y)=>this._onerror(Y))});return}let G={...w,jsonrpc:"2.0"};if(b?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[Z1]:b.relatedTask}}};await this._transport.send(G,b)}setRequestHandler(w,b){let $=z6(w);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(W,Q)=>{let G=D6(w,W);return Promise.resolve(b(G,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 $=z6(w);this._notificationHandlers.set($,(W)=>{let Q=D6(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"&&p4(W.message)){let Q=W.message.id,G=this._requestResolvers.get(Q);if(G)G(new u(l.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(l.InvalidRequest,"Request cancelled"));return}let G=setTimeout(W,$);b.addEventListener("abort",()=>{clearTimeout(G),Q(new u(l.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(l.InvalidParams,"Failed to retrieve task: Task not found");return Q},storeTaskResult:async(W,Q,G)=>{await $.storeTaskResult(W,Q,G,b);let X=await $.getTask(W,b);if(X){let Y=y0.parse({method:"notifications/tasks/status",params:X});if(await this.notification(Y),V1(X.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return $.getTaskResult(W,b)},updateTaskStatus:async(W,Q,G)=>{let X=await $.getTask(W,b);if(!X)throw new u(l.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(V1(X.status))throw new u(l.InvalidParams,`Cannot update task "${W}" from terminal status "${X.status}" to "${Q}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(W,Q,G,b);let Y=await $.getTask(W,b);if(Y){let J=y0.parse({method:"notifications/tasks/status",params:Y});if(await this.notification(J),V1(Y.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return $.listTasks(W,b)}}}}function rG(w){return w!==null&&typeof w==="object"&&!Array.isArray(w)}function sG(w,b){let $={...w};for(let W in b){let Q=W,G=b[Q];if(G===void 0)continue;let X=$[Q];if(rG(X)&&rG(G))$[Q]={...X,...G};else $[Q]=G}return $}var T7=e9(X9(),1),R7=e9(E7(),1);function XP(){let w=new T7.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return R7.default(w),w}class B9{constructor(w){this._ajv=w??XP()}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 K9{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 S7(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 C7(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 O9 extends U6{constructor(w,b){super(b);if(this._serverInfo=w,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(f0.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 B9,this.setRequestHandler(t4,($)=>this._oninitialize($)),this.setNotificationHandler(r4,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(X6,async($,W)=>{let Q=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:G}=$.params,X=f0.safeParse(G);if(X.success)this._loggingLevels.set(Q,X.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new K9(this)};return this._experimental}registerCapabilities(w){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=sG(this._capabilities,w)}setRequestHandler(w,b){let W=hb(w)?.method;if(!W)throw Error("Schema is missing a method literal");let Q;if(n1(W)){let X=W;Q=X._zod?.def?.value??X.value}else{let X=W;Q=X._def?.value??X.value}if(typeof Q!=="string")throw Error("Schema method literal must be a string");if(Q==="tools/call"){let X=async(Y,J)=>{let H=P1(u0,Y);if(!H.success){let L=H.error instanceof Error?H.error.message:String(H.error);throw new u(l.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:z}=H.data,D=await Promise.resolve(b(Y,J));if(z.task){let L=P1(o1,D);if(!L.success){let K=L.error instanceof Error?L.error.message:String(L.error);throw new u(l.InvalidParams,`Invalid task creation result: ${K}`)}return L.data}let A=P1(ab,D);if(!A.success){let L=A.error instanceof Error?A.error.message:String(A.error);throw new u(l.InvalidParams,`Invalid tools/call result: ${L}`)}return A.data};return super.setRequestHandler(w,X)}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){C7(this._clientCapabilities?.tasks?.requests,w,"Client")}assertTaskHandlerCapability(w){if(!this._capabilities)return;S7(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:_G.includes(b)?b:i4,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"},lb)}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((J)=>J.type==="tool_result"),G=w.messages.length>1?w.messages[w.messages.length-2]:void 0,X=G?Array.isArray(G.content)?G.content:[G.content]:[],Y=X.some((J)=>J.type==="tool_use");if(Q){if(W.some((J)=>J.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!Y)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(Y){let J=new Set(X.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(J.size!==H.size||![...J].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},J6,b);return this.request({method:"sampling/createMessage",params:w},Y6,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},w$,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},w$,b);if(Q.action==="accept"&&Q.content&&W.requestedSchema)try{let X=this._jsonSchemaValidator.getValidator(W.requestedSchema)(Q.content);if(!X.valid)throw new u(l.InvalidParams,`Elicitation response content does not match requested schema: ${X.errorMessage}`)}catch(G){if(G instanceof u)throw G;throw new u(l.InternalError,`Error validating elicitation response: ${G instanceof Error?G.message:String(G)}`)}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},H6,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 v7={name:"@sequenzy/mcp",version:"0.0.129",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 M9=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],_7={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 JP(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 w1(w){return encodeURIComponent(w)}function zw(w,b){return`${w}${b}`}function Dw(w,b=""){return`/dashboard/company/${w1(w)}${b}`}function k7(w,b,$){return zw(w,`${Dw(b,"/settings")}?tab=${encodeURIComponent($)}`)}function HP(w,b){let $=M9.map((W)=>[W,b?k7(w,b,W):""]);return Object.fromEntries($)}function D1(w={},b){let $=JP(b),W=ow(w.companyId),Q={},G=HP($,W);if(!W)return{appUrl:$,routeTemplates:_7,settingsTabValues:M9,urls:Q,settingsUrls:G};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 X=ow(w.campaignId);if(X)Q.campaign=zw($,Dw(W,`/campaign/${w1(X)}`)),Q.campaignPreview=`${Q.campaign}?step=review`;let Y=ow(w.landingPageId);if(Y)Q.landingPage=zw($,Dw(W,`/landing-pages/${w1(Y)}`));let J=ow(w.sequenceId);if(J)Q.sequence=zw($,Dw(W,`/sequences/${w1(J)}`));let H=ow(w.emailId)??ow(w.templateId);if(H)Q.email=zw($,Dw(W,`/emails/${w1(H)}`)),Q.template=Q.email;let z=ow(w.transactionalId);if(z)Q.transactionalEmail=zw($,Dw(W,`/transactional/${w1(z)}`));let D=ow(w.emailSendId);if(D)Q.emailSend=zw($,Dw(W,`/sent-emails/${w1(D)}`));let A=ow(w.domainId);if(A)Q.domain=zw($,Dw(W,`/settings/domain/${w1(A)}`)),Q.domainVerify=`${Q.domain}/verify`;let L=ow(w.status);if(L)Q.campaignList=zw($,Dw(W,`/campaign/list/${w1(L)}`)),Q.sequenceList=zw($,Dw(W,`/sequences/list/${w1(L)}`));let K=ow(w.settingsTab);if(K)Q.settingsTab=k7($,W,K);return{appUrl:$,routeTemplates:_7,settingsTabValues:M9,urls:Q,settingsUrls:G}}var x7=[{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 y7(w){try{let b;switch(w){case"sequenzy://dashboard":b=await U("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await U("GET","/api/v1/account"),W=B1()??$.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");b=await U("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":b=await U("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":b=await U("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":b=await U("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":b=await U("GET","/api/v1/sequences");break;case"sequenzy://templates":b=await U("GET","/api/v1/templates");break;case"sequenzy://segments":b=await U("GET","/api/v1/segments");break;case"sequenzy://tags":b=await U("GET","/api/v1/tags");break;case"sequenzy://health":b=await U("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":b=D1();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:F1(b)}]}}}function k(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}function F(w,b){let $=w[b];if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function P(w,b,$){let W=F(b,$);if(W===void 0)throw Error(`\`${$}\` is required when calling \`${w}\`.`);return W}var f$=' 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 q9=' 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.',P9=' 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). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page.',Z9=' 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" }.',Jw="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.",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`.',U1=`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: [...] }.${q9}${P9}${Z9}${f$}`,A1=`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\`.${q9}${P9}${Z9}${f$}`,X0=`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.${q9}${P9}${Z9}${f$}`,zb="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.",h7="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.",V9=500,j9=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."},Db=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay","transport_failure"],Ub=Db.join(", "),c$={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},zP={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},Y0={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:zP,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},J0={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},I9={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.",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},m$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:I9,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},H0=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],z0=["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.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","sequence.finished","sequence.failed","poll.answered"];var DP=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_api_keys","list_websites","list_integrations","list_sender_profiles","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"]),UP=new Set(["select_company","create_company","update_company","update_sync_rules","update_shopify_automation_settings","create_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","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","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"]),AP=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","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"]),LP=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","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","remove_recipient_suppression"]);function FP(w){let b=DP.has(w),$=UP.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:LP.has(w),openWorldHint:AP.has(w)}}function u7(w){return{...w,annotations:{...w.annotations,...FP(w.name)}}}var N9={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"]},BP=Object.entries(N9).map(([w,b])=>`${w}: ${b.join(", ")}`).join("; "),E9={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: ${BP}.`},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},T9={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 g$(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 l$(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 $=g$([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(l$):[]}}function KP(w){let b=w.indexOf(":");return b!==-1&&w.substring(0,b).trim().length>0}function OP(w){let b=w.indexOf(":");return b!==-1&&w.substring(b+1).trim().length>0}function f7(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 MP(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 G=$.slice(0,-2).join(":").trim(),X=$.at(-2),Y=$.at(-1),J=X===void 0?Number.NaN:Number.parseInt(X,10);return G&&Number.isInteger(J)&&J>0&&Y!==void 0&&f7(Y)?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&&f7(Q)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function qP(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 PP(w){return w.trim().toLowerCase().replace(/[-\s]+/g,"_")}function ZP(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 VP(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 jP(w){return["is","is_not","gte","lte","gt","lt"].includes(w)}function IP(w,b,$){if(w==="stripeProduct"){if(b!=="at_least"&&b!=="less_than_count")return null;let Y=$.indexOf(":");if(Y===-1)return null;let J=$.substring(0,Y).trim(),H=Number.parseInt($.substring(Y+1).trim(),10);return J&&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:G}=qP($);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 X=PP(Q);if(ZP(X))return b==="is"||b==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!VP(w,X))return`Unsupported Stripe product subfilter "${Q}".`;if(!jP(b))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return G?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var c7=new Set(["shopify","woocommerce","api"]);function NP(w,b){let $=b.trim(),W=$.indexOf(":");if(W!==-1&&c7.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 G=$.substring(0,Q).trim(),X=Number.parseInt($.substring(Q+1).trim(),10);return G&&Number.isInteger(X)&&X>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function EP(w,b){let $=b.trim(),W=$.indexOf(":");if(W!==-1&&c7.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 G=$.substring(0,Q).trim(),X=Number.parseInt($.substring(Q+1).trim(),10);return G&&Number.isInteger(X)&&X>=1?null:'Purchased Collection threshold filters must use "provider:collection:count" with a count of at least 1.'}function TP(w){let b;try{b=JSON.parse(w)}catch{return`Poll response filters must use valid JSON. ${C1}`}if(!k(b)||b.v!==1||typeof b.campaignId!=="string"||!b.campaignId.trim()||typeof b.blockId!=="string"||!b.blockId.trim()||!k(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 i$(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 N9))return`Unsupported segment filter field "${String($)}".`;if(typeof W!=="string")return`Segment filter "${$}" must include an operator.`;let G=N9[$];if(!G.includes(W))return`Operator "${W}" is not supported for ${$} filters. Use one of: ${G.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(!KP(Q))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!OP(Q))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof Q==="string"){let X=MP(W,Q);if(X)return X}if($==="pollResponse"&&typeof Q==="string"){let X=TP(Q);if(X)return X}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof Q==="string"){let X=IP($,W,Q);if(X)return X}if($==="commerceProduct"&&typeof Q==="string"){let X=NP(W,Q);if(X)return X}if($==="commerceCollection"&&typeof Q==="string"){let X=EP(W,Q);if(X)return X}if($==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof Q==="string"&&Q.split(",").map((Y)=>Y.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function n$(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 $=i$(b);return $?[$]:[]}if(Array.isArray(b.children))return b.children.flatMap(n$);return[]}function vw(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 l7(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 G=i$(Q);return G?[G]:[]}):n$(w.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function i7(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 G=i$(Q);return G?[G]:[]}):$?n$(w.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}var R9=["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 S9(w,b,$){if(b[$]!==void 0&&!k(b[$]))throw Error(`\`${$}\` must be an object when calling \`${w}\`.`)}function m7(w,b,$){if(b[$]!==void 0&&!Array.isArray(b[$]))throw Error(`\`${$}\` must be an array when calling \`${w}\`.`)}function n7(w){let b=new Set(["companyId",...R9]),$=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 R9)if(w[Q]!==void 0)W[Q]=w[Q];if(Object.keys(W).length===0)throw Error(`Provide at least one of ${R9.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(S9("update_company",w,"brandColors"),S9("update_company",w,"socialLinks"),S9("update_company",w,"pricing"),w.emailTheme!==void 0&&w.emailTheme!==null&&!k(w.emailTheme))throw Error("`emailTheme` must be an object or null when calling `update_company`.");m7("update_company",w,"valueProps"),m7("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 G=w[Q];if(typeof G==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G.trim()))throw Error(`\`${Q}\` must be a valid email address when calling \`update_company\`.`)}return W}var p7=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function RP(w){return p7.some((b)=>w[b]!==void 0)}function SP(w){if(typeof w.nodeType==="string")return w.nodeType==="action_email";return w.type===void 0||w.type==="email"}function p$(w,b,$){for(let W of p7){let Q=$[W];if(Q!==void 0&&typeof Q!=="string")throw Error(`\`${W}\` must be a string for ${b} when calling \`${w}\`.`)}if($.senderProfileId!==void 0&&$.fromEmail!==void 0)throw Error(`Provide either \`senderProfileId\` or \`fromEmail\` for ${b} when calling \`${w}\`, not both.`);if($.replyProfileId!==void 0&&$.replyTo!==void 0)throw Error(`Provide either \`replyProfileId\` or \`replyTo\` for ${b} when calling \`${w}\`, not both.`);if($.replyToName!==void 0&&$.replyTo===void 0)throw Error(`\`replyToName\` requires \`replyTo\` for ${b} when calling \`${w}\`.`)}function v9(w,b,$){if(RP($)&&!SP($))throw Error(`Sender identity fields are only supported for email steps at ${b} when calling \`${w}\`.`);p$(w,b,$)}function g7(w,b,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(k(W))p$(w,`${b}[${Q}]`,W)})}function C9(w,b,$){if(!Array.isArray($))return;$.forEach((W,Q)=>{if(k(W))v9(w,`${b}[${Q}]`,W)})}function CP(w){if(g7("update_sequence","emails",w.emails),g7("update_sequence","steps",w.steps),k(w.insertSteps))C9("update_sequence","insertSteps.steps",w.insertSteps.steps);if(!k(w.branch))return;if(Array.isArray(w.branch.branches))w.branch.branches.forEach(($,W)=>{if(k($))C9("update_sequence",`branch.branches[${W}].steps`,$.steps)});C9("update_sequence","branch.elseSteps",w.branch.elseSteps)}function o7(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(w.fromEmail!==void 0&&w.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_sequence`, not both.");if(w.replyTo!==void 0&&w.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_sequence`, not both.");if(w.fromName!==void 0&&w.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_sequence`.");if(w.replyToName!==void 0&&w.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_sequence`.");if(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.");CP(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 vP(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,G=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"&&!G)throw Error(`\`attributePreviousValue\` is required when calling \`${w}\` with \`attributeCondition: "changed_from_to"\`.`)}function d7(w){vP("create_sequence_goal",w)}function t7(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 s7(w,b,$){let W=P(w,b,"nodeId");if(!k(b.changes)||Object.keys(b.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${w}\`.`);let Q=P(w,b,"expectedUpdatedAt");return{nodeId:W,changes:b.changes,expectedUpdatedAt:Q}}function e7(w){let b=s7("update_sequence_node",w,"the node update");return{...w.confirmLiveChange!==void 0&&{confirmLiveChange:w.confirmLiveChange},nodeUpdates:[b]}}function a7(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(!k(W))throw Error(`\`updates[${Q}]\` must be an object when calling \`update_sequence_nodes\`.`);let G=s7("update_sequence_nodes",W,`updates[${Q}]`),X=String(G.nodeId);if(b.has(X))throw Error(`\`updates[${Q}]\` targets duplicate nodeId '${X}' when calling \`update_sequence_nodes\`.`);return b.add(X),G});return{...w.confirmLiveChange!==void 0&&{confirmLiveChange:w.confirmLiveChange},nodeUpdates:$}}function wz(w){let b=P("edit_sequence_graph",w,"action"),$=P("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=F(w,"nodeId"),G=F(w,"afterNodeId"),X=F(w,"beforeNodeId"),Y=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 J=b==="move_node"||b==="duplicate_node";if(J&&(G?1:0)+(X?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${b} when calling \`edit_sequence_graph\`.`);if(!J&&(G||X))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${b} when calling \`edit_sequence_graph\`.`);if((b==="replace_edges"||b==="delete_node"&&Y!==void 0)&&(!Array.isArray(Y)||Y.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")&&Y!==void 0)throw Error(`\`edges\` is not used with ${b} when calling \`edit_sequence_graph\`.`);let H=Array.isArray(Y)?Y.map((z,D)=>{if(!k(z))throw Error(`\`edges\` item ${D+1} must be an object when calling \`edit_sequence_graph\`.`);let A=P("edit_sequence_graph",z,"sourceNodeId"),L=P("edit_sequence_graph",z,"targetNodeId");if(z.condition!==void 0&&z.condition!==null&&!k(z.condition))throw Error(`\`edges\` item ${D+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:A,targetNodeId:L,...k(z.condition)?{condition:z.condition}:{}}}):void 0;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},graphEdit:{action:b,expectedRevision:$,...Q?{nodeId:Q}:{},...G?{afterNodeId:G}:{},...X?{beforeNodeId:X}:{},...H?{edges:H}:{}}}}function bz(w){let b=F(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 X=P("insert_sequence_step",w,"eventName"),Y=w.timeoutDays,J=Y===void 0?7:Y;if(typeof J!=="number"||!Number.isInteger(J)||J<1||J>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=F(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:F(w,"label")??`Wait for ${X}`,eventName:X,timeoutDays:J,timeoutAction:H}}]},D=F(w,"afterNodeId");if(D)z.afterNodeId=D;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:z}}if(b==="logic_branch"){let X=P("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 Y=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"]),J=["id","label","conditionType","tagName","tagId","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue","targetNodeId","steps"],H=w.allowEmptyPaths===!0,z=w.branches.map((L,K)=>{if(!k(L))throw Error(`\`branches[${K}]\` must be an object when calling \`insert_sequence_step\`.`);let M=P("insert_sequence_step",L,"conditionType");if(!Y.has(M))throw Error(`\`branches[${K}].conditionType\` is not supported when calling \`insert_sequence_step\`.`);let j=`branches[${K}]`;if((M==="has_tag"||M==="does_not_have_tag")&&!F(L,"tagId")&&!F(L,"tagName"))throw Error(`\`${j}\` must provide \`tagId\` or \`tagName\` for ${M} when calling \`insert_sequence_step\`.`);if(M==="in_list"&&!F(L,"listId"))throw Error(`\`${j}.listId\` is required for in_list when calling \`insert_sequence_step\`.`);if(M==="in_segment"&&!F(L,"segmentId"))throw Error(`\`${j}.segmentId\` is required for in_segment when calling \`insert_sequence_step\`.`);if(M==="event_received"&&!F(L,"eventName"))throw Error(`\`${j}.eventName\` is required for event_received when calling \`insert_sequence_step\`.`);if(M.startsWith("field_")&&(!F(L,"fieldName")||!F(L,"fieldValue")))throw Error(`\`${j}\` must provide \`fieldName\` and \`fieldValue\` for ${M} when calling \`insert_sequence_step\`.`);if(L.steps!==void 0&&!Array.isArray(L.steps))throw Error(`\`branches[${K}].steps\` must be an array when calling \`insert_sequence_step\`.`);let V=F(L,"targetNodeId"),C=Array.isArray(L.steps)&&L.steps.length>0;if(!V&&!C&&!H)throw Error(`\`branches[${K}]\` must provide \`targetNodeId\` or non-empty \`steps\` when inserting \`logic_branch\` with \`insert_sequence_step\`.`);return Object.fromEntries(J.flatMap((R)=>L[R]===void 0?[]:[[R,L[R]]]))});if(w.elseSteps!==void 0&&!Array.isArray(w.elseSteps))throw Error("`elseSteps` must be an array when calling `insert_sequence_step`.");let D=F(w,"elseTargetNodeId"),A=Array.isArray(w.elseSteps)&&w.elseSteps.length>0;if(!D&&!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:X,...F(w,"label")?{label:F(w,"label")}:{},branches:z,...Array.isArray(w.elseSteps)?{elseSteps:w.elseSteps}:{},...D?{elseTargetNodeId:D}:{},...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 X;if(b==="delay"){X={type:"delay"};for(let H of["delay","delayMs","waitUntil"])if(w[H]!==void 0)X[H]=w[H];if(X.delay===void 0&&X.delayMs===void 0&&X.waitUntil===void 0)throw Error("Provide `delay`, `delayMs`, or `waitUntil` when inserting a delay step.")}else if(b==="create_discount"){X={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)X[H]=w[H]}else if(b==="update_subscriber"){if(!k(w.config))throw Error("`config` is required when inserting an update_subscriber step.");X={type:"update_subscriber",nodeType:"action_update_attributes",config:w.config}}else if(b==="webhook"){let H=F(w,"method")??"POST";if(H!=="POST"&&H!=="GET")throw Error("`method` must be `POST` or `GET` when inserting a webhook step.");if(w.headers!==void 0&&(!k(w.headers)||Object.values(w.headers).some((z)=>typeof z!=="string")))throw Error("`headers` must be an object with string values when inserting a webhook step.");X={type:"webhook",nodeType:"action_webhook",config:{label:F(w,"label")??"Webhook",url:P("insert_sequence_step",w,"url"),method:H,...w.headers!==void 0?{headers:w.headers}:{}}}}else if(b==="condition"){let H=P("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")&&!F(w,"tagId")&&!F(w,"tagName"))throw Error("Provide `tagId` or `tagName` for this condition step.");if(H==="in_list"&&!F(w,"listId"))throw Error("`listId` is required for an in_list condition.");if(H==="in_segment"&&!F(w,"segmentId"))throw Error("`segmentId` is required for an in_segment condition.");if(H==="event_received"&&!F(w,"eventName"))throw Error("`eventName` is required for an event_received condition.");if(H.startsWith("field_")&&(!F(w,"fieldName")||!F(w,"fieldValue")))throw Error("`fieldName` and `fieldValue` are required for field conditions.");let D={label:F(w,"label")??"Condition",conditionType:H};for(let A of["tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"])if(w[A]!==void 0)D[A]=w[A];X={type:"condition",nodeType:"logic_condition",config:D}}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",D={label:F(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=F(w,"tagId"),L=F(w,"tagName");if(!A&&!L)throw Error("Provide `tagId` or `tagName` when inserting a tag action.");if(A)D.tagId=A;if(L)D.tagName=L}else{D.listId=P("insert_sequence_step",w,"listId");let A=F(w,"listName");if(A)D.listName=A}X={nodeType:z,config:D}}for(let H of["delay","delayMs","waitUntil"])if(b!=="delay"&&w[H]!==void 0)X[H]=w[H];let Y={steps:[X]},J=F(w,"afterNodeId");if(J)Y.afterNodeId=J;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:Y}}let W=b==="sms",Q;if(W){v9("insert_sequence_step","SMS step",w);let X=F(w,"text"),Y=Array.isArray(w.blocks)&&w.blocks.length>0;if(X===void 0&&!Y)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");Q={type:"sms"};for(let J of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(w[J]!==void 0)Q[J]=w[J]}else{vw("insert_sequence_step",w,{requireContent:!0}),p$("insert_sequence_step","email step",w),Q={subject:P("insert_sequence_step",w,"subject")};for(let X of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","isTransactional","ccEmails","bccEmails","attachments"])if(w[X]!==void 0)Q[X]=w[X]}let G={steps:[Q]};if(w.afterNodeId!==void 0)G.afterNodeId=w.afterNodeId;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:G}}function r7(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 $z(w){let b=F(w,"subscriberId"),$=r7(w,"subscriberIds"),W=r7(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 X=F(w,"fieldPath"),Y=F(w,"reason");return{...Q&&{cancelAll:!0},...b!==void 0&&{subscriberId:b},...$.length>0&&{subscriberIds:$},...X!==void 0&&{fieldPath:X},...W.length>0&&{fieldValues:W},...typeof w.dryRun==="boolean"&&{dryRun:w.dryRun},...Y!==void 0&&{reason:Y}}}function Wz(w){vw("create_campaign",w),L1("create_campaign",w);let b=F(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&&F(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function Qz(w){vw("create_template",w),L1("create_template",w);let b=F(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&&F(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function Gz(w){if(F(w,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(w.targetLists!==void 0&&!k(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 o$(w,b,$){let W=new Set(["companyId","landingPageId","name","slug","content"]),Q=Object.keys(b).filter((G)=>!W.has(G));if(Q.length>0)throw Error(`\`${w}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${Q.length===1?"":"s"}: ${Q.map((G)=>`\`${G}\``).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 Xz(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 Yz(w){vw("create_transactional_email",w);let b=F(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&&F(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var D0={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},_P={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 url plus optional method and headers; logic_delay uses delayDays/delayHours/delayMinutes. Fields that do not apply to the node type are dropped.",properties:{...D0.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 URL called when a subscriber reaches this step."},method:{type:"string",enum:["POST","GET"],description:"action_webhook: HTTP method. Defaults to POST."},headers:{type:"object",description:"action_webhook: optional string-valued request headers. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},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},Ab={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."}},Lb={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:_P,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:X0,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:J0,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:Y0,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."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",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},_9={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:Lb}},required:["conditionType"],additionalProperties:!1};function Jz(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.")}function k9(w){return w.trim().toLowerCase().replace(/\s+/g,"-")}function kP(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());return b.set("page",String(w.page)),b.set("limit",String(w.pageSize)),b}async function zz(w,b){let $=typeof w.limit==="number"&&Number.isFinite(w.limit)?Math.max(1,Math.trunc(w.limit)):void 0,W=Math.min(100,Math.max(1,$??100)),Q=[],G=1,X=0,Y=0,J=0;while(!0){let z=kP({query:w.query,tags:w.tags,list:w.list,listId:w.listId,listName:w.listName,segmentId:w.segmentId,status:w.status,page:G,pageSize:W}),D=await U("GET",`/api/v1/subscribers?${z.toString()}`,void 0,b);X=D.pagination?.total??D.subscribers.length,Y=D.pagination?.totalPages??1,J+=1,Q.push(...D.subscribers??[]);let A=$!==void 0&&Q.length>=$,L=D.pagination?G>=D.pagination.totalPages:(D.subscribers??[]).length<W;if(A||L)break;G+=1}let H=$!==void 0?Q.slice(0,$):Q;return{success:!0,subscribers:H,pagination:{page:1,limit:W,total:X,totalPages:Y,fetchedPages:J},returned:H.length,truncated:$!==void 0&&X>0&&H.length<X}}function xP(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 dw(w,b){let $=xP(b);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${w}\`.`);return $}function d$(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 x9(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 Fb(w,b,$){return U("GET",d$(w,$),void 0,b)}function p(w,b,$,W){let Q=F(b,$);if(Q===void 0)return;if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${w}\`.`);return Q}function Bb(w,b,$,W){let Q=P(w,b,$);if(!W.includes(Q))throw Error(`\`${$}\` must be one of ${W.join(", ")} when calling \`${w}\`.`);return Q}function qw(w,b,$,W,Q){let G=b[$];if(G===void 0)return;if(typeof G!=="number"||!Number.isInteger(G)||G<W||G>Q)throw Error(`\`${$}\` must be an integer between ${W} and ${Q} when calling \`${w}\`.`);return G}function yP(w,b){let $=[],W=p(w,b,"eventType",Db);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,G)=>{if(typeof Q!=="string")throw Error(`\`eventTypes\` item ${G+1} must be a string when calling \`${w}\`.`);let X=Q.trim();if(!Db.includes(X))throw Error(`\`eventTypes\` item ${G+1} must be one of ${Db.join(", ")} when calling \`${w}\`.`);$.push(X)})}return[...new Set($)]}function y9(w,b){let $=new URLSearchParams,W=yP(w,b);if(W.length>0)$.set("eventTypes",W.join(","));let Q=p(w,b,"period",["1h","24h","7d","30d","90d"]);if(Q)$.set("period",Q);let G=F(b,"start");if(G)$.set("start",G);let X=F(b,"end");if(X)$.set("end",X);let Y=qw(w,b,"page",1,1e6);if(Y!==void 0)$.set("page",String(Y));let J=qw(w,b,"limit",1,500);if(J!==void 0)$.set("limit",String(J));if(b.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function h9(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"||!z0.includes(W))throw Error(`\`events\` item ${Q+1} must be one of ${z0.join(", ")} when calling \`${w}\`.`);return W});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${w}\`.`);return $}function u9(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 G=W.trim();if(G.length>0)$.push(G)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${w}\`.`);if($.length>V9)throw Error(`\`emails\` must include no more than ${V9} email addresses when calling \`${w}\`. Split larger batches into multiple calls.`);return $}function Hz(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 G=[];if(Q.forEach((X,Y)=>{if(typeof X!=="string")throw Error(`\`${$}\` item ${Y+1} must be a string when calling \`${w}\`.`);let J=X.trim();if(J.length>0)G.push(J)}),G.length===0)throw Error(`\`${$}\` must include at least one ${W} when calling \`${w}\`.`);return G}function Dz(w){let $=Hz("enroll_subscribers_in_sequence",w,"emails","email address"),W=Hz("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>j9)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${j9} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let G=F(w,"targetNodeId");return{...$!==void 0&&{emails:$},...W!==void 0&&{subscriberIds:W},...G!==void 0&&{targetNodeId:G}}}import{readFileSync as hP,statSync as uP}from"node:fs";import{basename as fP}from"node:path";var cP={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 mP(w){let b=w.split(".").pop()?.toLowerCase()??"";return cP[b]??null}var gP=104857600;async function Uz(w,b){if(!Kb())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 $=mP(w);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=uP(w).size;if(W>gP)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let Q=hP(w),G=await U("POST","/api/v1/products/delivery/upload-url",{filename:fP(w),contentType:$,fileSizeBytes:W},b),X=await fetch(G.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:Q});if(!X.ok)throw Error(`File upload failed (${X.status})`);return{url:G.publicUrl,fileName:G.fileName,fileSizeBytes:W,mimeType:$}}async function t$(w){let b=F(w,"companyId");if(b)return b;let $=B1();if($)return $;try{return(await U("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function r$(w,b){let $=await t$(b);if(!$)throw Error(`A company is required when calling \`${w}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function A0(w,b){if(!k(w)||!b)return w;return{...w,url:b}}function Az(w,b){if(!k(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(!k(W))return W;let Q=F(W,"id");if(!Q)return W;let G=D1({companyId:b,...$==="campaign"&&{campaignId:Q},...$==="landingPage"&&{landingPageId:Q},...$==="sequence"&&{sequenceId:Q},...$==="template"&&{emailId:Q},...$==="transactional"&&{transactionalId:Q},...$==="emailSend"&&{emailSendId:Q}});if($==="campaign")return Az(W,G.urls);let X=$==="sequence"?G.urls.sequence:$==="landingPage"?G.urls.landingPage:$==="template"?G.urls.email:$==="transactional"?G.urls.transactionalEmail:G.urls.emailSend;return A0(W,X)})}function lP(w){if(!Array.isArray(w))return w;return w.map((b)=>{if(!k(b))return b;let $=F(b,"id");if(!$)return b;let W=D1({companyId:$});return{...b,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var f9=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 Lz(w,b,$){if(!k($)||!f9.has(w))return $;let W=k($.company)?$.company:void 0,G=F($,"selectedCompanyId")??F($,"currentCompanyId")??F($,"companyId")??(W?F(W,"id"):void 0)??(W?F(W,"companyId"):void 0)??await t$(b);if(!G)return $;let X=k($.campaign)?$.campaign:void 0,Y=k($.sequence)?$.sequence:void 0,J=k($.landingPage)?$.landingPage:void 0,H=k($.template)?$.template:void 0,z=k($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,D={companyId:G,campaignId:F(b,"campaignId")??F($,"campaignId")??(X?F(X,"id"):void 0),landingPageId:F(b,"landingPageId")??F($,"landingPageId")??(J?F(J,"id"):void 0),sequenceId:F(b,"sequenceId")??F($,"sequenceId")??(Y?F(Y,"id"):void 0),emailId:F($,"templateId")??(H?F(H,"id"):void 0)??(z?F(z,"emailId"):void 0)??F(b,"templateId"),transactionalId:F(b,"transactionalId")??(z?F(z,"id"):void 0)??F(b,"idOrSlug"),emailSendId:F(b,"emailSendId")??F($,"emailSendId")??(k($.emailSend)?F($.emailSend,"id"):void 0),status:F(b,"status")},A=D1(D),L=W?D1({companyId:G}):void 0;return{...$,...Array.isArray($.companies)&&{companies:lP($.companies)},...Array.isArray($.campaigns)&&{campaigns:U0($.campaigns,G,"campaign")},...Array.isArray($.landingPages)&&{landingPages:U0($.landingPages,G,"landingPage")},...Array.isArray($.sequences)&&{sequences:U0($.sequences,G,"sequence")},...Array.isArray($.templates)&&{templates:U0($.templates,G,"template")},...Array.isArray($.transactional)&&{transactional:U0($.transactional,G,"transactional")},...Array.isArray($.emailSends)&&{emailSends:U0($.emailSends,G,"emailSend")},...W&&L!==void 0&&{company:{...W,url:L.urls.dashboard,settingsUrl:L.urls.settings}},...X&&A.urls.campaign!==void 0&&{campaign:Az(X,A.urls)},...Y&&A.urls.sequence!==void 0&&{sequence:A0(Y,A.urls.sequence)},...J&&A.urls.landingPage!==void 0&&{landingPage:A0(J,A.urls.landingPage)},...H&&A.urls.email!==void 0&&{template:A0(H,A.urls.email)},...z&&A.urls.transactionalEmail!==void 0&&{transactional:A0(z,A.urls.transactionalEmail)},...k($.emailSend)&&A.urls.emailSend!==void 0&&{emailSend:A0($.emailSend,A.urls.emailSend)},appUrls:A.urls}}import{readFileSync as iP,statSync as nP}from"node:fs";import{basename as pP,extname as Bz}from"node:path";var m9=5242880,oP=Math.ceil(m9/3)*4,dP=Math.ceil(oP*1.05)+256,Kz={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},tP=new Set(Object.values(Kz));function c9(w){return w?.split(";")[0]?.trim().toLowerCase()||void 0}function rP(w){return Kz[Bz(w).toLowerCase()]}function sP(w){let b=Bz(w);return(b?w.slice(0,-b.length):w).replace(/[-_]+/g," ").trim()||"Image"}function eP(w){if(w.length>dP)throw Error("Image assets must be 5MB or smaller.")}function aP(w){let b=0,$=0;for(let Q=0;Q<w.length;Q+=1){let G=w.charCodeAt(Q);if(G===9||G===10||G===11||G===12||G===13||G===32)continue;b+=1,$=G===61?$+1:0}if(Math.floor(b*3/4)-Math.min($,2)>m9)throw Error("Image assets must be 5MB or smaller.")}function wZ(w){eP(w);let b=w.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(b),W=$?.[2]??b;aP(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:c9($[1])}:{}}}function Fz(w){if(w<=0)throw Error("The image file is empty.");if(w>m9)throw Error("Image assets must be 5MB or smaller.")}function bZ(w){let b=rP(w.filename)??c9(w.explicitContentType)??c9(w.dataUrlContentType);if(!b||!tP.has(b))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return b}function $Z(w){let b,$,W;if(w.filePath!==void 0){if(!Kb())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 G=nP(w.filePath).size;Fz(G),b=iP(w.filePath),$=w.filename??pP(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 G=wZ(w.imageBase64);b=G.bytes,W=G.dataUrlContentType,$=w.filename,Fz(b.byteLength)}let Q=bZ({filename:$,explicitContentType:w.contentType,dataUrlContentType:W});return{bytes:b,filename:$,contentType:Q,altText:w.altText??sP($)}}async function Oz(w){let b=$Z(w),$=b.bytes.byteLength,W=await U("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 U("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 WZ={type:"boolean",description:"Whether the Sequenzy operation succeeded."},QZ={type:"string",description:"Human-readable status, confirmation, or next-step message."},GZ={type:"string",description:"Additional context about the result."};function v(w){return{type:"object",description:w,additionalProperties:!0}}function l9(w){return{type:"array",description:w,items:v("One item in the returned collection.")}}function Z(w){return{type:"string",description:w}}function Mz(w){return{type:["object","null"],description:w,additionalProperties:!0}}function g9(w){return{type:["string","null"],description:w}}function c(w){return{type:"number",description:w}}function Gw(w){return{type:"boolean",description:w}}function q(w){return v(`The ${w} record returned by Sequenzy.`)}function y(w){return l9(`List of ${w} records returned by Sequenzy.`)}var s$="`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`.",Pz="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.",c1=v(`The sequence record returned by Sequenzy. ${Pz}`),XZ=l9(`List of sequence records returned by Sequenzy. ${Pz}`),e$={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:Gw("Whether new subscribers can enter the sequence right now."),processesExistingEnrollments:Gw("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.")},qz={...c1,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.")}},YZ={appUrls:v("Dashboard URLs for relevant Sequenzy resources."),url:Z("Primary dashboard URL for this result."),settingsUrl:Z("Company settings URL when available.")},JZ={success:WZ,message:QZ,note:GZ,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:v("One returned item.")},value:v("Fallback object wrapper used only when a tool returns a non-object value.")},HZ={get_account:{account:q("account"),companies:y("company"),apiKeyPermissions:v("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:v("All generated URLs keyed by resource type.")},create_company:{company:q("company"),autoSelected:Gw("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:q("company")},get_company:{company:q("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:v("One sync rule.")},isDefault:Gw("Whether the company uses the inherited SaaS/ecommerce platform preset.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:v("One sync rule.")},isDefault:Gw("Whether the company now uses the inherited SaaS/ecommerce platform preset.")},get_shopify_automation_settings:{browseAbandonment:v("Effective browse-abandonment settings (defaults applied)."),cartAbandonment:v("Effective cart-abandonment settings (defaults applied)."),priceDrop:v("Effective price-drop settings (defaults applied)."),shopDomain:Z("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:v("Effective browse-abandonment settings after the update."),cartAbandonment:v("Effective cart-abandonment settings after the update."),priceDrop:v("Effective price-drop settings after the update."),shopDomain:Z("Connected Shopify store domain.")},create_api_key:{apiKey:v("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:y("non-secret API key metadata, including ID, name, prefix, permissions, timestamps, and active-credential status")},revoke_api_key:{apiKey:q("revoked non-secret API key metadata")},delete_api_key:{apiKey:q("deleted non-secret API key metadata")},list_websites:{websites:y("sender website")},list_integrations:{integrations:y("connected integration, including provider, provider account ID, active and sync status, last sync time, last sync error, and allowlisted non-secret details. Credentials are never included")},list_sender_profiles:{senderProfiles:y("sender (From) profile, including the sending domain behind it, its verification status, and whether the address can currently send"),replyProfiles:y("reply-to profile"),defaultSenderProfileId:g9("Company default sender profile ID. Null when no default is set."),defaultReplyProfileId:g9("Company default reply-to profile ID. Null when no default is set.")},get_tracking_settings:{tracking:v("Open, click, and unsubscribe tracking flags plus the default attribution window in hours."),autoUtm:v("Automatic UTM tagging state and its configured parameters."),trackingDomain:Mz("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:v("Inbound reply tracking configuration.")},add_website:{website:q("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:q("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:q("sender website"),ready:Gw("Whether the sender website is ready."),status:Z("Current processing or verification status.")},verify_sending_domain:{website:q("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:Gw("Whether the sending domain passed the fresh verification check."),message:Z("Verification result summary.")},get_integration_guide:{guide:q("integration guide"),code:Z("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:v("One setup step.")}},add_subscriber:{subscriber:q("subscriber")},create_subscriber_import:{import:q("subscriber import")},get_subscriber_import:{import:q("subscriber import")},update_subscriber:{subscriber:q("subscriber")},remove_subscriber:{subscriber:q("subscriber"),hardDeleted:Gw("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:q("subscriber")},list_subscriber_notes:{notes:y("subscriber note")},add_subscriber_note:{note:q("subscriber note")},delete_subscriber_note:{id:Z("Deleted subscriber note ID."),deleted:Gw("Whether the subscriber note was deleted.")},trigger_subscriber_event:{subscriber:q("subscriber"),event:q("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:q("subscriber"),events:y("recorded event")},bulk_add_subscriber_tags:{tags:{type:"array",description:"Normalized tag names applied to every matched subscriber.",items:Z("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:v("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds. These subscribers were NOT created."),failures:y("per-subscriber failure (up to 50)"),triggeredAutomations:Gw("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: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:v("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds."),failures:y("per-subscriber failure (up to 50)")},search_subscribers:{subscribers:y("subscriber"),pagination:v("Pagination metadata."),returned:c("Number of subscribers returned."),truncated:Gw("Whether the result was truncated by the requested limit.")},list_products:{products:y("product")},upsert_products:{products:y("product"),created:c("Number of products created."),updated:c("Number of products updated.")},delete_product:{productId:Z("Deleted product ID.")},attach_product_file:{product:q("product"),delivery:q("digital delivery file")},remove_product_file:{product:q("product")},upload_image_asset:{asset:q("hosted image asset"),imageBlock:v("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:q("product sync job"),jobId:Z("Queued product sync job ID.")},list_tags:{tags:y("tag")},create_tag:{tag:q("tag")},update_tag:{tag:q("tag")},delete_tag:{tagId:Z("Deleted tag ID.")},list_lists:{lists:y("list")},create_list:{list:q("list")},update_list:{list:q("list")},delete_list:{listId:Z("Deleted list ID.")},add_subscribers_to_list:{list:q("list"),added:c("Number of subscribers added to the list."),skipped:c("Number of subscribers skipped.")},remove_subscribers_from_list:{list:q("list"),removed:c("Number of subscribers removed from the list."),skipped:c("Number of subscribers skipped.")},list_segments:{segments:y("segment")},create_segment:{segment:q("segment")},update_segment:{segment:q("segment")},delete_segment:{segmentId:Z("Deleted segment ID.")},get_segment_count:{count:c("Number of subscribers matching the segment."),segmentId:Z("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:y("audience sync")},list_ad_accounts:{adAccounts:y("ad account")},create_audience_sync:{audienceSync:q("audience sync")},update_audience_sync:{audienceSync:q("audience sync")},delete_audience_sync:{audienceSyncId:Z("Deleted audience sync ID.")},sync_audience_now:{audienceSync:q("audience sync"),job:q("audience sync job"),jobId:Z("Queued audience sync job ID.")},list_templates:{templates:y("email template")},get_template:{template:q("email template")},create_template:{template:q("email template")},update_template:{template:q("email template")},set_template_localization:{templateId:Z("Localized template ID."),localization:q("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:c("Number of localized variants queued for translation.")},delete_template:{templateId:Z("Deleted template ID.")},list_ab_tests:{abTests:y("A/B test")},get_ab_test:{abTest:q("A/B test")},get_ab_test_stats:{abTest:q("A/B test"),stats:q("A/B test statistics")},restart_ab_test:{abTest:q("A/B test")},update_ab_test_variant:{abTest:q("A/B test"),variant:q("A/B test variant")},update_ab_test:{abTest:q("A/B test")},create_ab_test:{abTest:q("A/B test")},add_ab_test_variant:{abTest:q("A/B test"),variant:q("A/B test variant")},delete_ab_test_variant:{abTest:q("A/B test"),variantId:Z("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:Z("Deleted A/B test ID.")},list_campaigns:{campaigns:y("campaign"),pagination:v("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:q("campaign")},get_campaign_audience:{campaignId:Z("Campaign the audience was resolved for."),campaignName:Z("Campaign name."),status:Z("Campaign status."),audience:v("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:Mz("Raw stored targeting exactly as persisted on the campaign. Null when targeting has never been set.")},get_email_send:{emailSend:q("email send, including copied-recipient identity and primary email send ID when applicable"),events:y("email delivery event")},list_email_sends:{emailSends:y("email send"),pagination:q("email send pagination"),retentionDays:c("Number of days sent-email rows remain queryable in this collection.")},get_recipient_suppression:{suppression:q("recipient suppression status")},remove_recipient_suppression:{removed:Gw("Whether stale bounce suppression was removed."),removedLocalBounce:Gw("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:q("recipient suppression status after cleanup")},create_campaign:{campaign:q("campaign")},update_campaign:{campaign:q("campaign")},schedule_campaign:{campaign:q("campaign"),scheduledAt:Z("Scheduled send timestamp.")},unschedule_campaign:{campaign:q("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:q("campaign")},pause_campaign:{campaign:q("campaign")},resume_campaign:{campaign:q("campaign")},delete_campaign:{campaignId:Z("Deleted campaign ID.")},duplicate_campaign:{campaign:q("duplicated campaign")},resend_campaign_to_non_openers:{campaign:q("non-opener resend draft campaign"),estimatedNonOpenerCount:c("Estimated number of subscribers who haven't opened the original campaign.")},list_forms:{forms:y("saved form")},create_form:{form:q("saved form"),embed:v("Public action URL plus JavaScript, native form, and fetch snippets.")},get_form_embed:{form:q("saved form"),embed:v("Public action URL plus JavaScript, native form, and fetch snippets.")},list_landing_pages:{landingPages:y("landing page")},get_landing_page:{landingPage:q("landing page")},create_landing_page:{landingPage:q("landing page")},update_landing_page:{landingPage:q("landing page")},duplicate_landing_page:{landingPage:q("landing page")},delete_landing_page:{landingPageId:Z("Deleted landing page ID.")},publish_landing_page:{landingPage:q("landing page")},unpublish_landing_page:{landingPage:q("landing page")},connect_landing_page_domain:{landingPage:q("landing page"),domain:Z("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:q("landing page"),domain:Z("Landing page domain.")},list_sequences:{sequences:XZ,pagination:v("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:c1},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:Z("Subscriber email address. Falls back to the address captured at enrollment when the subscriber record no longer exists."),firstName:Z("Subscriber first name, or null when unset."),lastName:Z("Subscriber last name, or null when unset."),subscriberStatus:Z("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:Gw("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:Z("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.")},required:["enrollmentId","sequenceId","subscriberId","status","currentNodeId","currentNodeMissing","enrollmentStartedAt"]}},pagination:v("Pagination metadata.")},send_sequence_test_email:{sequenceId:Z("Sequence ID."),nodeId:Z("Tested sequence email-step node ID."),results:l9("Per-recipient test-send results containing recipientEmail, durable emailSendId, and legacy jobId.")},create_sequence:{sequence:c1,eventTrackingCode:Z("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:v("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:qz},update_sequence_node:{sequence:q("sequence")},update_sequence_nodes:{sequence:q("sequence")},edit_sequence_graph:{sequence:qz},insert_sequence_step:{sequence:q("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:c("Number of email steps inserted."),addedBranchNodeId:Z("New logic_branch node ID when the inserted step is a branch."),addedBranchPathNodeIds:v("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:Gw("Whether new sequence enrollments are paused."),...e$},disable_sequence:{sequenceId:Z("Sequence ID."),status:Z("Stored lifecycle status after the change."),enrollmentPaused:Gw("Whether new sequence enrollments are paused."),...e$},duplicate_sequence:{sequence:c1,nodes:y("sequence node"),edges:y("sequence edge")},archive_sequence:{sequence:c1},unarchive_sequence:{sequence:c1},list_sequence_goals:{goals:y("sequence goal")},create_sequence_goal:{goal:q("sequence goal")},update_sequence_goal:{goal:q("sequence goal")},delete_sequence_goal:{goalId:Z("Deleted sequence goal ID.")},get_sequence_inbound_webhook:{webhook:q("sequence inbound webhook")},configure_sequence_inbound_webhook:{webhook:q("sequence inbound webhook")},rotate_sequence_inbound_webhook_secret:{webhook:q("sequence inbound webhook")},pause_sequence_enrollments:{sequenceId:Z("Sequence ID."),enrollmentPaused:Gw("Whether new sequence enrollments are paused."),...e$},resume_sequence_enrollments:{sequenceId:Z("Sequence ID."),enrollmentPaused:Gw("Whether new sequence enrollments are paused."),...e$},enroll_subscribers_in_sequence:{sequence:q("sequence"),enrollments:y("sequence enrollment"),enrolled:c("Number of subscribers enrolled."),skipped:c("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequenceId:Z("Sequence ID."),dryRun:Gw("Whether this call only reported matches instead of cancelling them."),target:v("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:y("sequence enrollment sample (up to 50)"),hasMore:Gw("Whether more enrollments matched than the returned sample.")},delete_sequence:{sequenceId:Z("Deleted sequence ID.")},list_transactional_emails:{transactional:y("transactional email with subject, all-time delivery metrics, and dashboard URL")},get_transactional_email:{transactional:q("transactional email")},create_transactional_email:{transactional:q("transactional email")},update_transactional_email:{transactional:q("transactional email")},send_email:{emailSendId:Z("Durable email delivery ID."),emailType:{type:"string",enum:["marketing","transactional"],description:"Delivery policy accepted for the queued email."},transactional:q("transactional email")},get_stats:{stats:v(`Account-wide delivery funnel for the requested window. ${s$}`),emailType:Z("Applied structural email type filter when one was requested."),commerceForecast:q("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:q("campaign"),stats:v(`Delivery funnel for this campaign. ${s$}`),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:v("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:v("One poll or NPS results summary.")},recommendations:v("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:q("transactional email"),stats:v(`Delivery funnel for this transactional email. ${s$}`),complaints:q("complaint count and rate for the selected transactional email"),clickedLinks:y("clicked link with click count and percentage share"),bounceBreakdown:q("permanent, transient, and undetermined bounce counts plus subtype details"),engagementBreakdown:q("human and machine open and click counts")},get_sequence_stats:{sequence:c1,stats:v(`Delivery funnel across every email step in this sequence. ${s$}`),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: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:Gw("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:v("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:y("campaign email event"),pagination:v("Pagination metadata.")},list_sequence_events:{events:y("sequence email event"),pagination:v("Pagination metadata.")},get_subscriber_activity:{activity:y("subscriber activity event"),subscribers:y("subscriber"),pagination:v("Pagination metadata.")},list_team_members:{members:y("team member"),invitations:y("team invitation")},invite_team_member:{invitation:q("team invitation")},cancel_team_invitation:{invitationId:Z("Cancelled invitation ID.")},list_conversations:{conversations:y("inbox conversation"),pagination:v("Pagination metadata.")},get_conversation:{conversation:q("inbox conversation"),messages:y("conversation message")},reply_to_conversation:{conversation:q("inbox conversation"),message:q("conversation message")},update_conversation_status:{conversation:q("inbox conversation")},mark_conversation_read:{conversation:q("inbox conversation")},list_webhooks:{webhooks:y("outbound webhook")},create_webhook:{webhook:q("outbound webhook")},update_webhook:{webhook:q("outbound webhook")},delete_webhook:{webhookId:Z("Deleted outbound webhook ID.")},test_webhook:{webhook:q("outbound webhook"),delivery:q("test webhook delivery")},list_webhook_deliveries:{deliveries:y("webhook delivery")},replay_webhook_delivery:{delivery:q("webhook delivery"),job:q("webhook replay job")},generate_email:{email:q("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:v("One generated email block.")},subject:Z("Generated subject line."),previewText:Z("Generated inbox preview text.")},generate_sequence:{sequence:q("persisted AI-generated sequence draft"),deprecated:Gw("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:y("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:v("One generated SMS message.")}},get_sms_settings:{sms:v("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:g9("Inbox preview text with merge tags resolved, or null when unset."),locale:Z("Localization locale the render resolved to."),personalized:Gw("Whether a real contact was supplied. False means a sample contact was used and merge tags resolved to empty values."),trackingApplied:Gw("Whether auto-UTM link decoration was applied."),entity:v("Which entity was rendered: type, id, and variantId.")}};function zZ(w){let b=HZ[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:{...JZ,...b,...f9.has(w)?YZ:{}},additionalProperties:!0}}function Zz(w){return{...w,outputSchema:zZ(w.name)}}function Vz(w){if(k(w))return w;if(Array.isArray(w))return{items:w};return{value:w}}var jz=[{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. ${Jw}`},blocks:{type:"array",description:`${A1} 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:A1,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:A1,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 Iz=[{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
|
+
`)}L.write("payload.value = newResult;"),L.write("return payload;");let _=L.compile();return(R,m)=>_(A,R,m)},X,Y=v1,G=!Zb.jitless,H=G&&L4.value,z=b.catchall,D;w._zod.parse=(A,L)=>{D??(D=Q.value);let O=A.value;if(!Y(O))return A.issues.push({expected:"object",code:"invalid_type",input:O,inst:w}),A;if(G&&H&&L?.async===!1&&L.jitless!==!0){if(!X)X=W(b.shape);if(A=X(A,L),!z)return A;return A8([],O,A,L,D,w)}return $(A,L)}});function RW(w,b,$,Q){for(let X of w)if(X.issues.length===0)return b.value=X.value,b;let W=w.filter((X)=>!q1(X));if(W.length===1)return b.value=W[0].value,W[0];return b.issues.push({code:"invalid_union",input:b.value,inst:$,errors:w.map((X)=>X.issues.map((Y)=>cw(Y,Q,_w())))}),b}var N4=M("$ZodUnion",(w,b)=>{a.init(w,b),r(w._zod,"optin",()=>b.options.some((W)=>W._zod.optin==="optional")?"optional":void 0),r(w._zod,"optout",()=>b.options.some((W)=>W._zod.optout==="optional")?"optional":void 0),r(w._zod,"values",()=>{if(b.options.every((W)=>W._zod.values))return new Set(b.options.flatMap((W)=>Array.from(W._zod.values)));return}),r(w._zod,"pattern",()=>{if(b.options.every((W)=>W._zod.pattern)){let W=b.options.map((X)=>X._zod.pattern);return new RegExp(`^(${W.map((X)=>Z0(X.source)).join("|")})$`)}return});let $=b.options.length===1,Q=b.options[0]._zod.run;w._zod.parse=(W,X)=>{if($)return Q(W,X);let Y=!1,G=[];for(let J of b.options){let H=J._zod.run({value:W.value,issues:[]},X);if(H instanceof Promise)G.push(H),Y=!0;else{if(H.issues.length===0)return H;G.push(H)}}if(!Y)return RW(G,W,w,X);return Promise.all(G).then((J)=>{return RW(J,W,w,X)})}}),F8=M("$ZodDiscriminatedUnion",(w,b)=>{N4.init(w,b);let $=w._zod.parse;r(w._zod,"propValues",()=>{let W={};for(let X of b.options){let Y=X._zod.propValues;if(!Y||Object.keys(Y).length===0)throw Error(`Invalid discriminated union option at index "${b.options.indexOf(X)}"`);for(let[G,J]of Object.entries(Y)){if(!W[G])W[G]=new Set;for(let H of J)W[G].add(H)}}return W});let Q=l1(()=>{let W=b.options,X=new Map;for(let Y of W){let G=Y._zod.propValues?.[b.discriminator];if(!G||G.size===0)throw Error(`Invalid discriminated union option at index "${b.options.indexOf(Y)}"`);for(let J of G){if(X.has(J))throw Error(`Duplicate discriminator value "${String(J)}"`);X.set(J,Y)}}return X});w._zod.parse=(W,X)=>{let Y=W.value;if(!v1(Y))return W.issues.push({code:"invalid_type",expected:"object",input:Y,inst:w}),W;let G=Q.value.get(Y?.[b.discriminator]);if(G)return G._zod.run(W,X);if(b.unionFallback)return $(W,X);return W.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:b.discriminator,input:Y,path:[b.discriminator],inst:w}),W}}),B8=M("$ZodIntersection",(w,b)=>{a.init(w,b),w._zod.parse=($,Q)=>{let W=$.value,X=b.left._zod.run({value:W,issues:[]},Q),Y=b.right._zod.run({value:W,issues:[]},Q);if(X instanceof Promise||Y instanceof Promise)return Promise.all([X,Y]).then(([J,H])=>{return SW($,J,H)});return SW($,X,Y)}});function j4(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(K1(w)&&K1(b)){let $=Object.keys(b),Q=Object.keys(w).filter((X)=>$.indexOf(X)!==-1),W={...w,...b};for(let X of Q){let Y=j4(w[X],b[X]);if(!Y.valid)return{valid:!1,mergeErrorPath:[X,...Y.mergeErrorPath]};W[X]=Y.data}return{valid:!0,data:W}}if(Array.isArray(w)&&Array.isArray(b)){if(w.length!==b.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let Q=0;Q<w.length;Q++){let W=w[Q],X=b[Q],Y=j4(W,X);if(!Y.valid)return{valid:!1,mergeErrorPath:[Q,...Y.mergeErrorPath]};$.push(Y.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function SW(w,b,$){if(b.issues.length)w.issues.push(...b.issues);if($.issues.length)w.issues.push(...$.issues);if(q1(w))return w;let Q=j4(b.value,$.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return w.value=Q.data,w}var O8=M("$ZodRecord",(w,b)=>{a.init(w,b),w._zod.parse=($,Q)=>{let W=$.value;if(!K1(W))return $.issues.push({expected:"record",code:"invalid_type",input:W,inst:w}),$;let X=[];if(b.keyType._zod.values){let Y=b.keyType._zod.values;$.value={};for(let J of Y)if(typeof J==="string"||typeof J==="number"||typeof J==="symbol"){let H=b.valueType._zod.run({value:W[J],issues:[]},Q);if(H instanceof Promise)X.push(H.then((z)=>{if(z.issues.length)$.issues.push(...W1(J,z.issues));$.value[J]=z.value}));else{if(H.issues.length)$.issues.push(...W1(J,H.issues));$.value[J]=H.value}}let G;for(let J in W)if(!Y.has(J))G=G??[],G.push(J);if(G&&G.length>0)$.issues.push({code:"unrecognized_keys",input:W,inst:w,keys:G})}else{$.value={};for(let Y of Reflect.ownKeys(W)){if(Y==="__proto__")continue;let G=b.keyType._zod.run({value:Y,issues:[]},Q);if(G instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(G.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:G.issues.map((H)=>cw(H,Q,_w())),input:Y,path:[Y],inst:w}),$.value[G.value]=G.value;continue}let J=b.valueType._zod.run({value:W[Y],issues:[]},Q);if(J instanceof Promise)X.push(J.then((H)=>{if(H.issues.length)$.issues.push(...W1(Y,H.issues));$.value[G.value]=H.value}));else{if(J.issues.length)$.issues.push(...W1(Y,J.issues));$.value[G.value]=J.value}}}if(X.length)return Promise.all(X).then(()=>$);return $}});var M8=M("$ZodEnum",(w,b)=>{a.init(w,b);let $=U4(b.entries),Q=new Set($);w._zod.values=Q,w._zod.pattern=new RegExp(`^(${$.filter((W)=>F4.has(typeof W)).map((W)=>typeof W==="string"?Q1(W):W.toString()).join("|")})$`),w._zod.parse=(W,X)=>{let Y=W.value;if(Q.has(Y))return W;return W.issues.push({code:"invalid_value",values:$,input:Y,inst:w}),W}}),K8=M("$ZodLiteral",(w,b)=>{if(a.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=($,Q)=>{let W=$.value;if(w._zod.values.has(W))return $;return $.issues.push({code:"invalid_value",values:b.values,input:W,inst:w}),$}});var q8=M("$ZodTransform",(w,b)=>{a.init(w,b),w._zod.parse=($,Q)=>{if(Q.direction==="backward")throw new M0(w.constructor.name);let W=b.transform($.value,$);if(Q.async)return(W instanceof Promise?W:Promise.resolve(W)).then((Y)=>{return $.value=Y,$});if(W instanceof Promise)throw new $1;return $.value=W,$}});function CW(w,b){if(w.issues.length&&b===void 0)return{issues:[],value:void 0};return w}var Z8=M("$ZodOptional",(w,b)=>{a.init(w,b),w._zod.optin="optional",w._zod.optout="optional",r(w._zod,"values",()=>{return b.innerType._zod.values?new Set([...b.innerType._zod.values,void 0]):void 0}),r(w._zod,"pattern",()=>{let $=b.innerType._zod.pattern;return $?new RegExp(`^(${Z0($.source)})?$`):void 0}),w._zod.parse=($,Q)=>{if(b.innerType._zod.optin==="optional"){let W=b.innerType._zod.run($,Q);if(W instanceof Promise)return W.then((X)=>CW(X,$.value));return CW(W,$.value)}if($.value===void 0)return $;return b.innerType._zod.run($,Q)}}),P8=M("$ZodNullable",(w,b)=>{a.init(w,b),r(w._zod,"optin",()=>b.innerType._zod.optin),r(w._zod,"optout",()=>b.innerType._zod.optout),r(w._zod,"pattern",()=>{let $=b.innerType._zod.pattern;return $?new RegExp(`^(${Z0($.source)}|null)$`):void 0}),r(w._zod,"values",()=>{return b.innerType._zod.values?new Set([...b.innerType._zod.values,null]):void 0}),w._zod.parse=($,Q)=>{if($.value===null)return $;return b.innerType._zod.run($,Q)}}),V8=M("$ZodDefault",(w,b)=>{a.init(w,b),w._zod.optin="optional",r(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,Q)=>{if(Q.direction==="backward")return b.innerType._zod.run($,Q);if($.value===void 0)return $.value=b.defaultValue,$;let W=b.innerType._zod.run($,Q);if(W instanceof Promise)return W.then((X)=>vW(X,b));return vW(W,b)}});function vW(w,b){if(w.value===void 0)w.value=b.defaultValue;return w}var j8=M("$ZodPrefault",(w,b)=>{a.init(w,b),w._zod.optin="optional",r(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,Q)=>{if(Q.direction==="backward")return b.innerType._zod.run($,Q);if($.value===void 0)$.value=b.defaultValue;return b.innerType._zod.run($,Q)}}),I8=M("$ZodNonOptional",(w,b)=>{a.init(w,b),r(w._zod,"values",()=>{let $=b.innerType._zod.values;return $?new Set([...$].filter((Q)=>Q!==void 0)):void 0}),w._zod.parse=($,Q)=>{let W=b.innerType._zod.run($,Q);if(W instanceof Promise)return W.then((X)=>_W(X,w));return _W(W,w)}});function _W(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 N8=M("$ZodCatch",(w,b)=>{a.init(w,b),r(w._zod,"optin",()=>b.innerType._zod.optin),r(w._zod,"optout",()=>b.innerType._zod.optout),r(w._zod,"values",()=>b.innerType._zod.values),w._zod.parse=($,Q)=>{if(Q.direction==="backward")return b.innerType._zod.run($,Q);let W=b.innerType._zod.run($,Q);if(W instanceof Promise)return W.then((X)=>{if($.value=X.value,X.issues.length)$.value=b.catchValue({...$,error:{issues:X.issues.map((Y)=>cw(Y,Q,_w()))},input:$.value}),$.issues=[];return $});if($.value=W.value,W.issues.length)$.value=b.catchValue({...$,error:{issues:W.issues.map((X)=>cw(X,Q,_w()))},input:$.value}),$.issues=[];return $}});var E8=M("$ZodPipe",(w,b)=>{a.init(w,b),r(w._zod,"values",()=>b.in._zod.values),r(w._zod,"optin",()=>b.in._zod.optin),r(w._zod,"optout",()=>b.out._zod.optout),r(w._zod,"propValues",()=>b.in._zod.propValues),w._zod.parse=($,Q)=>{if(Q.direction==="backward"){let X=b.out._zod.run($,Q);if(X instanceof Promise)return X.then((Y)=>Cb(Y,b.in,Q));return Cb(X,b.in,Q)}let W=b.in._zod.run($,Q);if(W instanceof Promise)return W.then((X)=>Cb(X,b.out,Q));return Cb(W,b.out,Q)}});function Cb(w,b,$){if(w.issues.length)return w.aborted=!0,w;return b._zod.run({value:w.value,issues:w.issues},$)}var T8=M("$ZodReadonly",(w,b)=>{a.init(w,b),r(w._zod,"propValues",()=>b.innerType._zod.propValues),r(w._zod,"values",()=>b.innerType._zod.values),r(w._zod,"optin",()=>b.innerType._zod.optin),r(w._zod,"optout",()=>b.innerType._zod.optout),w._zod.parse=($,Q)=>{if(Q.direction==="backward")return b.innerType._zod.run($,Q);let W=b.innerType._zod.run($,Q);if(W instanceof Promise)return W.then(kW);return kW(W)}});function kW(w){return w.value=Object.freeze(w.value),w}var R8=M("$ZodCustom",(w,b)=>{Lw.init(w,b),a.init(w,b),w._zod.parse=($,Q)=>{return $},w._zod.check=($)=>{let Q=$.value,W=b.fn(Q);if(W instanceof Promise)return W.then((X)=>xW(X,$,Q,w));xW(W,$,Q,w);return}});function xW(w,b,$,Q){if(!w){let W={code:"custom",input:$,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)W.params=Q._zod.def.params;b.issues.push(i1(W))}}var I3=(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},N3=()=>{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(Q){return w[Q]??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(Q)=>{switch(Q.code){case"invalid_type":return`Invalid input: expected ${Q.expected}, received ${I3(Q.input)}`;case"invalid_value":if(Q.values.length===1)return`Invalid input: expected ${Ib(Q.values[0])}`;return`Invalid option: expected one of ${Pb(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",X=b(Q.origin);if(X)return`Too big: expected ${Q.origin??"value"} to have ${W}${Q.maximum.toString()} ${X.unit??"elements"}`;return`Too big: expected ${Q.origin??"value"} to be ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",X=b(Q.origin);if(X)return`Too small: expected ${Q.origin} to have ${W}${Q.minimum.toString()} ${X.unit}`;return`Too small: expected ${Q.origin} to be ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Invalid string: must start with "${W.prefix}"`;if(W.format==="ends_with")return`Invalid string: must end with "${W.suffix}"`;if(W.format==="includes")return`Invalid string: must include "${W.includes}"`;if(W.format==="regex")return`Invalid string: must match pattern ${W.pattern}`;return`Invalid ${$[W.format]??Q.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${Q.divisor}`;case"unrecognized_keys":return`Unrecognized key${Q.keys.length>1?"s":""}: ${Pb(Q.keys,", ")}`;case"invalid_key":return`Invalid key in ${Q.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${Q.origin}`;default:return"Invalid input"}}};function E4(){return{localeError:N3()}}var rP=Symbol("ZodOutput"),sP=Symbol("ZodInput");class S8{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 Q={...$,...this._map.get(w)};return Object.keys(Q).length?Q:void 0}return this._map.get(w)}has(w){return this._map.has(w)}}function E3(){return new S8}var E0=E3();function C8(w,b){return new w({type:"string",...C(b)})}function v8(w,b){return new w({type:"string",format:"email",check:"string_format",abort:!1,...C(b)})}function T4(w,b){return new w({type:"string",format:"guid",check:"string_format",abort:!1,...C(b)})}function _8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,...C(b)})}function k8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...C(b)})}function x8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...C(b)})}function h8(w,b){return new w({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...C(b)})}function y8(w,b){return new w({type:"string",format:"url",check:"string_format",abort:!1,...C(b)})}function u8(w,b){return new w({type:"string",format:"emoji",check:"string_format",abort:!1,...C(b)})}function f8(w,b){return new w({type:"string",format:"nanoid",check:"string_format",abort:!1,...C(b)})}function c8(w,b){return new w({type:"string",format:"cuid",check:"string_format",abort:!1,...C(b)})}function m8(w,b){return new w({type:"string",format:"cuid2",check:"string_format",abort:!1,...C(b)})}function g8(w,b){return new w({type:"string",format:"ulid",check:"string_format",abort:!1,...C(b)})}function l8(w,b){return new w({type:"string",format:"xid",check:"string_format",abort:!1,...C(b)})}function i8(w,b){return new w({type:"string",format:"ksuid",check:"string_format",abort:!1,...C(b)})}function n8(w,b){return new w({type:"string",format:"ipv4",check:"string_format",abort:!1,...C(b)})}function p8(w,b){return new w({type:"string",format:"ipv6",check:"string_format",abort:!1,...C(b)})}function o8(w,b){return new w({type:"string",format:"cidrv4",check:"string_format",abort:!1,...C(b)})}function d8(w,b){return new w({type:"string",format:"cidrv6",check:"string_format",abort:!1,...C(b)})}function t8(w,b){return new w({type:"string",format:"base64",check:"string_format",abort:!1,...C(b)})}function r8(w,b){return new w({type:"string",format:"base64url",check:"string_format",abort:!1,...C(b)})}function s8(w,b){return new w({type:"string",format:"e164",check:"string_format",abort:!1,...C(b)})}function e8(w,b){return new w({type:"string",format:"jwt",check:"string_format",abort:!1,...C(b)})}function a8(w,b){return new w({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C(b)})}function wX(w,b){return new w({type:"string",format:"date",check:"string_format",...C(b)})}function bX(w,b){return new w({type:"string",format:"time",check:"string_format",precision:null,...C(b)})}function $X(w,b){return new w({type:"string",format:"duration",check:"string_format",...C(b)})}function QX(w,b){return new w({type:"number",checks:[],...C(b)})}function WX(w,b){return new w({type:"number",check:"number_format",abort:!1,format:"safeint",...C(b)})}function XX(w,b){return new w({type:"boolean",...C(b)})}function YX(w,b){return new w({type:"null",...C(b)})}function GX(w){return new w({type:"unknown"})}function JX(w,b){return new w({type:"never",...C(b)})}function kb(w,b){return new Z4({check:"less_than",...C(b),value:w,inclusive:!1})}function T0(w,b){return new Z4({check:"less_than",...C(b),value:w,inclusive:!0})}function xb(w,b){return new P4({check:"greater_than",...C(b),value:w,inclusive:!1})}function R0(w,b){return new P4({check:"greater_than",...C(b),value:w,inclusive:!0})}function hb(w,b){return new LW({check:"multiple_of",...C(b),value:w})}function yb(w,b){return new BW({check:"max_length",...C(b),maximum:w})}function n1(w,b){return new OW({check:"min_length",...C(b),minimum:w})}function ub(w,b){return new MW({check:"length_equals",...C(b),length:w})}function R4(w,b){return new KW({check:"string_format",format:"regex",...C(b),pattern:w})}function S4(w){return new qW({check:"string_format",format:"lowercase",...C(w)})}function C4(w){return new ZW({check:"string_format",format:"uppercase",...C(w)})}function v4(w,b){return new PW({check:"string_format",format:"includes",...C(b),includes:w})}function _4(w,b){return new VW({check:"string_format",format:"starts_with",...C(b),prefix:w})}function k4(w,b){return new jW({check:"string_format",format:"ends_with",...C(b),suffix:w})}function _1(w){return new IW({check:"overwrite",tx:w})}function x4(w){return _1((b)=>b.normalize(w))}function h4(){return _1((w)=>w.trim())}function y4(){return _1((w)=>w.toLowerCase())}function u4(){return _1((w)=>w.toUpperCase())}function HX(w,b,$){return new w({type:"array",element:b,...C($)})}function zX(w,b,$){let Q=C($);return Q.abort??(Q.abort=!0),new w({type:"custom",check:"custom",fn:b,...Q})}function DX(w,b,$){return new w({type:"custom",check:"custom",fn:b,...C($)})}function UX(w){let b=T3(($)=>{return $.addIssue=(Q)=>{if(typeof Q==="string")$.issues.push(i1(Q,$.value,b._zod.def));else{let W=Q;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=$.value),W.inst??(W.inst=b),W.continue??(W.continue=!b._zod.def.abort),$.issues.push(i1(W))}},w($.value,$)});return b}function T3(w,b){let $=new Lw({check:"custom",...C(b)});return $._zod.check=w,$}function p1(w){return!!w._zod}function Z1(w,b){if(p1(w))return j0(w,b);return w.safeParse(b)}function fb(w){if(!w)return;let b;if(p1(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 AX(w){if(p1(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 Q=w.value;if(Q!==void 0)return Q;return}var C0={};HQ(C0,{time:()=>m4,duration:()=>g4,datetime:()=>f4,date:()=>c4,ZodISOTime:()=>BX,ZodISODuration:()=>OX,ZodISODateTime:()=>LX,ZodISODate:()=>FX});var LX=M("ZodISODateTime",(w,b)=>{oW.init(w,b),$w.init(w,b)});function f4(w){return a8(LX,w)}var FX=M("ZodISODate",(w,b)=>{dW.init(w,b),$w.init(w,b)});function c4(w){return wX(FX,w)}var BX=M("ZodISOTime",(w,b)=>{tW.init(w,b),$w.init(w,b)});function m4(w){return bX(BX,w)}var OX=M("ZodISODuration",(w,b)=>{rW.init(w,b),$w.init(w,b)});function g4(w){return $X(OX,w)}var MX=(w,b)=>{Nb.init(w,b),w.name="ZodError",Object.defineProperties(w,{format:{value:($)=>RQ(w,$)},flatten:{value:($)=>TQ(w,$)},addIssue:{value:($)=>{w.issues.push($),w.message=JSON.stringify(w.issues,g1,2)}},addIssues:{value:($)=>{w.issues.push(...$),w.message=JSON.stringify(w.issues,g1,2)}},isEmpty:{get(){return w.issues.length===0}}})},hV=M("ZodError",MX),Sw=M("ZodError",MX,{Parent:Error});var KX=Eb(Sw),qX=Tb(Sw),ZX=V0(Sw),PX=I0(Sw),VX=SQ(Sw),jX=CQ(Sw),IX=vQ(Sw),NX=_Q(Sw),EX=kQ(Sw),TX=xQ(Sw),RX=hQ(Sw),SX=yQ(Sw);var Gw=M("ZodType",(w,b)=>{return a.init(w,b),w.def=b,w.type=b.type,Object.defineProperty(w,"_def",{value:b}),w.check=(...$)=>{return w.clone(o.mergeDefs(b,{checks:[...b.checks??[],...$.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]}))},w.clone=($,Q)=>fw(w,$,Q),w.brand=()=>w,w.register=($,Q)=>{return $.add(w,Q),w},w.parse=($,Q)=>KX(w,$,Q,{callee:w.parse}),w.safeParse=($,Q)=>ZX(w,$,Q),w.parseAsync=async($,Q)=>qX(w,$,Q,{callee:w.parseAsync}),w.safeParseAsync=async($,Q)=>PX(w,$,Q),w.spa=w.safeParseAsync,w.encode=($,Q)=>VX(w,$,Q),w.decode=($,Q)=>jX(w,$,Q),w.encodeAsync=async($,Q)=>IX(w,$,Q),w.decodeAsync=async($,Q)=>NX(w,$,Q),w.safeEncode=($,Q)=>EX(w,$,Q),w.safeDecode=($,Q)=>TX(w,$,Q),w.safeEncodeAsync=async($,Q)=>RX(w,$,Q),w.safeDecodeAsync=async($,Q)=>SX(w,$,Q),w.refine=($,Q)=>w.check(jD($,Q)),w.superRefine=($)=>w.check(ID($)),w.overwrite=($)=>w.check(_1($)),w.optional=()=>Yw(w),w.nullable=()=>_X(w),w.nullish=()=>Yw(_X(w)),w.nonoptional=($)=>MD(w,$),w.array=()=>g(w),w.or=($)=>e([w,$]),w.and=($)=>mb(w,$),w.transform=($)=>i4(w,uX($)),w.default=($)=>FD(w,$),w.prefault=($)=>OD(w,$),w.catch=($)=>qD(w,$),w.pipe=($)=>i4(w,$),w.readonly=()=>VD(w),w.describe=($)=>{let Q=w.clone();return E0.add(Q,{description:$}),Q},Object.defineProperty(w,"description",{get(){return E0.get(w)?.description},configurable:!0}),w.meta=(...$)=>{if($.length===0)return E0.get(w);let Q=w.clone();return E0.add(Q,$[0]),Q},w.isOptional=()=>w.safeParse(void 0).success,w.isNullable=()=>w.safeParse(null).success,w}),kX=M("_ZodString",(w,b)=>{_b.init(w,b),Gw.init(w,b);let $=w._zod.bag;w.format=$.format??null,w.minLength=$.minimum??null,w.maxLength=$.maximum??null,w.regex=(...Q)=>w.check(R4(...Q)),w.includes=(...Q)=>w.check(v4(...Q)),w.startsWith=(...Q)=>w.check(_4(...Q)),w.endsWith=(...Q)=>w.check(k4(...Q)),w.min=(...Q)=>w.check(n1(...Q)),w.max=(...Q)=>w.check(yb(...Q)),w.length=(...Q)=>w.check(ub(...Q)),w.nonempty=(...Q)=>w.check(n1(1,...Q)),w.lowercase=(Q)=>w.check(S4(Q)),w.uppercase=(Q)=>w.check(C4(Q)),w.trim=()=>w.check(h4()),w.normalize=(...Q)=>w.check(x4(...Q)),w.toLowerCase=()=>w.check(y4()),w.toUpperCase=()=>w.check(u4())}),y3=M("ZodString",(w,b)=>{_b.init(w,b),kX.init(w,b),w.email=($)=>w.check(v8(u3,$)),w.url=($)=>w.check(y8(f3,$)),w.jwt=($)=>w.check(e8(wD,$)),w.emoji=($)=>w.check(u8(c3,$)),w.guid=($)=>w.check(T4(CX,$)),w.uuid=($)=>w.check(_8(cb,$)),w.uuidv4=($)=>w.check(k8(cb,$)),w.uuidv6=($)=>w.check(x8(cb,$)),w.uuidv7=($)=>w.check(h8(cb,$)),w.nanoid=($)=>w.check(f8(m3,$)),w.guid=($)=>w.check(T4(CX,$)),w.cuid=($)=>w.check(c8(g3,$)),w.cuid2=($)=>w.check(m8(l3,$)),w.ulid=($)=>w.check(g8(i3,$)),w.base64=($)=>w.check(t8(s3,$)),w.base64url=($)=>w.check(r8(e3,$)),w.xid=($)=>w.check(l8(n3,$)),w.ksuid=($)=>w.check(i8(p3,$)),w.ipv4=($)=>w.check(n8(o3,$)),w.ipv6=($)=>w.check(p8(d3,$)),w.cidrv4=($)=>w.check(o8(t3,$)),w.cidrv6=($)=>w.check(d8(r3,$)),w.e164=($)=>w.check(s8(a3,$)),w.datetime=($)=>w.check(f4($)),w.date=($)=>w.check(c4($)),w.time=($)=>w.check(m4($)),w.duration=($)=>w.check(g4($))});function B(w){return C8(y3,w)}var $w=M("ZodStringFormat",(w,b)=>{ww.init(w,b),kX.init(w,b)}),u3=M("ZodEmail",(w,b)=>{uW.init(w,b),$w.init(w,b)});var CX=M("ZodGUID",(w,b)=>{hW.init(w,b),$w.init(w,b)});var cb=M("ZodUUID",(w,b)=>{yW.init(w,b),$w.init(w,b)});var f3=M("ZodURL",(w,b)=>{fW.init(w,b),$w.init(w,b)});var c3=M("ZodEmoji",(w,b)=>{cW.init(w,b),$w.init(w,b)});var m3=M("ZodNanoID",(w,b)=>{mW.init(w,b),$w.init(w,b)});var g3=M("ZodCUID",(w,b)=>{gW.init(w,b),$w.init(w,b)});var l3=M("ZodCUID2",(w,b)=>{lW.init(w,b),$w.init(w,b)});var i3=M("ZodULID",(w,b)=>{iW.init(w,b),$w.init(w,b)});var n3=M("ZodXID",(w,b)=>{nW.init(w,b),$w.init(w,b)});var p3=M("ZodKSUID",(w,b)=>{pW.init(w,b),$w.init(w,b)});var o3=M("ZodIPv4",(w,b)=>{sW.init(w,b),$w.init(w,b)});var d3=M("ZodIPv6",(w,b)=>{eW.init(w,b),$w.init(w,b)});var t3=M("ZodCIDRv4",(w,b)=>{aW.init(w,b),$w.init(w,b)});var r3=M("ZodCIDRv6",(w,b)=>{w8.init(w,b),$w.init(w,b)});var s3=M("ZodBase64",(w,b)=>{$8.init(w,b),$w.init(w,b)});var e3=M("ZodBase64URL",(w,b)=>{Q8.init(w,b),$w.init(w,b)});var a3=M("ZodE164",(w,b)=>{W8.init(w,b),$w.init(w,b)});var wD=M("ZodJWT",(w,b)=>{X8.init(w,b),$w.init(w,b)});var xX=M("ZodNumber",(w,b)=>{I4.init(w,b),Gw.init(w,b),w.gt=(Q,W)=>w.check(xb(Q,W)),w.gte=(Q,W)=>w.check(R0(Q,W)),w.min=(Q,W)=>w.check(R0(Q,W)),w.lt=(Q,W)=>w.check(kb(Q,W)),w.lte=(Q,W)=>w.check(T0(Q,W)),w.max=(Q,W)=>w.check(T0(Q,W)),w.int=(Q)=>w.check(vX(Q)),w.safe=(Q)=>w.check(vX(Q)),w.positive=(Q)=>w.check(xb(0,Q)),w.nonnegative=(Q)=>w.check(R0(0,Q)),w.negative=(Q)=>w.check(kb(0,Q)),w.nonpositive=(Q)=>w.check(T0(0,Q)),w.multipleOf=(Q,W)=>w.check(hb(Q,W)),w.step=(Q,W)=>w.check(hb(Q,W)),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 t(w){return QX(xX,w)}var bD=M("ZodNumberFormat",(w,b)=>{Y8.init(w,b),xX.init(w,b)});function vX(w){return WX(bD,w)}var $D=M("ZodBoolean",(w,b)=>{G8.init(w,b),Gw.init(w,b)});function Aw(w){return XX($D,w)}var QD=M("ZodNull",(w,b)=>{J8.init(w,b),Gw.init(w,b)});function n4(w){return YX(QD,w)}var WD=M("ZodUnknown",(w,b)=>{H8.init(w,b),Gw.init(w,b)});function Qw(){return GX(WD)}var XD=M("ZodNever",(w,b)=>{z8.init(w,b),Gw.init(w,b)});function YD(w){return JX(XD,w)}var GD=M("ZodArray",(w,b)=>{D8.init(w,b),Gw.init(w,b),w.element=b.element,w.min=($,Q)=>w.check(n1($,Q)),w.nonempty=($)=>w.check(n1(1,$)),w.max=($,Q)=>w.check(yb($,Q)),w.length=($,Q)=>w.check(ub($,Q)),w.unwrap=()=>w.element});function g(w,b){return HX(GD,w,b)}var hX=M("ZodObject",(w,b)=>{L8.init(w,b),Gw.init(w,b),o.defineLazy(w,"shape",()=>{return b.shape}),w.keyof=()=>jw(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:YD()}),w.strip=()=>w.clone({...w._zod.def,catchall:void 0}),w.extend=($)=>{return o.extend(w,$)},w.safeExtend=($)=>{return o.safeExtend(w,$)},w.merge=($)=>o.merge(w,$),w.pick=($)=>o.pick(w,$),w.omit=($)=>o.omit(w,$),w.partial=(...$)=>o.partial(fX,w,$[0]),w.required=(...$)=>o.required(cX,w,$[0])});function N(w,b){let $={type:"object",shape:w??{},...o.normalizeParams(b)};return new hX($)}function Zw(w,b){return new hX({type:"object",shape:w,catchall:Qw(),...o.normalizeParams(b)})}var yX=M("ZodUnion",(w,b)=>{N4.init(w,b),Gw.init(w,b),w.options=b.options});function e(w,b){return new yX({type:"union",options:w,...o.normalizeParams(b)})}var JD=M("ZodDiscriminatedUnion",(w,b)=>{yX.init(w,b),F8.init(w,b)});function p4(w,b,$){return new JD({type:"union",options:b,discriminator:w,...o.normalizeParams($)})}var HD=M("ZodIntersection",(w,b)=>{B8.init(w,b),Gw.init(w,b)});function mb(w,b){return new HD({type:"intersection",left:w,right:b})}var zD=M("ZodRecord",(w,b)=>{O8.init(w,b),Gw.init(w,b),w.keyType=b.keyType,w.valueType=b.valueType});function Ww(w,b,$){return new zD({type:"record",keyType:w,valueType:b,...o.normalizeParams($)})}var l4=M("ZodEnum",(w,b)=>{M8.init(w,b),Gw.init(w,b),w.enum=b.entries,w.options=Object.values(b.entries);let $=new Set(Object.keys(b.entries));w.extract=(Q,W)=>{let X={};for(let Y of Q)if($.has(Y))X[Y]=b.entries[Y];else throw Error(`Key ${Y} not found in enum`);return new l4({...b,checks:[],...o.normalizeParams(W),entries:X})},w.exclude=(Q,W)=>{let X={...b.entries};for(let Y of Q)if($.has(Y))delete X[Y];else throw Error(`Key ${Y} not found in enum`);return new l4({...b,checks:[],...o.normalizeParams(W),entries:X})}});function jw(w,b){let $=Array.isArray(w)?Object.fromEntries(w.map((Q)=>[Q,Q])):w;return new l4({type:"enum",entries:$,...o.normalizeParams(b)})}var DD=M("ZodLiteral",(w,b)=>{K8.init(w,b),Gw.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 E(w,b){return new DD({type:"literal",values:Array.isArray(w)?w:[w],...o.normalizeParams(b)})}var UD=M("ZodTransform",(w,b)=>{q8.init(w,b),Gw.init(w,b),w._zod.parse=($,Q)=>{if(Q.direction==="backward")throw new M0(w.constructor.name);$.addIssue=(X)=>{if(typeof X==="string")$.issues.push(o.issue(X,$.value,b));else{let Y=X;if(Y.fatal)Y.continue=!1;Y.code??(Y.code="custom"),Y.input??(Y.input=$.value),Y.inst??(Y.inst=w),$.issues.push(o.issue(Y))}};let W=b.transform($.value,$);if(W instanceof Promise)return W.then((X)=>{return $.value=X,$});return $.value=W,$}});function uX(w){return new UD({type:"transform",transform:w})}var fX=M("ZodOptional",(w,b)=>{Z8.init(w,b),Gw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function Yw(w){return new fX({type:"optional",innerType:w})}var AD=M("ZodNullable",(w,b)=>{P8.init(w,b),Gw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function _X(w){return new AD({type:"nullable",innerType:w})}var LD=M("ZodDefault",(w,b)=>{V8.init(w,b),Gw.init(w,b),w.unwrap=()=>w._zod.def.innerType,w.removeDefault=w.unwrap});function FD(w,b){return new LD({type:"default",innerType:w,get defaultValue(){return typeof b==="function"?b():o.shallowClone(b)}})}var BD=M("ZodPrefault",(w,b)=>{j8.init(w,b),Gw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function OD(w,b){return new BD({type:"prefault",innerType:w,get defaultValue(){return typeof b==="function"?b():o.shallowClone(b)}})}var cX=M("ZodNonOptional",(w,b)=>{I8.init(w,b),Gw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function MD(w,b){return new cX({type:"nonoptional",innerType:w,...o.normalizeParams(b)})}var KD=M("ZodCatch",(w,b)=>{N8.init(w,b),Gw.init(w,b),w.unwrap=()=>w._zod.def.innerType,w.removeCatch=w.unwrap});function qD(w,b){return new KD({type:"catch",innerType:w,catchValue:typeof b==="function"?b:()=>b})}var ZD=M("ZodPipe",(w,b)=>{E8.init(w,b),Gw.init(w,b),w.in=b.in,w.out=b.out});function i4(w,b){return new ZD({type:"pipe",in:w,out:b})}var PD=M("ZodReadonly",(w,b)=>{T8.init(w,b),Gw.init(w,b),w.unwrap=()=>w._zod.def.innerType});function VD(w){return new PD({type:"readonly",innerType:w})}var mX=M("ZodCustom",(w,b)=>{R8.init(w,b),Gw.init(w,b)});function gX(w,b){return zX(mX,w??(()=>!0),b)}function jD(w,b={}){return DX(mX,w,b)}function ID(w){return UX(w)}function o4(w,b){return i4(uX(w),b)}_w(E4());var d4="2025-11-25";var lX=[d4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],P1="io.modelcontextprotocol/related-task",lb="2.0",Fw=gX((w)=>w!==null&&(typeof w==="object"||typeof w==="function")),iX=e([B(),t().int()]),nX=B(),Cj=Zw({ttl:e([t(),n4()]).optional(),pollInterval:t().optional()}),ND=N({ttl:t().optional()}),ED=N({taskId:B()}),t4=Zw({progressToken:iX.optional(),[P1]:ED.optional()}),Cw=N({_meta:t4.optional()}),v0=Cw.extend({task:ND.optional()}),pX=(w)=>v0.safeParse(w).success,Bw=N({method:B(),params:Cw.loose().optional()}),kw=N({_meta:t4.optional()}),xw=N({method:B(),params:kw.loose().optional()}),Ow=Zw({_meta:t4.optional()}),ib=e([B(),t().int()]),oX=N({jsonrpc:E(lb),id:ib,...Bw.shape}).strict(),r4=(w)=>oX.safeParse(w).success,dX=N({jsonrpc:E(lb),...xw.shape}).strict(),tX=(w)=>dX.safeParse(w).success,s4=N({jsonrpc:E(lb),id:ib,result:Ow}).strict(),_0=(w)=>s4.safeParse(w).success;var l;(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"})(l||(l={}));var e4=N({jsonrpc:E(lb),id:ib.optional(),error:N({code:t().int(),message:B(),data:Qw().optional()})}).strict();var rX=(w)=>e4.safeParse(w).success;var sX=e([oX,dX,s4,e4]),vj=e([s4,e4]),nb=Ow.strict(),TD=kw.extend({requestId:ib.optional(),reason:B().optional()}),pb=xw.extend({method:E("notifications/cancelled"),params:TD}),RD=N({src:B(),mimeType:B().optional(),sizes:g(B()).optional(),theme:jw(["light","dark"]).optional()}),k0=N({icons:g(RD).optional()}),o1=N({name:B(),title:B().optional()}),eX=o1.extend({...o1.shape,...k0.shape,version:B(),websiteUrl:B().optional(),description:B().optional()}),SD=mb(N({applyDefaults:Aw().optional()}),Ww(B(),Qw())),CD=o4((w)=>{if(w&&typeof w==="object"&&!Array.isArray(w)){if(Object.keys(w).length===0)return{form:{}}}return w},mb(N({form:SD.optional(),url:Fw.optional()}),Ww(B(),Qw()).optional())),vD=Zw({list:Fw.optional(),cancel:Fw.optional(),requests:Zw({sampling:Zw({createMessage:Fw.optional()}).optional(),elicitation:Zw({create:Fw.optional()}).optional()}).optional()}),_D=Zw({list:Fw.optional(),cancel:Fw.optional(),requests:Zw({tools:Zw({call:Fw.optional()}).optional()}).optional()}),kD=N({experimental:Ww(B(),Fw).optional(),sampling:N({context:Fw.optional(),tools:Fw.optional()}).optional(),elicitation:CD.optional(),roots:N({listChanged:Aw().optional()}).optional(),tasks:vD.optional()}),xD=Cw.extend({protocolVersion:B(),capabilities:kD,clientInfo:eX}),a4=Bw.extend({method:E("initialize"),params:xD});var hD=N({experimental:Ww(B(),Fw).optional(),logging:Fw.optional(),completions:Fw.optional(),prompts:N({listChanged:Aw().optional()}).optional(),resources:N({subscribe:Aw().optional(),listChanged:Aw().optional()}).optional(),tools:N({listChanged:Aw().optional()}).optional(),tasks:_D.optional()}),yD=Ow.extend({protocolVersion:B(),capabilities:hD,serverInfo:eX,instructions:B().optional()}),w6=xw.extend({method:E("notifications/initialized"),params:kw.optional()});var ob=Bw.extend({method:E("ping"),params:Cw.optional()}),uD=N({progress:t(),total:Yw(t()),message:Yw(B())}),fD=N({...kw.shape,...uD.shape,progressToken:iX}),db=xw.extend({method:E("notifications/progress"),params:fD}),cD=Cw.extend({cursor:nX.optional()}),x0=Bw.extend({params:cD.optional()}),h0=Ow.extend({nextCursor:nX.optional()}),mD=jw(["working","input_required","completed","failed","cancelled"]),y0=N({taskId:B(),status:mD,ttl:e([t(),n4()]),createdAt:B(),lastUpdatedAt:B(),pollInterval:Yw(t()),statusMessage:Yw(B())}),d1=Ow.extend({task:y0}),gD=kw.merge(y0),u0=xw.extend({method:E("notifications/tasks/status"),params:gD}),tb=Bw.extend({method:E("tasks/get"),params:Cw.extend({taskId:B()})}),rb=Ow.merge(y0),sb=Bw.extend({method:E("tasks/result"),params:Cw.extend({taskId:B()})}),_j=Ow.loose(),eb=x0.extend({method:E("tasks/list")}),ab=h0.extend({tasks:g(y0)}),w$=Bw.extend({method:E("tasks/cancel"),params:Cw.extend({taskId:B()})}),aX=Ow.merge(y0),wY=N({uri:B(),mimeType:Yw(B()),_meta:Ww(B(),Qw()).optional()}),bY=wY.extend({text:B()}),b6=B().refine((w)=>{try{return atob(w),!0}catch{return!1}},{message:"Invalid Base64 string"}),$Y=wY.extend({blob:b6}),f0=jw(["user","assistant"]),t1=N({audience:g(f0).optional(),priority:t().min(0).max(1).optional(),lastModified:C0.datetime({offset:!0}).optional()}),QY=N({...o1.shape,...k0.shape,uri:B(),description:Yw(B()),mimeType:Yw(B()),annotations:t1.optional(),_meta:Yw(Zw({}))}),lD=N({...o1.shape,...k0.shape,uriTemplate:B(),description:Yw(B()),mimeType:Yw(B()),annotations:t1.optional(),_meta:Yw(Zw({}))}),$6=x0.extend({method:E("resources/list")}),iD=h0.extend({resources:g(QY)}),nD=x0.extend({method:E("resources/templates/list")}),pD=h0.extend({resourceTemplates:g(lD)}),Q6=Cw.extend({uri:B()}),oD=Q6,W6=Bw.extend({method:E("resources/read"),params:oD}),dD=Ow.extend({contents:g(e([bY,$Y]))}),tD=xw.extend({method:E("notifications/resources/list_changed"),params:kw.optional()}),rD=Q6,sD=Bw.extend({method:E("resources/subscribe"),params:rD}),eD=Q6,aD=Bw.extend({method:E("resources/unsubscribe"),params:eD}),wU=kw.extend({uri:B()}),bU=xw.extend({method:E("notifications/resources/updated"),params:wU}),$U=N({name:B(),description:Yw(B()),required:Yw(Aw())}),QU=N({...o1.shape,...k0.shape,description:Yw(B()),arguments:Yw(g($U)),_meta:Yw(Zw({}))}),WU=x0.extend({method:E("prompts/list")}),XU=h0.extend({prompts:g(QU)}),YU=Cw.extend({name:B(),arguments:Ww(B(),B()).optional()}),GU=Bw.extend({method:E("prompts/get"),params:YU}),X6=N({type:E("text"),text:B(),annotations:t1.optional(),_meta:Ww(B(),Qw()).optional()}),Y6=N({type:E("image"),data:b6,mimeType:B(),annotations:t1.optional(),_meta:Ww(B(),Qw()).optional()}),G6=N({type:E("audio"),data:b6,mimeType:B(),annotations:t1.optional(),_meta:Ww(B(),Qw()).optional()}),JU=N({type:E("tool_use"),name:B(),id:B(),input:Ww(B(),Qw()),_meta:Ww(B(),Qw()).optional()}),HU=N({type:E("resource"),resource:e([bY,$Y]),annotations:t1.optional(),_meta:Ww(B(),Qw()).optional()}),zU=QY.extend({type:E("resource_link")}),J6=e([X6,Y6,G6,zU,HU]),DU=N({role:f0,content:J6}),UU=Ow.extend({description:B().optional(),messages:g(DU)}),AU=xw.extend({method:E("notifications/prompts/list_changed"),params:kw.optional()}),LU=N({title:B().optional(),readOnlyHint:Aw().optional(),destructiveHint:Aw().optional(),idempotentHint:Aw().optional(),openWorldHint:Aw().optional()}),FU=N({taskSupport:jw(["required","optional","forbidden"]).optional()}),WY=N({...o1.shape,...k0.shape,description:B().optional(),inputSchema:N({type:E("object"),properties:Ww(B(),Fw).optional(),required:g(B()).optional()}).catchall(Qw()),outputSchema:N({type:E("object"),properties:Ww(B(),Fw).optional(),required:g(B()).optional()}).catchall(Qw()).optional(),annotations:LU.optional(),execution:FU.optional(),_meta:Ww(B(),Qw()).optional()}),H6=x0.extend({method:E("tools/list")}),BU=h0.extend({tools:g(WY)}),b$=Ow.extend({content:g(J6).default([]),structuredContent:Ww(B(),Qw()).optional(),isError:Aw().optional()}),kj=b$.or(Ow.extend({toolResult:Qw()})),OU=v0.extend({name:B(),arguments:Ww(B(),Qw()).optional()}),c0=Bw.extend({method:E("tools/call"),params:OU}),MU=xw.extend({method:E("notifications/tools/list_changed"),params:kw.optional()}),xj=N({autoRefresh:Aw().default(!0),debounceMs:t().int().nonnegative().default(300)}),m0=jw(["debug","info","notice","warning","error","critical","alert","emergency"]),KU=Cw.extend({level:m0}),z6=Bw.extend({method:E("logging/setLevel"),params:KU}),qU=kw.extend({level:m0,logger:B().optional(),data:Qw()}),ZU=xw.extend({method:E("notifications/message"),params:qU}),PU=N({name:B().optional()}),VU=N({hints:g(PU).optional(),costPriority:t().min(0).max(1).optional(),speedPriority:t().min(0).max(1).optional(),intelligencePriority:t().min(0).max(1).optional()}),jU=N({mode:jw(["auto","required","none"]).optional()}),IU=N({type:E("tool_result"),toolUseId:B().describe("The unique identifier for the corresponding tool call."),content:g(J6).default([]),structuredContent:N({}).loose().optional(),isError:Aw().optional(),_meta:Ww(B(),Qw()).optional()}),NU=p4("type",[X6,Y6,G6]),gb=p4("type",[X6,Y6,G6,JU,IU]),EU=N({role:f0,content:e([gb,g(gb)]),_meta:Ww(B(),Qw()).optional()}),TU=v0.extend({messages:g(EU),modelPreferences:VU.optional(),systemPrompt:B().optional(),includeContext:jw(["none","thisServer","allServers"]).optional(),temperature:t().optional(),maxTokens:t().int(),stopSequences:g(B()).optional(),metadata:Fw.optional(),tools:g(WY).optional(),toolChoice:jU.optional()}),RU=Bw.extend({method:E("sampling/createMessage"),params:TU}),D6=Ow.extend({model:B(),stopReason:Yw(jw(["endTurn","stopSequence","maxTokens"]).or(B())),role:f0,content:NU}),U6=Ow.extend({model:B(),stopReason:Yw(jw(["endTurn","stopSequence","maxTokens","toolUse"]).or(B())),role:f0,content:e([gb,g(gb)])}),SU=N({type:E("boolean"),title:B().optional(),description:B().optional(),default:Aw().optional()}),CU=N({type:E("string"),title:B().optional(),description:B().optional(),minLength:t().optional(),maxLength:t().optional(),format:jw(["email","uri","date","date-time"]).optional(),default:B().optional()}),vU=N({type:jw(["number","integer"]),title:B().optional(),description:B().optional(),minimum:t().optional(),maximum:t().optional(),default:t().optional()}),_U=N({type:E("string"),title:B().optional(),description:B().optional(),enum:g(B()),default:B().optional()}),kU=N({type:E("string"),title:B().optional(),description:B().optional(),oneOf:g(N({const:B(),title:B()})),default:B().optional()}),xU=N({type:E("string"),title:B().optional(),description:B().optional(),enum:g(B()),enumNames:g(B()).optional(),default:B().optional()}),hU=e([_U,kU]),yU=N({type:E("array"),title:B().optional(),description:B().optional(),minItems:t().optional(),maxItems:t().optional(),items:N({type:E("string"),enum:g(B())}),default:g(B()).optional()}),uU=N({type:E("array"),title:B().optional(),description:B().optional(),minItems:t().optional(),maxItems:t().optional(),items:N({anyOf:g(N({const:B(),title:B()}))}),default:g(B()).optional()}),fU=e([yU,uU]),cU=e([xU,hU,fU]),mU=e([cU,SU,CU,vU]),gU=v0.extend({mode:E("form").optional(),message:B(),requestedSchema:N({type:E("object"),properties:Ww(B(),mU),required:g(B()).optional()})}),lU=v0.extend({mode:E("url"),message:B(),elicitationId:B(),url:B().url()}),iU=e([gU,lU]),nU=Bw.extend({method:E("elicitation/create"),params:iU}),pU=kw.extend({elicitationId:B()}),oU=xw.extend({method:E("notifications/elicitation/complete"),params:pU}),$$=Ow.extend({action:jw(["accept","decline","cancel"]),content:o4((w)=>w===null?void 0:w,Ww(B(),e([B(),t(),Aw(),g(B())])).optional())}),dU=N({type:E("ref/resource"),uri:B()});var tU=N({type:E("ref/prompt"),name:B()}),rU=Cw.extend({ref:e([tU,dU]),argument:N({name:B(),value:B()}),context:N({arguments:Ww(B(),B()).optional()}).optional()}),sU=Bw.extend({method:E("completion/complete"),params:rU});var eU=Ow.extend({completion:Zw({values:g(B()).max(100),total:Yw(t().int()),hasMore:Yw(Aw())})}),aU=N({uri:B().startsWith("file://"),name:B().optional(),_meta:Ww(B(),Qw()).optional()}),wA=Bw.extend({method:E("roots/list"),params:Cw.optional()}),A6=Ow.extend({roots:g(aU)}),bA=xw.extend({method:E("notifications/roots/list_changed"),params:kw.optional()}),hj=e([ob,a4,sU,z6,GU,WU,$6,nD,W6,sD,aD,c0,H6,tb,sb,eb,w$]),yj=e([pb,db,w6,bA,u0]),uj=e([nb,D6,U6,$$,A6,rb,ab,d1]),fj=e([ob,RU,nU,wA,tb,sb,eb,w$]),cj=e([pb,db,ZU,bU,tD,MU,AU,u0,oU]),mj=e([nb,yD,eU,UU,XU,iD,pD,dD,b$,BU,rb,ab,d1]);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===l.UrlElicitationRequired&&$){let Q=$;if(Q.elicitations)return new XY(Q.elicitations,b)}return new u(w,b,$)}}class XY extends u{constructor(w,b=`URL elicitation${w.length>1?"s":""} required`){super(l.UrlElicitationRequired,b,{elicitations:w})}get elicitations(){return this.data?.elicitations??[]}}function V1(w){return w==="completed"||w==="failed"||w==="cancelled"}var $A=Symbol("Let zodToJsonSchema decide on which parser to use");var qI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function L6(w){let $=fb(w)?.method;if(!$)throw Error("Schema is missing a method literal");let Q=AX($);if(typeof Q!=="string")throw Error("Schema method literal must be a string");return Q}function F6(w,b){let $=Z1(w,b);if(!$.success)throw $.error;return $.data}var JA=60000;class B6{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(pb,(b)=>{this._oncancel(b)}),this.setNotificationHandler(db,(b)=>{this._onprogress(b)}),this.setRequestHandler(ob,(b)=>({})),this._taskStore=w?.taskStore,this._taskMessageQueue=w?.taskMessageQueue,this._taskStore)this.setRequestHandler(tb,async(b,$)=>{let Q=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!Q)throw new u(l.InvalidParams,"Failed to retrieve task: Task not found");return{...Q}}),this.setRequestHandler(sb,async(b,$)=>{let Q=async()=>{let W=b.params.taskId;if(this._taskMessageQueue){let Y;while(Y=await this._taskMessageQueue.dequeue(W,$.sessionId)){if(Y.type==="response"||Y.type==="error"){let G=Y.message,J=G.id,H=this._requestResolvers.get(J);if(H)if(this._requestResolvers.delete(J),Y.type==="response")H(G);else{let z=G,D=new u(z.error.code,z.error.message,z.error.data);H(D)}else{let z=Y.type==="response"?"Response":"Error";this._onerror(Error(`${z} handler missing for request ${J}`))}continue}await this._transport?.send(Y.message,{relatedRequestId:$.requestId})}}let X=await this._taskStore.getTask(W,$.sessionId);if(!X)throw new u(l.InvalidParams,`Task not found: ${W}`);if(!V1(X.status))return await this._waitForTaskUpdate(W,$.signal),await Q();if(V1(X.status)){let Y=await this._taskStore.getTaskResult(W,$.sessionId);return this._clearTaskQueue(W),{...Y,_meta:{...Y._meta,[P1]:{taskId:W}}}}return await Q()};return await Q()}),this.setRequestHandler(eb,async(b,$)=>{try{let{tasks:Q,nextCursor:W}=await this._taskStore.listTasks(b.params?.cursor,$.sessionId);return{tasks:Q,nextCursor:W,_meta:{}}}catch(Q){throw new u(l.InvalidParams,`Failed to list tasks: ${Q instanceof Error?Q.message:String(Q)}`)}}),this.setRequestHandler(w$,async(b,$)=>{try{let Q=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!Q)throw new u(l.InvalidParams,`Task not found: ${b.params.taskId}`);if(V1(Q.status))throw new u(l.InvalidParams,`Cannot cancel task in terminal status: ${Q.status}`);await this._taskStore.updateTaskStatus(b.params.taskId,"cancelled","Client cancelled task execution.",$.sessionId),this._clearTaskQueue(b.params.taskId);let W=await this._taskStore.getTask(b.params.taskId,$.sessionId);if(!W)throw new u(l.InvalidParams,`Task not found after cancellation: ${b.params.taskId}`);return{_meta:{},...W}}catch(Q){if(Q instanceof u)throw Q;throw new u(l.InvalidRequest,`Failed to cancel task: ${Q instanceof Error?Q.message:String(Q)}`)}})}async _oncancel(w){if(!w.params.requestId)return;this._requestHandlerAbortControllers.get(w.params.requestId)?.abort(w.params.reason)}_setupTimeout(w,b,$,Q,W=!1){this._timeoutInfo.set(w,{timeoutId:setTimeout(Q,b),startTime:Date.now(),timeout:b,maxTotalTimeout:$,resetTimeoutOnProgress:W,onTimeout:Q})}_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(l.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=(W)=>{$?.(W),this._onerror(W)};let Q=this._transport?.onmessage;this._transport.onmessage=(W,X)=>{if(Q?.(W,X),_0(W)||rX(W))this._onresponse(W);else if(r4(W))this._onrequest(W,X);else if(tX(W))this._onnotification(W);else this._onerror(Error(`Unknown message type: ${JSON.stringify(W)}`))},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(l.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,Q=this._transport,W=w.params?._meta?.[P1]?.taskId;if($===void 0){let H={jsonrpc:"2.0",id:w.id,error:{code:l.MethodNotFound,message:"Method not found"}};if(W&&this._taskMessageQueue)this._enqueueTaskMessage(W,{type:"error",message:H,timestamp:Date.now()},Q?.sessionId).catch((z)=>this._onerror(Error(`Failed to enqueue error response: ${z}`)));else Q?.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 Y=pX(w.params)?w.params.task:void 0,G=this._taskStore?this.requestTaskStore(w,Q?.sessionId):void 0,J={signal:X.signal,sessionId:Q?.sessionId,_meta:w.params?._meta,sendNotification:async(H)=>{let z={relatedRequestId:w.id};if(W)z.relatedTask={taskId:W};await this.notification(H,z)},sendRequest:async(H,z,D)=>{let A={...D,relatedRequestId:w.id};if(W&&!A.relatedTask)A.relatedTask={taskId:W};let L=A.relatedTask?.taskId??W;if(L&&G)await G.updateTaskStatus(L,"input_required");return await this.request(H,z,A)},authInfo:b?.authInfo,requestId:w.id,requestInfo:b?.requestInfo,taskId:W,taskStore:G,taskRequestedTtl:Y?.ttl,closeSSEStream:b?.closeSSEStream,closeStandaloneSSEStream:b?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(Y)this.assertTaskHandlerCapability(w.method)}).then(()=>$(w,J)).then(async(H)=>{if(X.signal.aborted)return;let z={result:H,jsonrpc:"2.0",id:w.id};if(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"response",message:z,timestamp:Date.now()},Q?.sessionId);else await Q?.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:l.InternalError,message:H.message??"Internal error",...H.data!==void 0&&{data:H.data}}};if(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"error",message:z,timestamp:Date.now()},Q?.sessionId);else await Q?.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,Q=Number(b),W=this._progressHandlers.get(Q);if(!W){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(w)}`));return}let X=this._responseHandlers.get(Q),Y=this._timeoutInfo.get(Q);if(Y&&X&&Y.resetTimeoutOnProgress)try{this._resetTimeout(Q)}catch(G){this._responseHandlers.delete(Q),this._progressHandlers.delete(Q),this._cleanupTimeout(Q),X(G);return}W($)}_onresponse(w){let b=Number(w.id),$=this._requestResolvers.get(b);if($){if(this._requestResolvers.delete(b),_0(w))$(w);else{let X=new u(w.error.code,w.error.message,w.error.data);$(X)}return}let Q=this._responseHandlers.get(b);if(Q===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 W=!1;if(_0(w)&&w.result&&typeof w.result==="object"){let X=w.result;if(X.task&&typeof X.task==="object"){let Y=X.task;if(typeof Y.taskId==="string")W=!0,this._taskProgressTokens.set(Y.taskId,b)}}if(!W)this._progressHandlers.delete(b);if(_0(w))Q(w);else{let X=u.fromError(w.error.code,w.error.message,w.error.data);Q(X)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(w,b,$){let{task:Q}=$??{};if(!Q){try{yield{type:"result",result:await this.request(w,b,$)}}catch(X){yield{type:"error",error:X instanceof u?X:new u(l.InternalError,String(X))}}return}let W;try{let X=await this.request(w,d1,$);if(X.task)W=X.task.taskId,yield{type:"taskCreated",task:X.task};else throw new u(l.InternalError,"Task creation did not return a task");while(!0){let Y=await this.getTask({taskId:W},$);if(yield{type:"taskStatus",task:Y},V1(Y.status)){if(Y.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:W},b,$)};else if(Y.status==="failed")yield{type:"error",error:new u(l.InternalError,`Task ${W} failed`)};else if(Y.status==="cancelled")yield{type:"error",error:new u(l.InternalError,`Task ${W} was cancelled`)};return}if(Y.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:W},b,$)};return}let G=Y.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((J)=>setTimeout(J,G)),$?.signal?.throwIfAborted()}}catch(X){yield{type:"error",error:X instanceof u?X:new u(l.InternalError,String(X))}}}request(w,b,$){let{relatedRequestId:Q,resumptionToken:W,onresumptiontoken:X,task:Y,relatedTask:G}=$??{};return new Promise((J,H)=>{let z=(V)=>{H(V)};if(!this._transport){z(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(w.method),Y)this.assertTaskCapability(w.method)}catch(V){z(V);return}$?.signal?.throwIfAborted();let D=this._requestMessageId++,A={...w,jsonrpc:"2.0",id:D};if($?.onprogress)this._progressHandlers.set(D,$.onprogress),A.params={...w.params,_meta:{...w.params?._meta||{},progressToken:D}};if(Y)A.params={...A.params,task:Y};if(G)A.params={...A.params,_meta:{...A.params?._meta||{},[P1]:G}};let L=(V)=>{this._responseHandlers.delete(D),this._progressHandlers.delete(D),this._cleanupTimeout(D),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:D,reason:String(V)}},{relatedRequestId:Q,resumptionToken:W,onresumptiontoken:X}).catch((R)=>this._onerror(Error(`Failed to send cancellation: ${R}`)));let _=V instanceof u?V:new u(l.RequestTimeout,String(V));H(_)};this._responseHandlers.set(D,(V)=>{if($?.signal?.aborted)return;if(V instanceof Error)return H(V);try{let _=Z1(b,V.result);if(!_.success)H(_.error);else J(_.data)}catch(_){H(_)}}),$?.signal?.addEventListener("abort",()=>{L($?.signal?.reason)});let O=$?.timeout??JA,K=()=>L(u.fromError(l.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(D,O,$?.maxTotalTimeout,K,$?.resetTimeoutOnProgress??!1);let j=G?.taskId;if(j){let V=(_)=>{let R=this._responseHandlers.get(D);if(R)R(_);else this._onerror(Error(`Response handler missing for side-channeled request ${D}`))};this._requestResolvers.set(D,V),this._enqueueTaskMessage(j,{type:"request",message:A,timestamp:Date.now()}).catch((_)=>{this._cleanupTimeout(D),H(_)})}else this._transport.send(A,{relatedRequestId:Q,resumptionToken:W,onresumptiontoken:X}).catch((V)=>{this._cleanupTimeout(D),H(V)})})}async getTask(w,b){return this.request({method:"tasks/get",params:w},rb,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},ab,b)}async cancelTask(w,b){return this.request({method:"tasks/cancel",params:w},aX,b)}async notification(w,b){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(w.method);let $=b?.relatedTask?.taskId;if($){let Y={...w,jsonrpc:"2.0",params:{...w.params,_meta:{...w.params?._meta||{},[P1]:b.relatedTask}}};await this._enqueueTaskMessage($,{type:"notification",message:Y,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 Y={...w,jsonrpc:"2.0"};if(b?.relatedTask)Y={...Y,params:{...Y.params,_meta:{...Y.params?._meta||{},[P1]:b.relatedTask}}};this._transport?.send(Y,b).catch((G)=>this._onerror(G))});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 $=L6(w);this.assertRequestHandlerCapability($),this._requestHandlers.set($,(Q,W)=>{let X=F6(w,Q);return Promise.resolve(b(X,W))})}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 $=L6(w);this._notificationHandlers.set($,(Q)=>{let W=F6(w,Q);return Promise.resolve(b(W))})}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 Q=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(w,b,$,Q)}async _clearTaskQueue(w,b){if(this._taskMessageQueue){let $=await this._taskMessageQueue.dequeueAll(w,b);for(let Q of $)if(Q.type==="request"&&r4(Q.message)){let W=Q.message.id,X=this._requestResolvers.get(W);if(X)X(new u(l.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(W);else this._onerror(Error(`Resolver missing for request ${W} during task ${w} cleanup`))}}}async _waitForTaskUpdate(w,b){let $=this._options?.defaultTaskPollInterval??1000;try{let Q=await this._taskStore?.getTask(w);if(Q?.pollInterval)$=Q.pollInterval}catch{}return new Promise((Q,W)=>{if(b.aborted){W(new u(l.InvalidRequest,"Request cancelled"));return}let X=setTimeout(Q,$);b.addEventListener("abort",()=>{clearTimeout(X),W(new u(l.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(w,b){let $=this._taskStore;if(!$)throw Error("No task store configured");return{createTask:async(Q)=>{if(!w)throw Error("No request provided");return await $.createTask(Q,w.id,{method:w.method,params:w.params},b)},getTask:async(Q)=>{let W=await $.getTask(Q,b);if(!W)throw new u(l.InvalidParams,"Failed to retrieve task: Task not found");return W},storeTaskResult:async(Q,W,X)=>{await $.storeTaskResult(Q,W,X,b);let Y=await $.getTask(Q,b);if(Y){let G=u0.parse({method:"notifications/tasks/status",params:Y});if(await this.notification(G),V1(Y.status))this._cleanupTaskProgressHandler(Q)}},getTaskResult:(Q)=>{return $.getTaskResult(Q,b)},updateTaskStatus:async(Q,W,X)=>{let Y=await $.getTask(Q,b);if(!Y)throw new u(l.InvalidParams,`Task "${Q}" not found - it may have been cleaned up`);if(V1(Y.status))throw new u(l.InvalidParams,`Cannot update task "${Q}" from terminal status "${Y.status}" to "${W}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await $.updateTaskStatus(Q,W,X,b);let G=await $.getTask(Q,b);if(G){let J=u0.parse({method:"notifications/tasks/status",params:G});if(await this.notification(J),V1(G.status))this._cleanupTaskProgressHandler(Q)}},listTasks:(Q)=>{return $.listTasks(Q,b)}}}}function YY(w){return w!==null&&typeof w==="object"&&!Array.isArray(w)}function GY(w,b){let $={...w};for(let Q in b){let W=Q,X=b[W];if(X===void 0)continue;let Y=$[W];if(YY(Y)&&YY(X))$[W]={...Y,...X};else $[W]=X}return $}var uH=JQ(z9(),1),fH=JQ(yH(),1);function OZ(){let w=new uH.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return fH.default(w),w}class q9{constructor(w){this._ajv=w??OZ()}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 Z9{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 cH(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 mH(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 P9 extends B6{constructor(w,b){super(b);if(this._serverInfo=w,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(m0.options.map(($,Q)=>[$,Q])),this.isMessageIgnored=($,Q)=>{let W=this._loggingLevels.get(Q);return W?this.LOG_LEVEL_SEVERITY.get($)<this.LOG_LEVEL_SEVERITY.get(W):!1},this._capabilities=b?.capabilities??{},this._instructions=b?.instructions,this._jsonSchemaValidator=b?.jsonSchemaValidator??new q9,this.setRequestHandler(a4,($)=>this._oninitialize($)),this.setNotificationHandler(w6,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(z6,async($,Q)=>{let W=Q.sessionId||Q.requestInfo?.headers["mcp-session-id"]||void 0,{level:X}=$.params,Y=m0.safeParse(X);if(Y.success)this._loggingLevels.set(W,Y.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new Z9(this)};return this._experimental}registerCapabilities(w){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=GY(this._capabilities,w)}setRequestHandler(w,b){let Q=fb(w)?.method;if(!Q)throw Error("Schema is missing a method literal");let W;if(p1(Q)){let Y=Q;W=Y._zod?.def?.value??Y.value}else{let Y=Q;W=Y._def?.value??Y.value}if(typeof W!=="string")throw Error("Schema method literal must be a string");if(W==="tools/call"){let Y=async(G,J)=>{let H=Z1(c0,G);if(!H.success){let L=H.error instanceof Error?H.error.message:String(H.error);throw new u(l.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:z}=H.data,D=await Promise.resolve(b(G,J));if(z.task){let L=Z1(d1,D);if(!L.success){let O=L.error instanceof Error?L.error.message:String(L.error);throw new u(l.InvalidParams,`Invalid task creation result: ${O}`)}return L.data}let A=Z1(b$,D);if(!A.success){let L=A.error instanceof Error?A.error.message:String(A.error);throw new u(l.InvalidParams,`Invalid tools/call result: ${L}`)}return A.data};return super.setRequestHandler(w,Y)}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){mH(this._clientCapabilities?.tasks?.requests,w,"Client")}assertTaskHandlerCapability(w){if(!this._capabilities)return;cH(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:lX.includes(b)?b:d4,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"},nb)}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],Q=Array.isArray($.content)?$.content:[$.content],W=Q.some((J)=>J.type==="tool_result"),X=w.messages.length>1?w.messages[w.messages.length-2]:void 0,Y=X?Array.isArray(X.content)?X.content:[X.content]:[],G=Y.some((J)=>J.type==="tool_use");if(W){if(Q.some((J)=>J.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!G)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(G){let J=new Set(Y.filter((z)=>z.type==="tool_use").map((z)=>z.id)),H=new Set(Q.filter((z)=>z.type==="tool_result").map((z)=>z.toolUseId));if(J.size!==H.size||![...J].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},U6,b);return this.request({method:"sampling/createMessage",params:w},D6,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 Q=w;return this.request({method:"elicitation/create",params:Q},$$,b)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let Q=w.mode==="form"?w:{...w,mode:"form"},W=await this.request({method:"elicitation/create",params:Q},$$,b);if(W.action==="accept"&&W.content&&Q.requestedSchema)try{let Y=this._jsonSchemaValidator.getValidator(Q.requestedSchema)(W.content);if(!Y.valid)throw new u(l.InvalidParams,`Elicitation response content does not match requested schema: ${Y.errorMessage}`)}catch(X){if(X instanceof u)throw X;throw new u(l.InternalError,`Error validating elicitation response: ${X instanceof Error?X.message:String(X)}`)}return W}}}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},A6,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 gH={name:"@sequenzy/mcp",version:"0.0.130",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 V9=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],lH={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 KZ(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 w1(w){return encodeURIComponent(w)}function zw(w,b){return`${w}${b}`}function Dw(w,b=""){return`/dashboard/company/${w1(w)}${b}`}function iH(w,b,$){return zw(w,`${Dw(b,"/settings")}?tab=${encodeURIComponent($)}`)}function qZ(w,b){let $=V9.map((Q)=>[Q,b?iH(w,b,Q):""]);return Object.fromEntries($)}function D1(w={},b){let $=KZ(b),Q=ow(w.companyId),W={},X=qZ($,Q);if(!Q)return{appUrl:$,routeTemplates:lH,settingsTabValues:V9,urls:W,settingsUrls:X};W.dashboard=zw($,Dw(Q)),W.campaigns=zw($,Dw(Q,"/campaign")),W.landingPages=zw($,Dw(Q,"/landing-pages")),W.sequences=zw($,Dw(Q,"/sequences")),W.settings=zw($,Dw(Q,"/settings")),W.emails=zw($,Dw(Q,"/emails")),W.subscribers=zw($,Dw(Q,"/subscribers")),W.sentEmails=zw($,Dw(Q,"/sent-emails")),W.segments=zw($,Dw(Q,"/segments")),W.metrics=zw($,Dw(Q,"/metrics")),W.transactional=zw($,Dw(Q,"/transactional"));let Y=ow(w.campaignId);if(Y)W.campaign=zw($,Dw(Q,`/campaign/${w1(Y)}`)),W.campaignPreview=`${W.campaign}?step=review`;let G=ow(w.landingPageId);if(G)W.landingPage=zw($,Dw(Q,`/landing-pages/${w1(G)}`));let J=ow(w.sequenceId);if(J)W.sequence=zw($,Dw(Q,`/sequences/${w1(J)}`));let H=ow(w.emailId)??ow(w.templateId);if(H)W.email=zw($,Dw(Q,`/emails/${w1(H)}`)),W.template=W.email;let z=ow(w.transactionalId);if(z)W.transactionalEmail=zw($,Dw(Q,`/transactional/${w1(z)}`));let D=ow(w.emailSendId);if(D)W.emailSend=zw($,Dw(Q,`/sent-emails/${w1(D)}`));let A=ow(w.domainId);if(A)W.domain=zw($,Dw(Q,`/settings/domain/${w1(A)}`)),W.domainVerify=`${W.domain}/verify`;let L=ow(w.status);if(L)W.campaignList=zw($,Dw(Q,`/campaign/list/${w1(L)}`)),W.sequenceList=zw($,Dw(Q,`/sequences/list/${w1(L)}`));let O=ow(w.settingsTab);if(O)W.settingsTab=iH($,Q,O);return{appUrl:$,routeTemplates:lH,settingsTabValues:V9,urls:W,settingsUrls:X}}var nH=[{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 pH(w){try{let b;switch(w){case"sequenzy://dashboard":b=await U("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let $=await U("GET","/api/v1/account"),Q=B1()??$.currentCompanyId;if(!Q)throw Error("No company available. Create or select a company first.");b=await U("GET",`/api/v1/companies/${Q}`);break}case"sequenzy://campaigns/recent":b=await U("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":b=await U("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":b=await U("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":b=await U("GET","/api/v1/sequences");break;case"sequenzy://templates":b=await U("GET","/api/v1/templates");break;case"sequenzy://segments":b=await U("GET","/api/v1/segments");break;case"sequenzy://tags":b=await U("GET","/api/v1/tags");break;case"sequenzy://health":b=await U("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":b=D1();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:F1(b)}]}}}function v(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}function F(w,b){let $=w[b];if(typeof $!=="string")return;let Q=$.trim();return Q.length>0?Q:void 0}function Z(w,b,$){let Q=F(b,$);if(Q===void 0)throw Error(`\`${$}\` is required when calling \`${w}\`.`);return Q}var m$=' 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 j9=' 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.',I9=' 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). Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page.',N9=' 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" }.',Jw="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.",g$=' 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`.',E9=" `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.",c1=" Unsupported fields are discarded and reported in the response `warnings` array rather than rejected.",U1=`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: [...] }.${j9}${E9}${c1}${I9}${N9}${m$}`,A1=`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\`.${j9}${E9}${I9}${N9}${m$}`,G0=`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.${j9}${E9}${I9}${N9}${m$}`,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.",oH="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.",T9=500,R9=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."},Ab=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay","transport_failure"],Lb=Ab.join(", "),l$={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},ZZ={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},J0={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:ZZ,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},H0={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},S9={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.",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},i$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:S9,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},z0=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],D0=["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.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","sequence.finished","sequence.failed","poll.answered"];var PZ=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_api_keys","list_websites","list_integrations","list_sender_profiles","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"]),VZ=new Set(["select_company","create_company","update_company","update_tracking_settings","update_sync_rules","update_shopify_automation_settings","create_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","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","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"]),jZ=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","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"]),IZ=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","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","remove_recipient_suppression"]);function NZ(w){let b=PZ.has(w),$=VZ.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:IZ.has(w),openWorldHint:jZ.has(w)}}function dH(w){return{...w,annotations:{...w.annotations,...NZ(w.name)}}}var C9={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"]},EZ=Object.entries(C9).map(([w,b])=>`${w}: ${b.join(", ")}`).join("; "),v9={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: ${EZ}.`},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},_9={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 n$(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 p$(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 $=n$([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(p$):[]}}function TZ(w){let b=w.indexOf(":");return b!==-1&&w.substring(0,b).trim().length>0}function RZ(w){let b=w.indexOf(":");return b!==-1&&w.substring(b+1).trim().length>0}function tH(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 SZ(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(),Y=$.at(-2),G=$.at(-1),J=Y===void 0?Number.NaN:Number.parseInt(Y,10);return X&&Number.isInteger(J)&&J>0&&G!==void 0&&tH(G)?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 Q=$.slice(0,-1).join(":").trim(),W=$.at(-1);return Q&&W!==void 0&&tH(W)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function CZ(w){let b=w.indexOf(":");if(b===-1)return{productId:w,subfilter:null,rawValue:null};let $=w.substring(0,b),Q=w.substring(b+1),W=Q.indexOf(":");if(W===-1)return{productId:$,subfilter:Q,rawValue:null};return{productId:$,subfilter:Q.substring(0,W),rawValue:Q.substring(W+1)}}function vZ(w){return w.trim().toLowerCase().replace(/[-\s]+/g,"_")}function _Z(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 kZ(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 xZ(w){return["is","is_not","gte","lte","gt","lt"].includes(w)}function hZ(w,b,$){if(w==="stripeProduct"){if(b!=="at_least"&&b!=="less_than_count")return null;let G=$.indexOf(":");if(G===-1)return null;let J=$.substring(0,G).trim(),H=Number.parseInt($.substring(G+1).trim(),10);return J&&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:Q,subfilter:W,rawValue:X}=CZ($);if(!Q.trim())return"Stripe product filters must include a product ID.";if(!W)return b==="is"||b==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let Y=vZ(W);if(_Z(Y))return b==="is"||b==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!kZ(w,Y))return`Unsupported Stripe product subfilter "${W}".`;if(!xZ(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 rH=new Set(["shopify","woocommerce","api"]);function yZ(w,b){let $=b.trim(),Q=$.indexOf(":");if(Q!==-1&&rH.has($.substring(0,Q).trim()))$=$.substring(Q+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 W=$.lastIndexOf(":");if(W===-1)return null;let X=$.substring(0,W).trim(),Y=Number.parseInt($.substring(W+1).trim(),10);return X&&Number.isInteger(Y)&&Y>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function uZ(w,b){let $=b.trim(),Q=$.indexOf(":");if(Q!==-1&&rH.has($.substring(0,Q).trim()))$=$.substring(Q+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 W=$.lastIndexOf(":");if(W===-1)return null;let X=$.substring(0,W).trim(),Y=Number.parseInt($.substring(W+1).trim(),10);return X&&Number.isInteger(Y)&&Y>=1?null:'Purchased Collection threshold filters must use "provider:collection:count" with a count of at least 1.'}function fZ(w){let b;try{b=JSON.parse(w)}catch{return`Poll response filters must use valid JSON. ${C1}`}if(!v(b)||b.v!==1||typeof b.campaignId!=="string"||!b.campaignId.trim()||typeof b.blockId!=="string"||!b.blockId.trim()||!v(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 o$(w){if(typeof w!=="object"||w===null)return"Segment filters must be objects.";let b=w,$=b.field,Q=b.operator,W=b.value;if(typeof $!=="string"||!($ in C9))return`Unsupported segment filter field "${String($)}".`;if(typeof Q!=="string")return`Segment filter "${$}" must include an operator.`;let X=C9[$];if(!X.includes(Q))return`Operator "${Q}" is not supported for ${$} filters. Use one of: ${X.join(", ")}.`;if(Q!=="is_empty"&&Q!=="is_not_empty"&&(typeof W!=="string"||W.trim().length===0))return`Segment filter "${$}" must include a value.`;if($==="attribute"&&typeof W==="string"){if(!TZ(W))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(Q!=="is_empty"&&Q!=="is_not_empty"&&!RZ(W))return'Attribute filters must include a value after "attributeName:".'}if($==="event"&&typeof W==="string"){let Y=SZ(Q,W);if(Y)return Y}if($==="pollResponse"&&typeof W==="string"){let Y=fZ(W);if(Y)return Y}if(($==="stripeProduct"||$==="stripeCurrentProduct"||$==="stripeTrialProduct")&&typeof W==="string"){let Y=hZ($,Q,W);if(Y)return Y}if($==="commerceProduct"&&typeof W==="string"){let Y=yZ(Q,W);if(Y)return Y}if($==="commerceCollection"&&typeof W==="string"){let Y=uZ(Q,W);if(Y)return Y}if($==="tag"&&(Q==="contains"||Q==="not_contains")){if(!(typeof W==="string"&&W.split(",").map((G)=>G.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function d$(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 $=o$(b);return $?[$]:[]}if(Array.isArray(b.children))return b.children.flatMap(d$);return[]}function vw(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 aH(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 Q=b?w.filters.flatMap((W)=>{let X=o$(W);return X?[X]:[]}):d$(w.root);if(Q.length>0)throw Error(Q[0]??"Invalid segment filter in `create_segment`.")}function wz(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 Q=b?w.filters.flatMap((W)=>{let X=o$(W);return X?[X]:[]}):$?d$(w.root):[];if(Q.length>0)throw Error(Q[0]??"Invalid segment filter in `update_segment`.")}var k9=["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 x9(w,b,$){if(b[$]!==void 0&&!v(b[$]))throw Error(`\`${$}\` must be an object when calling \`${w}\`.`)}function sH(w,b,$){if(b[$]!==void 0&&!Array.isArray(b[$]))throw Error(`\`${$}\` must be an array when calling \`${w}\`.`)}function bz(w){let b=new Set(["companyId",...k9]),$=Object.keys(w).filter((W)=>!b.has(W));if($.length>0)throw Error(`\`update_company\` accepts only editable company settings. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}.`);let Q={};for(let W of k9)if(w[W]!==void 0)Q[W]=w[W];if(Object.keys(Q).length===0)throw Error(`Provide at least one of ${k9.map((W)=>`\`${W}\``).join(", ")} when calling \`update_company\`.`);for(let W of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingDomainMode"])if(w[W]!==void 0&&typeof w[W]!=="string")throw Error(`\`${W}\` must be a string when calling \`update_company\`.`);if(x9("update_company",w,"brandColors"),x9("update_company",w,"socialLinks"),x9("update_company",w,"pricing"),w.emailTheme!==void 0&&w.emailTheme!==null&&!v(w.emailTheme))throw Error("`emailTheme` must be an object or null when calling `update_company`.");sH("update_company",w,"valueProps"),sH("update_company",w,"testimonials");for(let W of["replyTrackingEnabled","forwardReplies"])if(w[W]!==void 0&&typeof w[W]!=="boolean")throw Error(`\`${W}\` 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 W of["fromEmail","replyTo"]){let X=w[W];if(typeof X==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(X.trim()))throw Error(`\`${W}\` must be a valid email address when calling \`update_company\`.`)}return Q}var h9=["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","defaultAttributionWindowHours","autoUtmEnabled","autoUtmSettings"],y9=["source","medium","campaign","content","term"];function $z(w){let b=new Set(["companyId",...h9]),$=Object.keys(w).filter((W)=>!b.has(W));if($.length>0)throw Error(`\`update_tracking_settings\` accepts only tracking settings. Unsupported field${$.length===1?"":"s"}: ${$.map((W)=>`\`${W}\``).join(", ")}. Reply tracking is set with \`update_company\`.`);let Q={};for(let W of h9)if(w[W]!==void 0)Q[W]=w[W];if(Object.keys(Q).length===0)throw Error(`Provide at least one of ${h9.map((W)=>`\`${W}\``).join(", ")} when calling \`update_tracking_settings\`.`);for(let W of["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","autoUtmEnabled"])if(w[W]!==void 0&&typeof w[W]!=="boolean")throw Error(`\`${W}\` 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&&!v(w.autoUtmSettings))throw Error("`autoUtmSettings` must be an object or null when calling `update_tracking_settings`.");if(v(w.autoUtmSettings)){let W=w.autoUtmSettings,X=Object.keys(W).filter((Y)=>!y9.includes(Y));if(X.length>0)throw Error(`\`autoUtmSettings\` accepts only ${y9.map((Y)=>`\`${Y}\``).join(", ")}. Unsupported: ${X.map((Y)=>`\`${Y}\``).join(", ")}.`);for(let Y of y9){let G=W[Y];if(G!==void 0&&G!==null&&typeof G!=="string")throw Error(`\`autoUtmSettings.${Y}\` must be a string or null when calling \`update_tracking_settings\`.`)}}return Q}var f9={profileKey:"senderProfileId",emailKey:"fromEmail",nameKey:"fromName",addressLabel:"From"},c9={profileKey:"replyProfileId",emailKey:"replyTo",nameKey:"replyToName",addressLabel:"Reply-To"};function m9(w){let{profileKey:b,emailKey:$,nameKey:Q,addressLabel:W}=w.pair,X=w.args[b]!==void 0,Y=w.args[$]!==void 0,G=w.args[Q]!==void 0,J=w.location?`for ${w.location} when calling \`${w.toolName}\``:`when calling \`${w.toolName}\``,H=`\`${b}\` already sets both the ${W} address and the display name, so send it without \`${$}\`${w.nameIsOverride?"":` and \`${Q}\``}.`;if(X&&Y){let[z,D]=w.profileFirst?[b,$]:[$,b];throw Error(`Provide either \`${z}\` or \`${D}\` ${J}, not both. ${H}`)}if(X&&G&&!w.nameIsOverride)throw Error(`\`${Q}\` cannot be combined with \`${b}\` ${J}. ${H}`);if(G&&!Y&&!w.nameIsOverride)throw Error(`\`${Q}\` requires \`${$}\` ${J}. Send \`${Q}\` with the \`${$}\` it names, or send \`${b}\` on its own to use an existing profile's address and name.`)}function U0(w,b,$){let Q=$?.replyFirst?[c9,f9]:[f9,c9];for(let W of Q)m9({toolName:w,args:b,pair:W})}var Qz=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function cZ(w){return Qz.some((b)=>w[b]!==void 0)}function mZ(w){if(typeof w.nodeType==="string")return w.nodeType==="action_email";return w.type===void 0||w.type==="email"}function t$(w,b,$){for(let Q of Qz){let W=$[Q];if(W!==void 0&&typeof W!=="string")throw Error(`\`${Q}\` must be a string for ${b} when calling \`${w}\`.`)}m9({toolName:w,args:$,pair:f9,location:b,profileFirst:!0,nameIsOverride:!0}),m9({toolName:w,args:$,pair:c9,location:b,profileFirst:!0})}function g9(w,b,$){if(cZ($)&&!mZ($))throw Error(`Sender identity fields are only supported for email steps at ${b} when calling \`${w}\`.`);t$(w,b,$)}function eH(w,b,$){if(!Array.isArray($))return;$.forEach((Q,W)=>{if(v(Q))t$(w,`${b}[${W}]`,Q)})}function u9(w,b,$){if(!Array.isArray($))return;$.forEach((Q,W)=>{if(v(Q))g9(w,`${b}[${W}]`,Q)})}function gZ(w){if(eH("update_sequence","emails",w.emails),eH("update_sequence","steps",w.steps),v(w.insertSteps))u9("update_sequence","insertSteps.steps",w.insertSteps.steps);if(!v(w.branch))return;if(Array.isArray(w.branch.branches))w.branch.branches.forEach(($,Q)=>{if(v($))u9("update_sequence",`branch.branches[${Q}].steps`,$.steps)});u9("update_sequence","branch.elseSteps",w.branch.elseSteps)}function Wz(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((Q)=>w[Q]!==void 0))throw Error("Provide `trigger` when replacing sequence trigger configuration with `update_sequence`.");if(U0("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.");gZ(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 lZ(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 Q=b.attributeCondition??"changed",W=typeof b.attributeValue==="string"&&b.attributeValue.trim().length>0,X=typeof b.attributePreviousValue==="string"&&b.attributePreviousValue.trim().length>0;if((Q==="changed_to"||Q==="changed_from_to")&&!W)throw Error(`\`attributeValue\` is required when calling \`${w}\` with \`attributeCondition\` \`changed_to\` or \`changed_from_to\`.`);if(Q==="changed_from_to"&&!X)throw Error(`\`attributePreviousValue\` is required when calling \`${w}\` with \`attributeCondition: "changed_from_to"\`.`)}function Xz(w){lZ("create_sequence_goal",w)}function Yz(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 Jz(w,b,$){let Q=Z(w,b,"nodeId");if(!v(b.changes)||Object.keys(b.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${$} when calling \`${w}\`.`);let W=Z(w,b,"expectedUpdatedAt");return{nodeId:Q,changes:b.changes,expectedUpdatedAt:W}}function Hz(w){let b=Jz("update_sequence_node",w,"the node update");return{...w.confirmLiveChange!==void 0&&{confirmLiveChange:w.confirmLiveChange},nodeUpdates:[b]}}function zz(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((Q,W)=>{if(!v(Q))throw Error(`\`updates[${W}]\` must be an object when calling \`update_sequence_nodes\`.`);let X=Jz("update_sequence_nodes",Q,`updates[${W}]`),Y=String(X.nodeId);if(b.has(Y))throw Error(`\`updates[${W}]\` targets duplicate nodeId '${Y}' when calling \`update_sequence_nodes\`.`);return b.add(Y),X});return{...w.confirmLiveChange!==void 0&&{confirmLiveChange:w.confirmLiveChange},nodeUpdates:$}}function Dz(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 W=F(w,"nodeId"),X=F(w,"afterNodeId"),Y=F(w,"beforeNodeId"),G=w.edges;if(b!=="replace_edges"&&!W)throw Error(`\`nodeId\` is required for ${b} when calling \`edit_sequence_graph\`.`);if(b==="replace_edges"&&W)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let J=b==="move_node"||b==="duplicate_node";if(J&&(X?1:0)+(Y?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${b} when calling \`edit_sequence_graph\`.`);if(!J&&(X||Y))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${b} when calling \`edit_sequence_graph\`.`);if((b==="replace_edges"||b==="delete_node"&&G!==void 0)&&(!Array.isArray(G)||G.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")&&G!==void 0)throw Error(`\`edges\` is not used with ${b} when calling \`edit_sequence_graph\`.`);let H=Array.isArray(G)?G.map((z,D)=>{if(!v(z))throw Error(`\`edges\` item ${D+1} must be an object when calling \`edit_sequence_graph\`.`);let A=Z("edit_sequence_graph",z,"sourceNodeId"),L=Z("edit_sequence_graph",z,"targetNodeId");if(z.condition!==void 0&&z.condition!==null&&!v(z.condition))throw Error(`\`edges\` item ${D+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:A,targetNodeId:L,...v(z.condition)?{condition:z.condition}:{}}}):void 0;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},graphEdit:{action:b,expectedRevision:$,...W?{nodeId:W}:{},...X?{afterNodeId:X}:{},...Y?{beforeNodeId:Y}:{},...H?{edges:H}:{}}}}function Uz(w){let b=F(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 Y=Z("insert_sequence_step",w,"eventName"),G=w.timeoutDays,J=G===void 0?7:G;if(typeof J!=="number"||!Number.isInteger(J)||J<1||J>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=F(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:F(w,"label")??`Wait for ${Y}`,eventName:Y,timeoutDays:J,timeoutAction:H}}]},D=F(w,"afterNodeId");if(D)z.afterNodeId=D;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:z}}if(b==="logic_branch"){let Y=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 G=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"]),J=["id","label","conditionType","tagName","tagId","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue","targetNodeId","steps"],H=w.allowEmptyPaths===!0,z=w.branches.map((L,O)=>{if(!v(L))throw Error(`\`branches[${O}]\` must be an object when calling \`insert_sequence_step\`.`);let K=Z("insert_sequence_step",L,"conditionType");if(!G.has(K))throw Error(`\`branches[${O}].conditionType\` is not supported when calling \`insert_sequence_step\`.`);let j=`branches[${O}]`;if((K==="has_tag"||K==="does_not_have_tag")&&!F(L,"tagId")&&!F(L,"tagName"))throw Error(`\`${j}\` must provide \`tagId\` or \`tagName\` for ${K} when calling \`insert_sequence_step\`.`);if(K==="in_list"&&!F(L,"listId"))throw Error(`\`${j}.listId\` is required for in_list when calling \`insert_sequence_step\`.`);if(K==="in_segment"&&!F(L,"segmentId"))throw Error(`\`${j}.segmentId\` is required for in_segment when calling \`insert_sequence_step\`.`);if(K==="event_received"&&!F(L,"eventName"))throw Error(`\`${j}.eventName\` is required for event_received when calling \`insert_sequence_step\`.`);if(K.startsWith("field_")&&(!F(L,"fieldName")||!F(L,"fieldValue")))throw Error(`\`${j}\` must provide \`fieldName\` and \`fieldValue\` for ${K} when calling \`insert_sequence_step\`.`);if(L.steps!==void 0&&!Array.isArray(L.steps))throw Error(`\`branches[${O}].steps\` must be an array when calling \`insert_sequence_step\`.`);let V=F(L,"targetNodeId"),_=Array.isArray(L.steps)&&L.steps.length>0;if(!V&&!_&&!H)throw Error(`\`branches[${O}]\` must provide \`targetNodeId\` or non-empty \`steps\` when inserting \`logic_branch\` with \`insert_sequence_step\`.`);return Object.fromEntries(J.flatMap((R)=>L[R]===void 0?[]:[[R,L[R]]]))});if(w.elseSteps!==void 0&&!Array.isArray(w.elseSteps))throw Error("`elseSteps` must be an array when calling `insert_sequence_step`.");let D=F(w,"elseTargetNodeId"),A=Array.isArray(w.elseSteps)&&w.elseSteps.length>0;if(!D&&!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:Y,...F(w,"label")?{label:F(w,"label")}:{},branches:z,...Array.isArray(w.elseSteps)?{elseSteps:w.elseSteps}:{},...D?{elseTargetNodeId:D}:{},...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 Y;if(b==="delay"){Y={type:"delay"};for(let H of["delay","delayMs","waitUntil"])if(w[H]!==void 0)Y[H]=w[H];if(Y.delay===void 0&&Y.delayMs===void 0&&Y.waitUntil===void 0)throw Error("Provide `delay`, `delayMs`, or `waitUntil` when inserting a delay step.")}else if(b==="create_discount"){Y={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)Y[H]=w[H]}else if(b==="update_subscriber"){if(!v(w.config))throw Error("`config` is required when inserting an update_subscriber step.");Y={type:"update_subscriber",nodeType:"action_update_attributes",config:w.config}}else if(b==="webhook"){let H=F(w,"method")??"POST";if(H!=="POST"&&H!=="GET")throw Error("`method` must be `POST` or `GET` when inserting a webhook step.");if(w.headers!==void 0&&(!v(w.headers)||Object.values(w.headers).some((z)=>typeof z!=="string")))throw Error("`headers` must be an object with string values when inserting a webhook step.");Y={type:"webhook",nodeType:"action_webhook",config:{label:F(w,"label")??"Webhook",url:Z("insert_sequence_step",w,"url"),method:H,...w.headers!==void 0?{headers:w.headers}:{}}}}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")&&!F(w,"tagId")&&!F(w,"tagName"))throw Error("Provide `tagId` or `tagName` for this condition step.");if(H==="in_list"&&!F(w,"listId"))throw Error("`listId` is required for an in_list condition.");if(H==="in_segment"&&!F(w,"segmentId"))throw Error("`segmentId` is required for an in_segment condition.");if(H==="event_received"&&!F(w,"eventName"))throw Error("`eventName` is required for an event_received condition.");if(H.startsWith("field_")&&(!F(w,"fieldName")||!F(w,"fieldValue")))throw Error("`fieldName` and `fieldValue` are required for field conditions.");let D={label:F(w,"label")??"Condition",conditionType:H};for(let A of["tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"])if(w[A]!==void 0)D[A]=w[A];Y={type:"condition",nodeType:"logic_condition",config:D}}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",D={label:F(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=F(w,"tagId"),L=F(w,"tagName");if(!A&&!L)throw Error("Provide `tagId` or `tagName` when inserting a tag action.");if(A)D.tagId=A;if(L)D.tagName=L}else{D.listId=Z("insert_sequence_step",w,"listId");let A=F(w,"listName");if(A)D.listName=A}Y={nodeType:z,config:D}}for(let H of["delay","delayMs","waitUntil"])if(b!=="delay"&&w[H]!==void 0)Y[H]=w[H];let G={steps:[Y]},J=F(w,"afterNodeId");if(J)G.afterNodeId=J;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:G}}let Q=b==="sms",W;if(Q){g9("insert_sequence_step","SMS step",w);let Y=F(w,"text"),G=Array.isArray(w.blocks)&&w.blocks.length>0;if(Y===void 0&&!G)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");W={type:"sms"};for(let J of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil"])if(w[J]!==void 0)W[J]=w[J]}else{vw("insert_sequence_step",w,{requireContent:!0}),t$("insert_sequence_step","email step",w),W={subject:Z("insert_sequence_step",w,"subject")};for(let Y of["name","previewText","html","blocks","delay","delayMs","waitUntil","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","isTransactional","ccEmails","bccEmails","attachments"])if(w[Y]!==void 0)W[Y]=w[Y]}let X={steps:[W]};if(w.afterNodeId!==void 0)X.afterNodeId=w.afterNodeId;return{...w.confirmStructuralChange!==void 0&&{confirmStructuralChange:w.confirmStructuralChange},insertSteps:X}}function Gz(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 Q=$.map((W)=>typeof W==="string"?W.trim():"").filter((W)=>W.length>0);if($.some((W)=>typeof W!=="string")||Q.length===0)throw Error(`\`${b}\` must contain at least one non-empty string when calling \`cancel_sequence_enrollments\`.`);return Q}function Az(w){let b=F(w,"subscriberId"),$=Gz(w,"subscriberIds"),Q=Gz(w,"fieldValues");if(w.cancelAll!==void 0&&typeof w.cancelAll!=="boolean")throw Error("`cancelAll` must be a boolean when calling `cancel_sequence_enrollments`.");let W=w.cancelAll===!0;if((b!==void 0?1:0)+($.length>0?1:0)+(Q.length>0?1:0)+(W?1:0)!==1)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `cancelAll`, `subscriberId`, `subscriberIds`, or `fieldValues`.");let Y=F(w,"fieldPath"),G=F(w,"reason");return{...W&&{cancelAll:!0},...b!==void 0&&{subscriberId:b},...$.length>0&&{subscriberIds:$},...Y!==void 0&&{fieldPath:Y},...Q.length>0&&{fieldValues:Q},...typeof w.dryRun==="boolean"&&{dryRun:w.dryRun},...G!==void 0&&{reason:G}}}function Lz(w){vw("create_campaign",w),L1("create_campaign",w);let b=F(w,"prompt")!==void 0,$=w.html!==void 0,Q=w.blocks!==void 0,W=w.templateId!==void 0;if(w.prompt!==void 0&&!b)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(b&&($||Q||W))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&&F(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function Fz(w){vw("create_template",w),L1("create_template",w);let b=F(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&&F(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function Bz(w){if(F(w,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(w.targetLists!==void 0&&!v(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 r$(w,b,$){let Q=new Set(["companyId","landingPageId","name","slug","content"]),W=Object.keys(b).filter((X)=>!Q.has(X));if(W.length>0)throw Error(`\`${w}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${W.length===1?"":"s"}: ${W.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 Oz(w){let b=new Set(["companyId","domain","verify"]),$=Object.keys(w).filter((Q)=>!b.has(Q));if($.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${$.length===1?"":"s"}: ${$.map((Q)=>`\`${Q}\``).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 Mz(w){vw("create_transactional_email",w);let b=F(w,"prompt")!==void 0,$=w.html!==void 0,Q=w.blocks!==void 0;if(w.prompt!==void 0&&!b)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(b&&($||Q))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&&!$&&!Q)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!b&&F(w,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var A0={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},iZ={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 url plus optional method and headers; logic_delay uses delayDays/delayHours/delayMinutes. Fields that do not apply to the node type are dropped.",properties:{...A0.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 URL called when a subscriber reaches this step."},method:{type:"string",enum:["POST","GET"],description:"action_webhook: HTTP method. Defaults to POST."},headers:{type:"object",description:"action_webhook: optional string-valued request headers. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},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},Fb={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."}},Bb={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:iZ,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:G0,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:H0,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:J0,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.${g$}`,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},l9={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:Bb}},required:["conditionType"],additionalProperties:!1};function Kz(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.")}function i9(w){return w.trim().toLowerCase().replace(/\s+/g,"-")}function nZ(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());return b.set("page",String(w.page)),b.set("limit",String(w.pageSize)),b}async function Zz(w,b){let $=typeof w.limit==="number"&&Number.isFinite(w.limit)?Math.max(1,Math.trunc(w.limit)):void 0,Q=Math.min(100,Math.max(1,$??100)),W=[],X=1,Y=0,G=0,J=0;while(!0){let z=nZ({query:w.query,tags:w.tags,list:w.list,listId:w.listId,listName:w.listName,segmentId:w.segmentId,status:w.status,page:X,pageSize:Q}),D=await U("GET",`/api/v1/subscribers?${z.toString()}`,void 0,b);Y=D.pagination?.total??D.subscribers.length,G=D.pagination?.totalPages??1,J+=1,W.push(...D.subscribers??[]);let A=$!==void 0&&W.length>=$,L=D.pagination?X>=D.pagination.totalPages:(D.subscribers??[]).length<Q;if(A||L)break;X+=1}let H=$!==void 0?W.slice(0,$):W;return{success:!0,subscribers:H,pagination:{page:1,limit:Q,total:Y,totalPages:G,fetchedPages:J},returned:H.length,truncated:$!==void 0&&Y>0&&H.length<Y}}function pZ(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 dw(w,b){let $=pZ(b);if(!$.email&&!$.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${w}\`.`);return $}function s$(w,b){let $=new URLSearchParams;if(b?.includeMachineEngagement)$.set("includeMachineEngagement","true");let Q=$.toString(),W=Q?`?${Q}`:"";if(w.email)return`/api/v1/subscribers/${encodeURIComponent(w.email)}${W}`;return $.set("externalId",String(w.externalId)),`/api/v1/subscribers/external?${$.toString()}`}function n9(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 Ob(w,b,$){return U("GET",s$(w,$),void 0,b)}function p(w,b,$,Q){let W=F(b,$);if(W===void 0)return;if(!Q.includes(W))throw Error(`\`${$}\` must be one of ${Q.join(", ")} when calling \`${w}\`.`);return W}function Mb(w,b,$,Q){let W=Z(w,b,$);if(!Q.includes(W))throw Error(`\`${$}\` must be one of ${Q.join(", ")} when calling \`${w}\`.`);return W}function Uw(w,b,$,Q,W){let X=b[$];if(X===void 0)return;if(typeof X!=="number"||!Number.isInteger(X)||X<Q||X>W)throw Error(`\`${$}\` must be an integer between ${Q} and ${W} when calling \`${w}\`.`);return X}function oZ(w,b){let $=[],Q=p(w,b,"eventType",Ab);if(Q)$.push(Q);if(b.eventTypes!==void 0){if(!Array.isArray(b.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${w}\`.`);b.eventTypes.forEach((W,X)=>{if(typeof W!=="string")throw Error(`\`eventTypes\` item ${X+1} must be a string when calling \`${w}\`.`);let Y=W.trim();if(!Ab.includes(Y))throw Error(`\`eventTypes\` item ${X+1} must be one of ${Ab.join(", ")} when calling \`${w}\`.`);$.push(Y)})}return[...new Set($)]}function p9(w,b){let $=new URLSearchParams,Q=oZ(w,b);if(Q.length>0)$.set("eventTypes",Q.join(","));let W=p(w,b,"period",["1h","24h","7d","30d","90d"]);if(W)$.set("period",W);let X=F(b,"start");if(X)$.set("start",X);let Y=F(b,"end");if(Y)$.set("end",Y);let G=Uw(w,b,"page",1,1e6);if(G!==void 0)$.set("page",String(G));let J=Uw(w,b,"limit",1,500);if(J!==void 0)$.set("limit",String(J));if(b.includeMachineEngagement===!0)$.set("includeMachineEngagement","true");return $}function o9(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((Q,W)=>{if(typeof Q!=="string"||!D0.includes(Q))throw Error(`\`events\` item ${W+1} must be one of ${D0.join(", ")} when calling \`${w}\`.`);return Q});if($.length===0)throw Error(`\`events\` must include at least one event type when calling \`${w}\`.`);return $}function d9(w,b){if(!Array.isArray(b.emails))throw Error(`\`emails\` must be an array when calling \`${w}\`.`);let $=[];if(b.emails.forEach((Q,W)=>{if(typeof Q!=="string")throw Error(`\`emails\` item ${W+1} must be a string when calling \`${w}\`.`);let X=Q.trim();if(X.length>0)$.push(X)}),$.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${w}\`.`);if($.length>T9)throw Error(`\`emails\` must include no more than ${T9} email addresses when calling \`${w}\`. Split larger batches into multiple calls.`);return $}function qz(w,b,$,Q){let W=b[$];if(W===void 0)return;if(!Array.isArray(W))throw Error(`\`${$}\` must be an array when calling \`${w}\`.`);let X=[];if(W.forEach((Y,G)=>{if(typeof Y!=="string")throw Error(`\`${$}\` item ${G+1} must be a string when calling \`${w}\`.`);let J=Y.trim();if(J.length>0)X.push(J)}),X.length===0)throw Error(`\`${$}\` must include at least one ${Q} when calling \`${w}\`.`);return X}function Pz(w){let $=qz("enroll_subscribers_in_sequence",w,"emails","email address"),Q=qz("enroll_subscribers_in_sequence",w,"subscriberIds","subscriber ID"),W=($?.length??0)+(Q?.length??0);if(W===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(W>R9)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${R9} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let X=F(w,"targetNodeId");return{...$!==void 0&&{emails:$},...Q!==void 0&&{subscriberIds:Q},...X!==void 0&&{targetNodeId:X}}}import{readFileSync as dZ,statSync as tZ}from"node:fs";import{basename as rZ}from"node:path";var sZ={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 eZ(w){let b=w.split(".").pop()?.toLowerCase()??"";return sZ[b]??null}var aZ=104857600;async function Vz(w,b){if(!Kb())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 $=eZ(w);if(!$)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let Q=tZ(w).size;if(Q>aZ)throw Error(`File is too large (${Math.round(Q/1048576)}MB). Delivery files must be 100MB or smaller.`);let W=dZ(w),X=await U("POST","/api/v1/products/delivery/upload-url",{filename:rZ(w),contentType:$,fileSizeBytes:Q},b),Y=await fetch(X.uploadUrl,{method:"PUT",headers:{"Content-Type":$},body:W});if(!Y.ok)throw Error(`File upload failed (${Y.status})`);return{url:X.publicUrl,fileName:X.fileName,fileSizeBytes:Q,mimeType:$}}async function e$(w){let b=F(w,"companyId");if(b)return b;let $=B1();if($)return $;try{return(await U("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function a$(w,b){let $=await e$(b);if(!$)throw Error(`A company is required when calling \`${w}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return $}function F0(w,b){if(!v(w)||!b)return w;return{...w,url:b}}function jz(w,b){if(!v(w))return w;return{...w,...b.campaign!==void 0&&{url:b.campaign},...b.campaignPreview!==void 0&&{previewUrl:b.campaignPreview}}}function L0(w,b,$){if(!Array.isArray(w)||!b)return w;return w.map((Q)=>{if(!v(Q))return Q;let W=F(Q,"id");if(!W)return Q;let X=D1({companyId:b,...$==="campaign"&&{campaignId:W},...$==="landingPage"&&{landingPageId:W},...$==="sequence"&&{sequenceId:W},...$==="template"&&{emailId:W},...$==="transactional"&&{transactionalId:W},...$==="emailSend"&&{emailSendId:W}});if($==="campaign")return jz(Q,X.urls);let Y=$==="sequence"?X.urls.sequence:$==="landingPage"?X.urls.landingPage:$==="template"?X.urls.email:$==="transactional"?X.urls.transactionalEmail:X.urls.emailSend;return F0(Q,Y)})}function wP(w){if(!Array.isArray(w))return w;return w.map((b)=>{if(!v(b))return b;let $=F(b,"id");if(!$)return b;let Q=D1({companyId:$});return{...b,url:Q.urls.dashboard,settingsUrl:Q.urls.settings}})}var t9=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 Iz(w,b,$){if(!v($)||!t9.has(w))return $;let Q=v($.company)?$.company:void 0,X=F($,"selectedCompanyId")??F($,"currentCompanyId")??F($,"companyId")??(Q?F(Q,"id"):void 0)??(Q?F(Q,"companyId"):void 0)??await e$(b);if(!X)return $;let Y=v($.campaign)?$.campaign:void 0,G=v($.sequence)?$.sequence:void 0,J=v($.landingPage)?$.landingPage:void 0,H=v($.template)?$.template:void 0,z=v($.transactional)&&!Array.isArray($.transactional)?$.transactional:void 0,D={companyId:X,campaignId:F(b,"campaignId")??F($,"campaignId")??(Y?F(Y,"id"):void 0),landingPageId:F(b,"landingPageId")??F($,"landingPageId")??(J?F(J,"id"):void 0),sequenceId:F(b,"sequenceId")??F($,"sequenceId")??(G?F(G,"id"):void 0),emailId:F($,"templateId")??(H?F(H,"id"):void 0)??(z?F(z,"emailId"):void 0)??F(b,"templateId"),transactionalId:F(b,"transactionalId")??(z?F(z,"id"):void 0)??F(b,"idOrSlug"),emailSendId:F(b,"emailSendId")??F($,"emailSendId")??(v($.emailSend)?F($.emailSend,"id"):void 0),status:F(b,"status")},A=D1(D),L=Q?D1({companyId:X}):void 0;return{...$,...Array.isArray($.companies)&&{companies:wP($.companies)},...Array.isArray($.campaigns)&&{campaigns:L0($.campaigns,X,"campaign")},...Array.isArray($.landingPages)&&{landingPages:L0($.landingPages,X,"landingPage")},...Array.isArray($.sequences)&&{sequences:L0($.sequences,X,"sequence")},...Array.isArray($.templates)&&{templates:L0($.templates,X,"template")},...Array.isArray($.transactional)&&{transactional:L0($.transactional,X,"transactional")},...Array.isArray($.emailSends)&&{emailSends:L0($.emailSends,X,"emailSend")},...Q&&L!==void 0&&{company:{...Q,url:L.urls.dashboard,settingsUrl:L.urls.settings}},...Y&&A.urls.campaign!==void 0&&{campaign:jz(Y,A.urls)},...G&&A.urls.sequence!==void 0&&{sequence:F0(G,A.urls.sequence)},...J&&A.urls.landingPage!==void 0&&{landingPage:F0(J,A.urls.landingPage)},...H&&A.urls.email!==void 0&&{template:F0(H,A.urls.email)},...z&&A.urls.transactionalEmail!==void 0&&{transactional:F0(z,A.urls.transactionalEmail)},...v($.emailSend)&&A.urls.emailSend!==void 0&&{emailSend:F0($.emailSend,A.urls.emailSend)},appUrls:A.urls}}import{readFileSync as bP,statSync as $P}from"node:fs";import{basename as QP,extname as Ez}from"node:path";var s9=5242880,WP=Math.ceil(s9/3)*4,XP=Math.ceil(WP*1.05)+256,Tz={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},YP=new Set(Object.values(Tz));function r9(w){return w?.split(";")[0]?.trim().toLowerCase()||void 0}function GP(w){return Tz[Ez(w).toLowerCase()]}function JP(w){let b=Ez(w);return(b?w.slice(0,-b.length):w).replace(/[-_]+/g," ").trim()||"Image"}function HP(w){if(w.length>XP)throw Error("Image assets must be 5MB or smaller.")}function zP(w){let b=0,$=0;for(let W=0;W<w.length;W+=1){let X=w.charCodeAt(W);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)>s9)throw Error("Image assets must be 5MB or smaller.")}function DP(w){HP(w);let b=w.trim(),$=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(b),Q=$?.[2]??b;zP(Q);let W=Q.replace(/\s+/g,"");if(W.length===0||W.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(W))throw Error("`imageBase64` must contain valid base64 image bytes.");return{bytes:Buffer.from(W,"base64"),...$?.[1]?{dataUrlContentType:r9($[1])}:{}}}function Nz(w){if(w<=0)throw Error("The image file is empty.");if(w>s9)throw Error("Image assets must be 5MB or smaller.")}function UP(w){let b=GP(w.filename)??r9(w.explicitContentType)??r9(w.dataUrlContentType);if(!b||!YP.has(b))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return b}function AP(w){let b,$,Q;if(w.filePath!==void 0){if(!Kb())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=$P(w.filePath).size;Nz(X),b=bP(w.filePath),$=w.filename??QP(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=DP(w.imageBase64);b=X.bytes,Q=X.dataUrlContentType,$=w.filename,Nz(b.byteLength)}let W=UP({filename:$,explicitContentType:w.contentType,dataUrlContentType:Q});return{bytes:b,filename:$,contentType:W,altText:w.altText??JP($)}}async function Rz(w){let b=AP(w),$=b.bytes.byteLength,Q=await U("POST","/api/v1/media/upload-url",{filename:b.filename,contentType:b.contentType,fileSizeBytes:$},w.companyId);return await MQ(Q.uploadUrl,b.bytes,b.contentType,w.companyId),(await U("POST","/api/v1/media/complete-upload",{key:Q.key,filename:Q.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 LP={type:"boolean",description:"Whether the Sequenzy operation succeeded."},Cz={type:"string",description:"Human-readable status, confirmation, or next-step message."},FP={type:"string",description:"Additional context about the result."};function S(w){return{type:"object",description:w,additionalProperties:!0}}function $4(w){return{type:"array",description:w,items:S("One item in the returned collection.")}}function P(w){return{type:"string",description:w}}function e9(w){return{type:["object","null"],description:w,additionalProperties:!0}}function a9(w){return{type:["string","null"],description:w}}function c(w){return{type:"number",description:w}}function Xw(w){return{type:"boolean",description:w}}function q(w){return S(`The ${w} record returned by Sequenzy.`)}function h(w){return $4(`List of ${w} records returned by Sequenzy.`)}var w4="`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`.",vz="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.",m1=S(`The sequence record returned by Sequenzy. ${vz}`),BP=$4(`List of sequence records returned by Sequenzy. ${vz}`),b4={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:Xw("Whether new subscribers can enter the sequence right now."),processesExistingEnrollments:Xw("Whether subscribers already inside the sequence keep advancing and receiving steps."),effectiveStatusSummary:P("One plain-language sentence describing the run state, safe to show a user verbatim.")},Sz={...m1,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.")}},OP={appUrls:S("Dashboard URLs for relevant Sequenzy resources."),url:P("Primary dashboard URL for this result."),settingsUrl:P("Company settings URL when available.")},MP={success:LP,message:Cz,note:FP,warnings:{type:"array",description:"Non-fatal cautions about content, permissions, or follow-up actions.",items:P("One warning.")},items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:S("One returned item.")},value:S("Fallback object wrapper used only when a tool returns a non-object value.")},KP={get_account:{account:q("account"),companies:h("company"),apiKeyPermissions:S("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:P("Company ID selected by the authenticated API key, when available."),selectedCompanyId:P("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:P("Selected company ID."),companyName:P("Selected company name.")},get_app_urls:{dashboard:P("Company dashboard URL."),settings:P("Company settings URL."),campaign:P("Campaign editor URL."),landingPage:P("Landing page editor URL."),sequence:P("Sequence editor URL."),email:P("Email editor URL."),transactionalEmail:P("Transactional email URL."),emailSend:P("Sent email detail URL."),domain:P("Sending domain settings URL."),urls:S("All generated URLs keyed by resource type.")},create_company:{company:q("company"),autoSelected:Xw("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:q("company")},get_company:{company:q("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:S("One sync rule.")},isDefault:Xw("Whether the company uses the inherited SaaS/ecommerce platform preset.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:S("One sync rule.")},isDefault:Xw("Whether the company now uses the inherited SaaS/ecommerce platform preset.")},get_shopify_automation_settings:{browseAbandonment:S("Effective browse-abandonment settings (defaults applied)."),cartAbandonment:S("Effective cart-abandonment settings (defaults applied)."),priceDrop:S("Effective price-drop settings (defaults applied)."),shopDomain:P("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:S("Effective browse-abandonment settings after the update."),cartAbandonment:S("Effective cart-abandonment settings after the update."),priceDrop:S("Effective price-drop settings after the update."),shopDomain:P("Connected Shopify store domain.")},create_api_key:{apiKey:S("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:P("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")},revoke_api_key:{apiKey:q("revoked non-secret API key metadata")},delete_api_key:{apiKey:q("deleted non-secret API key metadata")},list_websites:{websites:h("sender website")},list_integrations:{integrations:h("connected integration, including provider, provider account ID, active and sync status, last sync time, last sync error, and allowlisted non-secret details. Credentials are never included")},list_sender_profiles:{senderProfiles:h("sender (From) profile, including the sending domain behind it, its verification status, and whether the address can currently send"),replyProfiles:h("reply-to profile"),defaultSenderProfileId:a9("Company default sender profile ID. Null when no default is set."),defaultReplyProfileId:a9("Company default reply-to profile ID. Null when no default is set.")},get_tracking_settings:{tracking:S("Open, click, and unsubscribe tracking flags, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours."),autoUtm:S("Automatic UTM tagging state and its configured parameters."),trackingDomain:e9("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:S("Inbound reply tracking configuration.")},update_tracking_settings:{message:Cz,tracking:S("Open, click, and unsubscribe tracking flags, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours, after the update."),autoUtm:S("Automatic UTM tagging state and its configured parameters, after the update."),trackingDomain:e9("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:S("Inbound reply tracking configuration. Unchanged by this tool; set it with update_company.")},add_website:{website:q("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},add_sending_domain:{website:q("Sending domain with the SPF, DKIM, MAIL FROM, and inbound DNS records required for setup.")},check_website:{website:q("sender website"),ready:Xw("Whether the sender website is ready."),status:P("Current processing or verification status.")},verify_sending_domain:{website:q("Sending domain with current aggregate, SPF, DKIM, and MAIL FROM verification details."),verified:Xw("Whether the sending domain passed the fresh verification check."),message:P("Verification result summary.")},get_integration_guide:{guide:q("integration guide"),code:P("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:S("One setup step.")}},add_subscriber:{subscriber:q("subscriber")},create_subscriber_import:{import:q("subscriber import")},get_subscriber_import:{import:q("subscriber import")},update_subscriber:{subscriber:q("subscriber")},remove_subscriber:{subscriber:q("subscriber"),hardDeleted:Xw("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:q("subscriber")},list_subscriber_notes:{notes:h("subscriber note")},add_subscriber_note:{note:q("subscriber note")},delete_subscriber_note:{id:P("Deleted subscriber note ID."),deleted:Xw("Whether the subscriber note was deleted.")},trigger_subscriber_event:{subscriber:q("subscriber"),event:q("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:P("One failed side effect.")}},trigger_subscriber_events:{subscriber:q("subscriber"),events:h("recorded event")},bulk_add_subscriber_tags:{tags:{type:"array",description:"Normalized tag names applied to every matched subscriber.",items:P("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:S("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:Xw("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:P("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:S("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:S("Pagination metadata."),returned:c("Number of subscribers returned."),truncated:Xw("Whether the result was truncated by the requested limit.")},list_products:{products:h("product"),pagination:S("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:P("Deleted product ID.")},attach_product_file:{product:q("product"),delivery:q("digital delivery file")},remove_product_file:{product:q("product")},upload_image_asset:{asset:q("hosted image asset"),imageBlock:S("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:q("product sync job"),jobId:P("Queued product sync job ID.")},list_tags:{tags:h("tag")},create_tag:{tag:q("tag")},update_tag:{tag:q("tag")},delete_tag:{tagId:P("Deleted tag ID.")},list_lists:{lists:h("list")},create_list:{list:q("list")},update_list:{list:q("list")},delete_list:{listId:P("Deleted list ID.")},add_subscribers_to_list:{list:q("list"),added:c("Number of subscribers added to the list."),skipped:c("Number of subscribers skipped.")},remove_subscribers_from_list:{list:q("list"),removed:c("Number of subscribers removed from the list."),skipped:c("Number of subscribers skipped.")},list_segments:{segments:h("segment")},create_segment:{segment:q("segment")},update_segment:{segment:q("segment")},delete_segment:{segmentId:P("Deleted segment ID.")},get_segment_count:{count:c("Number of subscribers matching the segment."),segmentId:P("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:h("audience sync")},list_ad_accounts:{adAccounts:h("ad account")},create_audience_sync:{audienceSync:q("audience sync")},update_audience_sync:{audienceSync:q("audience sync")},delete_audience_sync:{audienceSyncId:P("Deleted audience sync ID.")},sync_audience_now:{audienceSync:q("audience sync"),job:q("audience sync job"),jobId:P("Queued audience sync job ID.")},list_templates:{templates:h("email template")},get_template:{template:q("email template")},create_template:{template:q("email template")},update_template:{template:q("email template")},set_template_localization:{templateId:P("Localized template ID."),localization:q("template localization")},sync_template_localizations:{templateId:P("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:P("One queued locale code.")},queuedVariantCount:c("Number of localized variants queued for translation.")},delete_template:{templateId:P("Deleted template ID.")},list_ab_tests:{abTests:h("A/B test")},get_ab_test:{abTest:q("A/B test")},get_ab_test_stats:{abTest:q("A/B test"),stats:q("A/B test statistics")},restart_ab_test:{abTest:q("A/B test")},update_ab_test_variant:{abTest:q("A/B test"),variant:q("A/B test variant")},update_ab_test:{abTest:q("A/B test")},create_ab_test:{abTest:q("A/B test")},add_ab_test_variant:{abTest:q("A/B test"),variant:q("A/B test variant")},delete_ab_test_variant:{abTest:q("A/B test"),variantId:P("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:P("Deleted A/B test ID.")},list_campaigns:{campaigns:h("campaign"),pagination:S("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:q("campaign")},get_campaign_audience:{campaignId:P("Campaign the audience was resolved for."),campaignName:P("Campaign name."),status:P("Campaign status."),audience:S("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:e9("Raw stored targeting exactly as persisted on the campaign. Null when targeting has never been set.")},get_email_send:{emailSend:q("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:q("email send pagination"),retentionDays:c("Number of days sent-email rows remain queryable in this collection.")},get_recipient_suppression:{suppression:q("recipient suppression status")},remove_recipient_suppression:{removed:Xw("Whether stale bounce suppression was removed."),removedLocalBounce:Xw("Whether the platform-local bounce block was removed."),removedSesRegions:{type:"array",description:"AWS SES regions where a bounce suppression was removed.",items:P("One AWS SES region.")},remainingSuppression:q("recipient suppression status after cleanup")},create_campaign:{campaign:q("campaign")},update_campaign:{campaign:q("campaign")},schedule_campaign:{campaign:q("campaign"),scheduledAt:P("Scheduled send timestamp.")},unschedule_campaign:{campaign:q("draft campaign")},send_test_email:{emailSendId:P("Durable test email delivery ID."),recipientEmail:P("Test email recipient.")},send_test_sms:{smsSendId:P("Created test SMS send ID."),toPhone:P("Normalized E.164 destination phone.")},cancel_campaign:{campaign:q("campaign")},pause_campaign:{campaign:q("campaign")},resume_campaign:{campaign:q("campaign")},delete_campaign:{campaignId:P("Deleted campaign ID.")},duplicate_campaign:{campaign:q("duplicated campaign")},resend_campaign_to_non_openers:{campaign:q("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:q("saved form"),embed:S("Public action URL plus JavaScript, native form, and fetch snippets.")},get_form_embed:{form:q("saved form"),embed:S("Public action URL plus JavaScript, native form, and fetch snippets.")},list_landing_pages:{landingPages:h("landing page")},get_landing_page:{landingPage:q("landing page")},create_landing_page:{landingPage:q("landing page")},update_landing_page:{landingPage:q("landing page")},duplicate_landing_page:{landingPage:q("landing page")},delete_landing_page:{landingPageId:P("Deleted landing page ID.")},publish_landing_page:{landingPage:q("landing page")},unpublish_landing_page:{landingPage:q("landing page")},connect_landing_page_domain:{landingPage:q("landing page"),domain:P("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:q("landing page"),domain:P("Landing page domain.")},list_sequences:{sequences:BP,pagination:S("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:m1},list_sequence_enrollments:{sequenceId:P("Sequence ID these enrollments belong to."),sequenceName:P("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:P("Enrollment token ID. Stable identifier for this one run through the sequence."),sequenceId:P("Sequence ID."),subscriberId:P("Subscriber ID."),email:P("Subscriber email address. Falls back to the address captured at enrollment when the subscriber record no longer exists."),firstName:P("Subscriber first name, or null when unset."),lastName:P("Subscriber last name, or null when unset."),subscriberStatus:P("Subscriber status (active, unsubscribed, bounced), or null when the subscriber record no longer exists."),status:P("Enrollment status: active, waiting, completed, failed, or cancelled."),currentNodeId:P("Sequence node this enrollment is currently sitting on."),currentNodeType:P("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:P("Current sequence node label or email subject when available."),currentNodeMissing:Xw("Whether the current node no longer exists in the sequence graph."),enrollmentKey:P("Key that distinguishes concurrent enrollments of the same subscriber in this sequence."),enrollmentStartedAt:P("ISO 8601 timestamp when this enrollment entered the sequence."),waitUntil:P("ISO 8601 timestamp this enrollment is scheduled to resume, or null when nothing is scheduled."),lastUpdatedAt:P("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.")},required:["enrollmentId","sequenceId","subscriberId","status","currentNodeId","currentNodeMissing","enrollmentStartedAt"]}},pagination:S("Pagination metadata.")},send_sequence_test_email:{sequenceId:P("Sequence ID."),nodeId:P("Tested sequence email-step node ID."),results:$4("Per-recipient test-send results containing recipientEmail, durable emailSendId, and legacy jobId.")},create_sequence:{sequence:m1,eventTrackingCode:P("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:S("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:P("One required event name.")}},update_sequence:{sequence:Sz},update_sequence_node:{sequence:q("sequence")},update_sequence_nodes:{sequence:q("sequence")},edit_sequence_graph:{sequence:Sz},insert_sequence_step:{sequence:q("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for a linear inserted step, including any delay or wait-for-event node.",items:P("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:P("Inserted email template ID.")},insertedEmailCount:c("Number of email steps inserted."),addedBranchNodeId:P("New logic_branch node ID when the inserted step is a branch."),addedBranchPathNodeIds:S("Created path node IDs keyed by branch ID, plus else. Directly wired paths have empty arrays.")},enable_sequence:{sequenceId:P("Sequence ID."),status:P("Stored lifecycle status after the change."),enrollmentPaused:Xw("Whether new sequence enrollments are paused."),...b4},disable_sequence:{sequenceId:P("Sequence ID."),status:P("Stored lifecycle status after the change."),enrollmentPaused:Xw("Whether new sequence enrollments are paused."),...b4},duplicate_sequence:{sequence:m1,nodes:h("sequence node"),edges:h("sequence edge")},archive_sequence:{sequence:m1},unarchive_sequence:{sequence:m1},list_sequence_goals:{goals:h("sequence goal")},create_sequence_goal:{goal:q("sequence goal")},update_sequence_goal:{goal:q("sequence goal")},delete_sequence_goal:{goalId:P("Deleted sequence goal ID.")},get_sequence_inbound_webhook:{webhook:q("sequence inbound webhook")},configure_sequence_inbound_webhook:{webhook:q("sequence inbound webhook")},rotate_sequence_inbound_webhook_secret:{webhook:q("sequence inbound webhook")},pause_sequence_enrollments:{sequenceId:P("Sequence ID."),enrollmentPaused:Xw("Whether new sequence enrollments are paused."),...b4},resume_sequence_enrollments:{sequenceId:P("Sequence ID."),enrollmentPaused:Xw("Whether new sequence enrollments are paused."),...b4},enroll_subscribers_in_sequence:{sequence:q("sequence"),enrollments:h("sequence enrollment"),enrolled:c("Number of subscribers enrolled."),skipped:c("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequenceId:P("Sequence ID."),dryRun:Xw("Whether this call only reported matches instead of cancelling them."),target:S("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:Xw("Whether more enrollments matched than the returned sample.")},delete_sequence:{sequenceId:P("Deleted sequence ID.")},list_transactional_emails:{transactional:h("transactional email with subject, all-time delivery metrics, and dashboard URL")},get_transactional_email:{transactional:q("transactional email")},create_transactional_email:{transactional:q("transactional email")},update_transactional_email:{transactional:q("transactional email")},send_email:{emailSendId:P("Durable email delivery ID."),emailType:{type:"string",enum:["marketing","transactional"],description:"Delivery policy accepted for the queued email."},transactional:q("transactional email")},get_stats:{stats:S(`Account-wide delivery funnel for the requested window. ${w4}`),emailType:P("Applied structural email type filter when one was requested."),commerceForecast:q("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:q("campaign"),stats:S(`Delivery funnel for this campaign. ${w4}`),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:S("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:S("One poll or NPS results summary.")},recommendations:S("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:q("transactional email"),stats:S(`Delivery funnel for this transactional email. ${w4}`),complaints:q("complaint count and rate for the selected transactional email"),clickedLinks:h("clicked link with click count and percentage share"),bounceBreakdown:q("permanent, transient, and undetermined bounce counts plus subtype details"),engagementBreakdown:q("human and machine open and click counts")},get_sequence_stats:{sequence:m1,stats:S(`Delivery funnel across every email step in this sequence. ${w4}`),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:P("Current sequence node ID."),currentNodeType:P("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:P("Current sequence node label or email subject when available."),currentNodeMissing:Xw("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:S("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:S("Pagination metadata.")},list_sequence_events:{events:h("sequence email event"),pagination:S("Pagination metadata.")},get_subscriber_activity:{activity:h("subscriber activity event"),subscribers:h("subscriber"),pagination:S("Pagination metadata.")},list_team_members:{members:h("team member"),invitations:h("team invitation")},invite_team_member:{invitation:q("team invitation")},cancel_team_invitation:{invitationId:P("Cancelled invitation ID.")},list_conversations:{conversations:h("inbox conversation"),pagination:S("Pagination metadata.")},get_conversation:{conversation:q("inbox conversation"),messages:h("conversation message")},reply_to_conversation:{conversation:q("inbox conversation"),message:q("conversation message")},update_conversation_status:{conversation:q("inbox conversation")},mark_conversation_read:{conversation:q("inbox conversation")},list_webhooks:{webhooks:h("outbound webhook")},create_webhook:{webhook:q("outbound webhook")},update_webhook:{webhook:q("outbound webhook")},delete_webhook:{webhookId:P("Deleted outbound webhook ID.")},test_webhook:{webhook:q("outbound webhook"),delivery:q("test webhook delivery")},list_webhook_deliveries:{deliveries:h("webhook delivery")},replay_webhook_delivery:{delivery:q("webhook delivery"),job:q("webhook replay job")},generate_email:{email:q("generated email"),html:P("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:S("One generated email block.")},subject:P("Generated subject line."),previewText:P("Generated inbox preview text.")},generate_sequence:{sequence:q("persisted AI-generated sequence draft"),deprecated:Xw("Always true for this deprecated alias."),deprecationMessage:P("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:P("One generated subject line.")},variants:h("generated subject line variant")},generate_sms:{prompt:P("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:S("One generated SMS message.")}},get_sms_settings:{sms:S("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix, numbers, readyToSend (paid plan or credits plus an active number).")},submit_feedback:{},render_email:{html:P("Email-safe HTML document, rendered exactly as it would be sent."),subject:P("Subject line with merge tags resolved."),previewText:a9("Inbox preview text with merge tags resolved, or null when unset."),locale:P("Localization locale the render resolved to."),personalized:Xw("Whether a real contact was supplied. False means a sample contact was used, so contact-specific merge tags resolve to empty values."),trackingApplied:Xw("Whether auto-UTM link decoration was applied."),unresolvedMergeTags:$4(`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:S("Which entity was rendered: type, id, and variantId.")}};function qP(w){let b=KP[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:{...MP,...b,...t9.has(w)?OP:{}},additionalProperties:!0}}function _z(w){return{...w,outputSchema:qP(w.name)}}function kz(w){if(v(w))return w;if(Array.isArray(w))return{items:w};return{value:w}}var xz=[{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. ${Jw}`},blocks:{type:"array",description:`${A1}${c1} 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:`${A1}${c1}`,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:`${A1}${c1}`,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 hz=[{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
|
|
|
33
|
-
The response shows 'companies' (all available) and 'selectedCompanyId' (currently active). All subsequent operations will use the selected company unless you pass a companyId override.`,inputSchema:{type:"object",properties:{}}},{name:"select_company",description:"Select which company to operate on (for user-scoped API keys with access to multiple companies). Use get_account to see available companies. After selecting, all subsequent operations will use this company unless you pass a companyId override.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"The company ID to select (from get_account's companies list)"}},required:["companyId"]}},{name:"get_app_urls",description:"Generate Sequenzy dashboard URLs for known resource IDs. Use this when the user asks where to review or edit a generated sequence, campaign, template, or company settings. If companyId is omitted, the selected/current company is used when available.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If omitted, uses the selected/current company when available."},campaignId:{type:"string",description:"Campaign ID for the campaign editor URL."},landingPageId:{type:"string",description:"Landing page ID for the landing page editor URL."},sequenceId:{type:"string",description:"Sequence ID for the sequence editor URL."},templateId:{type:"string",description:"Template/email ID for the email editor URL."},emailId:{type:"string",description:"Email ID for the email editor URL."},transactionalId:{type:"string",description:"Transactional email ID."},emailSendId:{type:"string",description:"Email send ID for the sent email detail URL."},domainId:{type:"string",description:"Sending domain ID."},status:{type:"string",description:"Status for campaign/sequence list URLs."},settingsTab:{type:"string",description:"Settings tab slug, e.g. integrations, domain, tracking, api-keys, team."}}}},{name:"create_company",description:"Create a new company/brand. This will parse your website to extract brand information. The tool polls every 20 seconds until the company is fully processed (typically 30-60 seconds).",inputSchema:{type:"object",properties:{name:{type:"string",description:"Company name (optional, will be extracted from domain if not provided)"},domain:{type:"string",description:"The company's website domain (e.g., example.com)"}},required:["domain"]}},{name:"get_company",description:"Get company details, processing status, product info, brand colors, AI writing context, reply-tracking settings, and effective email localization settings",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"The company ID to check"}},required:["companyId"]}},{name:"update_company",description:"Edit company product info, brand context, the default email theme, reply-tracking settings, and account-wide sending identity defaults. fromEmail must use a verified sending domain; replyTo may be any valid mailbox. Missing sender/reply profiles are created automatically. Send fromName/replyToName on their own to rename the display name of the existing default profile without changing its address, or pair them with senderProfileId/replyProfileId (from list_sender_profiles) to rename a specific profile. Provide at least one editable field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If omitted, uses the selected/current company when available."},name:{type:"string",description:"Company display name."},description:{type:"string",description:"Short product or company summary for AI writing context."},logoUrl:{type:"string",description:"Public logo URL."},founderName:{type:"string",description:"Founder or sender name for personal email signatures."},primaryColor:{type:"string",description:"Primary brand color as a 6-digit hex value, e.g. #f97316."},brandColors:{type:"object",description:"Stored brand color object. Prefer primaryColor for the main color.",additionalProperties:!0},valueProps:{type:"array",description:"Value propositions, usually objects with title and description.",items:{type:"object",additionalProperties:!0}},testimonials:{type:"array",description:"Testimonials, usually objects with quote/text and author.",items:{type:"object",additionalProperties:!0}},toneVoice:{type:"string",description:"Tone of voice guidance for AI-written content."},companyContext:{type:"string",description:"Basic product/company knowledge AI should use when writing emails."},emailLengthPreference:{type:"string",description:"Email length preference: concise, balanced, or detailed."},socialLinks:{type:"object",description:"Social profile URLs keyed by platform.",additionalProperties:{type:"string"}},privacyPolicyUrl:{type:"string",description:"Privacy policy URL."},termsUrl:{type:"string",description:"Terms of service URL."},address:{type:"string",description:"Physical mailing address for email footers."},language:{type:"string",description:"Primary language code, e.g. en, es, de."},pricing:{type:"object",description:"Pricing information used as product context.",additionalProperties:!0},fontFamily:{type:"string",description:"Default email font family stack."},emailTheme:{type:["object","null"],description:"Default email theme applied to campaigns, sequences, and transactional email. Partial update: omitted fields keep their current value (or the preset default). Pass null to reset to the platform default theme. Numeric values are clamped to supported ranges.",properties:{presetId:{type:"string",description:"Theme preset to base the theme on: default, soft, editorial, or bold."},colors:{type:"object",description:"6-digit hex colors.",properties:{primary:{type:"string"},background:{type:"string"},surface:{type:"string"},text:{type:"string"},mutedText:{type:"string"},heading:{type:"string"},border:{type:"string"},link:{type:"string"}},additionalProperties:!1},typography:{type:"object",description:"Numeric type settings.",properties:{baseFontSize:{type:"number"},leadFontSize:{type:"number"},baseLineHeight:{type:"number"},heading1Size:{type:"number"},heading2Size:{type:"number"},heading3Size:{type:"number"},buttonFontSize:{type:"number"}},additionalProperties:!1},layout:{type:"object",description:"Numeric layout settings.",properties:{contentWidth:{type:"number"},containerPaddingX:{type:"number"},containerPaddingY:{type:"number"},blockSpacing:{type:"number"},baseRadius:{type:"number"},sectionPadding:{type:"number"},buttonPaddingX:{type:"number"},buttonPaddingY:{type:"number"},borderedBlockPadding:{type:"number"}},additionalProperties:!1}},additionalProperties:!1},emailDirection:{type:"string",description:"Default email text direction: ltr or rtl."},senderProfileId:{type:"string",description:"Make this existing sender profile the account-wide default, and the one fromName renames. Get IDs from list_sender_profiles. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"Set the account-wide default From address. Its domain must already be configured and verified."},fromName:{type:"string",description:"Display name of the default From profile. Sent alone it renames the current default profile; with senderProfileId it renames that profile; with fromEmail it names the profile for that address. If the address already has several display names, pass senderProfileId to say which one to rename."},replyProfileId:{type:"string",description:"Make this existing reply profile the account-wide default, and the one replyToName renames. Get IDs from list_sender_profiles. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Set the account-wide default Reply-To address. Creates a reply profile when needed."},replyToName:{type:"string",description:"Display name of the default Reply-To profile. Sent alone it renames the current default profile; with replyProfileId it renames that profile; with replyTo it names the profile for that address."},replyTrackingEnabled:{type:"boolean",description:"Enable or disable inbound reply capture for this company."},replyTrackingDomainMode:{type:"string",description:"Reply-tracking domain mode: sequenzy for the managed domain or custom for a configured custom domain."},forwardReplies:{type:"boolean",description:"Enable or disable forwarding captured replies to the configured mailbox."}}}},{name:"get_shopify_automation_settings",description:"Get the connected Shopify store's automation settings: browse abandonment (emails shoppers who viewed a product but didn't buy), cart abandonment (fires ecommerce.cart_abandoned with the full cart after the cart sits inactive), and price drop alerts (emails recent viewers when a product's price falls). Returns the effective values with platform defaults applied.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"update_shopify_automation_settings",description:"Update the connected Shopify store's browse-abandonment, cart-abandonment, and/or price-drop automation settings. Partial update: omitted sections are untouched, omitted fields within a section keep their current value, and passing null for a section resets it to the platform defaults (browse abandonment: on, 2h delay, 24h cooldown; cart abandonment: on, 1h inactivity, 24h cooldown; price drop: on, 5% minimum drop, 30-day viewer lookback, 7-day cooldown).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},browseAbandonment:{type:["object","null"],description:"Browse abandonment settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},delayHours:{type:"number",exclusiveMinimum:0,maximum:168,description:"Hours to wait after a product view before checking for abandonment (default 2)."},cooldownHours:{type:"number",exclusiveMinimum:0,maximum:720,description:"Minimum hours between browse-abandoned events per subscriber (default 24)."}},additionalProperties:!1},cartAbandonment:{type:["object","null"],description:"Cart abandonment settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},delayHours:{type:"number",exclusiveMinimum:0,maximum:168,description:"Hours of cart inactivity before the cart counts as abandoned (default 1)."},cooldownHours:{type:"number",exclusiveMinimum:0,maximum:720,description:"Minimum hours between cart-abandoned events per subscriber (default 24)."}},additionalProperties:!1},priceDrop:{type:["object","null"],description:"Price drop settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},minPercent:{type:"number",exclusiveMinimum:0,maximum:95,description:"Minimum price decrease percent to alert on (default 5)."},lookbackDays:{type:"number",exclusiveMinimum:0,maximum:90,description:"How many days back product viewers qualify as the audience (default 30)."},cooldownDays:{type:"number",exclusiveMinimum:0,maximum:90,description:"Minimum days between price-drop events per subscriber and product (default 7)."}},additionalProperties:!1}},additionalProperties:!1}},{name:"get_sync_rules",description:"Get the company's sync rules: the automatic tag changes applied when events fire (e.g. order placed -> add a tag). New companies start with no rules. Returns the effective rules plus isDefault, which is true when the company has explicitly opted into the inherited SaaS/ecommerce platform preset.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"update_sync_rules",description:"Replace the company's sync rules. Pass the FULL rule set (fetch with get_sync_rules first and edit it - this is not a partial update), [] to disable rules, or null to opt into the inherited SaaS/ecommerce platform preset. Each rule: { triggerEvent, actions: { addTags, removeTags }, conditions? }. Conditions support requiresTags, requiresNotTags, and purchasedProduct ({ tags?, collectionIds?, productTypes?, vendors? }) which matches products on commerce events - e.g. tag buyers of products carrying a given product tag.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncRules:{type:["array","null"],description:"Full replacement rule set. Use [] to disable sync rules, or null to opt into the inherited SaaS/ecommerce platform preset.",items:{type:"object",properties:{triggerEvent:{type:"string",description:"Event name that triggers the rule, e.g. ecommerce.order_placed or saas.purchase."},actions:{type:"object",properties:{addTags:{type:"array",items:{type:"string"}},removeTags:{type:"array",items:{type:"string"}}},required:["addTags","removeTags"],additionalProperties:!1},conditions:{type:"object",properties:{requiresTags:{type:"array",items:{type:"string"},description:"Rule only applies if the subscriber has ALL of these tags."},requiresNotTags:{type:"array",items:{type:"string"},description:"Rule only applies if the subscriber has NONE of these tags."},purchasedProduct:{type:"object",description:"For commerce events with product context: rule only applies when a product on the event matches every specified selector.",properties:{tags:{type:"array",items:{type:"string"}},collectionIds:{type:"array",items:{type:"string"}},productTypes:{type:"array",items:{type:"string"}},vendors:{type:"array",items:{type:"string"}}},additionalProperties:!1}},additionalProperties:!1}},required:["triggerEvent","actions"],additionalProperties:!1}}},required:["syncRules"],additionalProperties:!1}},{name:"create_api_key",description:"Create a new API key for a company. Use this when setting up Sequenzy integration in a project. The returned key should be saved to the project's .env file as SEQUENZY_API_KEY. The key can only be retrieved once at creation time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the key for"},name:{type:"string",description:"Optional name for the API key (e.g., 'Production', 'Development')"},preset:{type:"string",description:"Optional permission preset. Supported values: full_access, read_only, agent_safe, ai_drafting, data_ingest_safe, data_ingest_automations, transactional_sender, marketing_sender. Defaults to full_access when both preset and scopes are omitted; prefer agent_safe when creating a key for an AI agent."},scopes:{type:"array",description:"Optional explicit API key permission scopes. If provided, this overrides preset and must include at least one supported scope.",items:{type:"string"}}},required:["companyId"]}},{name:"list_api_keys",description:"List company-scoped API keys as non-secret metadata. Returns IDs, names, prefixes, permissions, usage timestamps, and whether each key is the active credential. It never returns a plain key or stored key hash. Use this before revoke_api_key or delete_api_key to identify the exact unused key.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID whose API keys should be listed"}},required:["companyId"]}},{name:"revoke_api_key",description:"Permanently revoke a company-scoped API key by ID. The response contains non-secret metadata only. Call list_api_keys first and compare the ID, name, prefix, and isCurrent flag because revoking a key cannot be undone and may invalidate the active credential.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID that owns the API key"},apiKeyId:{type:"string",description:"Exact API key ID returned by list_api_keys"}},required:["companyId","apiKeyId"]}},{name:"delete_api_key",description:"Compatibility alias for revoke_api_key. Permanently delete a company-scoped API key by ID and return non-secret metadata only. Call list_api_keys first to verify the exact target.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID that owns the API key"},apiKeyId:{type:"string",description:"Exact API key ID returned by list_api_keys"}},required:["companyId","apiKeyId"]}},{name:"list_websites",description:"List configured sending domains with stored aggregate, SPF, DKIM, and MAIL FROM verification status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},label:{type:"string",description:"Optional label name filter. Only templates assigned this label are returned."}}}},{name:"add_sending_domain",description:"Add and configure a sending domain. Returns the SPF, DKIM, MAIL FROM, and inbound DNS records to publish before calling verify_sending_domain.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Sending domain to add (for example, mail.example.com)."}},required:["domain"]}},{name:"add_website",description:"Compatibility alias for add_sending_domain. Adds a sending domain and returns the DNS records required for setup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"The domain to add (e.g., example.com)"}},required:["domain"]}},{name:"check_website",description:"Read a sending domain's stored aggregate status plus SPF, DKIM, MAIL FROM records and diagnostics. Use verify_sending_domain to run a fresh DNS check.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"The domain to check"}},required:["domain"]}},{name:"verify_sending_domain",description:"Run a fresh DNS/provider verification for a configured sending domain and return current aggregate, SPF, DKIM, and MAIL FROM status with diagnostics.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Configured sending domain to verify."}},required:["domain"]}},{name:"list_integrations",description:"List connected integrations (Stripe, Shopify, Supabase, Clerk, WooCommerce, ad platforms, and so on) with connection status, sync state, last sync time, and last sync error. Read-only: credentials, access tokens, and webhook secrets are never returned. Use this to audit which external systems feed this account and whether their syncs are healthy.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},includeInactive:{type:"boolean",description:"Include disconnected/inactive integrations. Defaults to false (active only)."}}}},{name:"list_sender_profiles",description:"List sender (From) profiles and reply-to profiles for the company, including which are the account defaults and whether each sender address sits on a verified sending domain. Use this to audit sending identity before scheduling, or to pick a valid senderProfileId/replyProfileId for create_campaign or update_campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_tracking_settings",description:"Get the company's email tracking configuration: open/click/unsubscribe tracking flags, default attribution window, automatic UTM tagging, the dedicated click-tracking domain and its verification status, and inbound reply-tracking settings. Use this to audit measurement readiness and to explain why opens or clicks may not be recorded.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_integration_guide",description:`Get code examples for integrating Sequenzy into your project.
|
|
33
|
+
The response shows 'companies' (all available) and 'selectedCompanyId' (currently active). All subsequent operations will use the selected company unless you pass a companyId override.`,inputSchema:{type:"object",properties:{}}},{name:"select_company",description:"Select which company to operate on (for user-scoped API keys with access to multiple companies). Use get_account to see available companies. After selecting, all subsequent operations will use this company unless you pass a companyId override.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"The company ID to select (from get_account's companies list)"}},required:["companyId"]}},{name:"get_app_urls",description:"Generate Sequenzy dashboard URLs for known resource IDs. Use this when the user asks where to review or edit a generated sequence, campaign, template, or company settings. If companyId is omitted, the selected/current company is used when available.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If omitted, uses the selected/current company when available."},campaignId:{type:"string",description:"Campaign ID for the campaign editor URL."},landingPageId:{type:"string",description:"Landing page ID for the landing page editor URL."},sequenceId:{type:"string",description:"Sequence ID for the sequence editor URL."},templateId:{type:"string",description:"Template/email ID for the email editor URL."},emailId:{type:"string",description:"Email ID for the email editor URL."},transactionalId:{type:"string",description:"Transactional email ID."},emailSendId:{type:"string",description:"Email send ID for the sent email detail URL."},domainId:{type:"string",description:"Sending domain ID."},status:{type:"string",description:"Status for campaign/sequence list URLs."},settingsTab:{type:"string",description:"Settings tab slug, e.g. integrations, domain, tracking, api-keys, team."}}}},{name:"create_company",description:"Create a new company/brand. This will parse your website to extract brand information. The tool polls every 20 seconds until the company is fully processed (typically 30-60 seconds).",inputSchema:{type:"object",properties:{name:{type:"string",description:"Company name (optional, will be extracted from domain if not provided)"},domain:{type:"string",description:"The company's website domain (e.g., example.com)"}},required:["domain"]}},{name:"get_company",description:"Get company details, processing status, product info, brand colors, AI writing context, reply-tracking settings, and effective email localization settings",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"The company ID to check"}},required:["companyId"]}},{name:"update_company",description:"Edit company product info, brand context, the default email theme, reply-tracking settings, and account-wide sending identity defaults. fromEmail must use a verified sending domain; replyTo may be any valid mailbox. Missing sender/reply profiles are created automatically. Send fromName/replyToName on their own to rename the display name of the existing default profile without changing its address, or pair them with senderProfileId/replyProfileId (from list_sender_profiles) to rename a specific profile. Provide at least one editable field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If omitted, uses the selected/current company when available."},name:{type:"string",description:"Company display name."},description:{type:"string",description:"Short product or company summary for AI writing context."},logoUrl:{type:"string",description:"Public logo URL."},founderName:{type:"string",description:"Founder or sender name for personal email signatures."},primaryColor:{type:"string",description:"Primary brand color as a 6-digit hex value, e.g. #f97316."},brandColors:{type:"object",description:"Stored brand color object. Prefer primaryColor for the main color.",additionalProperties:!0},valueProps:{type:"array",description:"Value propositions, usually objects with title and description.",items:{type:"object",additionalProperties:!0}},testimonials:{type:"array",description:"Testimonials, usually objects with quote/text and author.",items:{type:"object",additionalProperties:!0}},toneVoice:{type:"string",description:"Tone of voice guidance for AI-written content."},companyContext:{type:"string",description:"Basic product/company knowledge AI should use when writing emails."},emailLengthPreference:{type:"string",description:"Email length preference: concise, balanced, or detailed."},socialLinks:{type:"object",description:"Social profile URLs keyed by platform.",additionalProperties:{type:"string"}},privacyPolicyUrl:{type:"string",description:"Privacy policy URL."},termsUrl:{type:"string",description:"Terms of service URL."},address:{type:"string",description:"Physical mailing address for email footers."},language:{type:"string",description:"Primary language code, e.g. en, es, de."},pricing:{type:"object",description:"Pricing information used as product context.",additionalProperties:!0},fontFamily:{type:"string",description:"Default email font family stack."},emailTheme:{type:["object","null"],description:"Default email theme applied to campaigns, sequences, and transactional email. Partial update: omitted fields keep their current value (or the preset default). Pass null to reset to the platform default theme. Numeric values are clamped to supported ranges.",properties:{presetId:{type:"string",description:"Theme preset to base the theme on: default, soft, editorial, or bold."},colors:{type:"object",description:"6-digit hex colors.",properties:{primary:{type:"string"},background:{type:"string"},surface:{type:"string"},text:{type:"string"},mutedText:{type:"string"},heading:{type:"string"},border:{type:"string"},link:{type:"string"}},additionalProperties:!1},typography:{type:"object",description:"Numeric type settings.",properties:{baseFontSize:{type:"number"},leadFontSize:{type:"number"},baseLineHeight:{type:"number"},heading1Size:{type:"number"},heading2Size:{type:"number"},heading3Size:{type:"number"},buttonFontSize:{type:"number"}},additionalProperties:!1},layout:{type:"object",description:"Numeric layout settings.",properties:{contentWidth:{type:"number"},containerPaddingX:{type:"number"},containerPaddingY:{type:"number"},blockSpacing:{type:"number"},baseRadius:{type:"number"},sectionPadding:{type:"number"},buttonPaddingX:{type:"number"},buttonPaddingY:{type:"number"},borderedBlockPadding:{type:"number"}},additionalProperties:!1}},additionalProperties:!1},emailDirection:{type:"string",description:"Default email text direction: ltr or rtl."},senderProfileId:{type:"string",description:"Make this existing sender profile the account-wide default, and the one fromName renames. Get IDs from list_sender_profiles. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"Set the account-wide default From address. Its domain must already be configured and verified."},fromName:{type:"string",description:"Display name of the default From profile. Sent alone it renames the current default profile; with senderProfileId it renames that profile; with fromEmail it names the profile for that address. If the address already has several display names, pass senderProfileId to say which one to rename."},replyProfileId:{type:"string",description:"Make this existing reply profile the account-wide default, and the one replyToName renames. Get IDs from list_sender_profiles. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Set the account-wide default Reply-To address. Creates a reply profile when needed."},replyToName:{type:"string",description:"Display name of the default Reply-To profile. Sent alone it renames the current default profile; with replyProfileId it renames that profile; with replyTo it names the profile for that address."},replyTrackingEnabled:{type:"boolean",description:"Enable or disable inbound reply capture for this company."},replyTrackingDomainMode:{type:"string",description:"Reply-tracking domain mode: sequenzy for the managed domain or custom for a configured custom domain."},forwardReplies:{type:"boolean",description:"Enable or disable forwarding captured replies to the configured mailbox."}}}},{name:"get_shopify_automation_settings",description:"Get the connected Shopify store's automation settings: browse abandonment (emails shoppers who viewed a product but didn't buy), cart abandonment (fires ecommerce.cart_abandoned with the full cart after the cart sits inactive), and price drop alerts (emails recent viewers when a product's price falls). Returns the effective values with platform defaults applied.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"update_shopify_automation_settings",description:"Update the connected Shopify store's browse-abandonment, cart-abandonment, and/or price-drop automation settings. Partial update: omitted sections are untouched, omitted fields within a section keep their current value, and passing null for a section resets it to the platform defaults (browse abandonment: on, 2h delay, 24h cooldown; cart abandonment: on, 1h inactivity, 24h cooldown; price drop: on, 5% minimum drop, 30-day viewer lookback, 7-day cooldown).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},browseAbandonment:{type:["object","null"],description:"Browse abandonment settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},delayHours:{type:"number",exclusiveMinimum:0,maximum:168,description:"Hours to wait after a product view before checking for abandonment (default 2)."},cooldownHours:{type:"number",exclusiveMinimum:0,maximum:720,description:"Minimum hours between browse-abandoned events per subscriber (default 24)."}},additionalProperties:!1},cartAbandonment:{type:["object","null"],description:"Cart abandonment settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},delayHours:{type:"number",exclusiveMinimum:0,maximum:168,description:"Hours of cart inactivity before the cart counts as abandoned (default 1)."},cooldownHours:{type:"number",exclusiveMinimum:0,maximum:720,description:"Minimum hours between cart-abandoned events per subscriber (default 24)."}},additionalProperties:!1},priceDrop:{type:["object","null"],description:"Price drop settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},minPercent:{type:"number",exclusiveMinimum:0,maximum:95,description:"Minimum price decrease percent to alert on (default 5)."},lookbackDays:{type:"number",exclusiveMinimum:0,maximum:90,description:"How many days back product viewers qualify as the audience (default 30)."},cooldownDays:{type:"number",exclusiveMinimum:0,maximum:90,description:"Minimum days between price-drop events per subscriber and product (default 7)."}},additionalProperties:!1}},additionalProperties:!1}},{name:"get_sync_rules",description:"Get the company's sync rules: the automatic tag changes applied when events fire (e.g. order placed -> add a tag). New companies start with no rules. Returns the effective rules plus isDefault, which is true when the company has explicitly opted into the inherited SaaS/ecommerce platform preset.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"update_sync_rules",description:"Replace the company's sync rules. Pass the FULL rule set (fetch with get_sync_rules first and edit it - this is not a partial update), [] to disable rules, or null to opt into the inherited SaaS/ecommerce platform preset. Each rule: { triggerEvent, actions: { addTags, removeTags }, conditions? }. Conditions support requiresTags, requiresNotTags, and purchasedProduct ({ tags?, collectionIds?, productTypes?, vendors? }) which matches products on commerce events - e.g. tag buyers of products carrying a given product tag.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncRules:{type:["array","null"],description:"Full replacement rule set. Use [] to disable sync rules, or null to opt into the inherited SaaS/ecommerce platform preset.",items:{type:"object",properties:{triggerEvent:{type:"string",description:"Event name that triggers the rule, e.g. ecommerce.order_placed or saas.purchase."},actions:{type:"object",properties:{addTags:{type:"array",items:{type:"string"}},removeTags:{type:"array",items:{type:"string"}}},required:["addTags","removeTags"],additionalProperties:!1},conditions:{type:"object",properties:{requiresTags:{type:"array",items:{type:"string"},description:"Rule only applies if the subscriber has ALL of these tags."},requiresNotTags:{type:"array",items:{type:"string"},description:"Rule only applies if the subscriber has NONE of these tags."},purchasedProduct:{type:"object",description:"For commerce events with product context: rule only applies when a product on the event matches every specified selector.",properties:{tags:{type:"array",items:{type:"string"}},collectionIds:{type:"array",items:{type:"string"}},productTypes:{type:"array",items:{type:"string"}},vendors:{type:"array",items:{type:"string"}}},additionalProperties:!1}},additionalProperties:!1}},required:["triggerEvent","actions"],additionalProperties:!1}}},required:["syncRules"],additionalProperties:!1}},{name:"create_api_key",description:"Create a new API key for a company. Use this when setting up Sequenzy integration in a project. The returned key should be saved to the project's .env file as SEQUENZY_API_KEY. The key can only be retrieved once at creation time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the key for"},name:{type:"string",description:"Optional name for the API key (e.g., 'Production', 'Development')"},preset:{type:"string",description:"Optional permission preset. Supported values: full_access, read_only, agent_safe, ai_drafting, data_ingest_safe, data_ingest_automations, transactional_sender, marketing_sender. Defaults to full_access when both preset and scopes are omitted; prefer agent_safe when creating a key for an AI agent."},scopes:{type:"array",description:"Optional explicit API key permission scopes. If provided, this overrides preset and must include at least one supported scope.",items:{type:"string"}}},required:["companyId"]}},{name:"list_api_keys",description:"List company-scoped API keys as non-secret metadata. Returns IDs, names, prefixes, permissions, usage timestamps, and whether each key is the active credential. It never returns a plain key or stored key hash. Use this before revoke_api_key or delete_api_key to identify the exact unused key.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID whose API keys should be listed"}},required:["companyId"]}},{name:"revoke_api_key",description:"Permanently revoke a company-scoped API key by ID. The response contains non-secret metadata only. Call list_api_keys first and compare the ID, name, prefix, and isCurrent flag because revoking a key cannot be undone and may invalidate the active credential.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID that owns the API key"},apiKeyId:{type:"string",description:"Exact API key ID returned by list_api_keys"}},required:["companyId","apiKeyId"]}},{name:"delete_api_key",description:"Compatibility alias for revoke_api_key. Permanently delete a company-scoped API key by ID and return non-secret metadata only. Call list_api_keys first to verify the exact target.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID that owns the API key"},apiKeyId:{type:"string",description:"Exact API key ID returned by list_api_keys"}},required:["companyId","apiKeyId"]}},{name:"list_websites",description:"List configured sending domains with stored aggregate, SPF, DKIM, and MAIL FROM verification status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},label:{type:"string",description:"Optional label name filter. Only templates assigned this label are returned."}}}},{name:"add_sending_domain",description:"Add and configure a sending domain. Returns the SPF, DKIM, MAIL FROM, and inbound DNS records to publish before calling verify_sending_domain.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Sending domain to add (for example, mail.example.com)."}},required:["domain"]}},{name:"add_website",description:"Compatibility alias for add_sending_domain. Adds a sending domain and returns the DNS records required for setup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"The domain to add (e.g., example.com)"}},required:["domain"]}},{name:"check_website",description:"Read a sending domain's stored aggregate status plus SPF, DKIM, MAIL FROM records and diagnostics. Use verify_sending_domain to run a fresh DNS check.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"The domain to check"}},required:["domain"]}},{name:"verify_sending_domain",description:"Run a fresh DNS/provider verification for a configured sending domain and return current aggregate, SPF, DKIM, and MAIL FROM status with diagnostics.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Configured sending domain to verify."}},required:["domain"]}},{name:"list_integrations",description:"List connected integrations (Stripe, Shopify, Supabase, Clerk, WooCommerce, ad platforms, and so on) with connection status, sync state, last sync time, and last sync error. Read-only: credentials, access tokens, and webhook secrets are never returned. Use this to audit which external systems feed this account and whether their syncs are healthy.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},includeInactive:{type:"boolean",description:"Include disconnected/inactive integrations. Defaults to false (active only)."}}}},{name:"list_sender_profiles",description:"List sender (From) profiles and reply-to profiles for the company, including which are the account defaults and whether each sender address sits on a verified sending domain. Use this to audit sending identity before scheduling, or to pick a valid senderProfileId/replyProfileId for create_campaign or update_campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"get_tracking_settings",description:"Get the company's email tracking configuration: open/click/unsubscribe tracking flags, default attribution window, automatic UTM tagging, the dedicated click-tracking domain and its verification status, and inbound reply-tracking settings. Use this to audit measurement readiness and to explain why opens or clicks may not be recorded.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"update_tracking_settings",description:"Update the company's account-wide email tracking defaults: open, click, and unsubscribe tracking, opt-in strict bot filtering, the default attribution window, and automatic UTM tagging. Applies to every campaign, sequence, and transactional email sent afterwards; already-sent emails keep the links they were rendered with. Provide at least one field. Reply tracking (inbound email, reply domain mode, reply forwarding) is on update_company, and the dedicated click-tracking domain is configured in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},openTrackingEnabled:{type:"boolean",description:"Whether to embed the open-tracking pixel. Turning this off also stops open rates from being recorded."},clickTrackingEnabled:{type:"boolean",description:"Whether to rewrite links through the click-tracking redirect. Turning this off stops click rates and click-based automation triggers."},strictBotFilteringEnabled:{type:"boolean",description:"Opt in to aggressive bot detection: strict user-agent patterns, datacenter-IP classification, and cross-send IP sweeps. Off by default because it can also discard real engagement, lowering reported open and click rates. Enable it when the audience sits behind email-security appliances that inflate engagement."},unsubscribeTrackingEnabled:{type:"boolean",description:"Whether unsubscribe links are attributed to the email that produced them. Unsubscribe links keep working either way."},defaultAttributionWindowHours:{type:"number",description:"Default revenue attribution window in hours (1-720). Used by goals and revenue reporting when no per-goal window is set."},autoUtmEnabled:{type:"boolean",description:"Whether to append UTM parameters to outgoing links automatically. Enabling this with no stored parameters seeds the platform defaults."},autoUtmSettings:{type:["object","null"],description:"UTM templates to merge over the stored ones: source, medium, campaign, content, term. Values support placeholders such as {{email.subject}} and {{link.text}}. Pass null for a single parameter to stop emitting it, or null for the whole object to reset every parameter to the defaults.",properties:{source:{type:["string","null"]},medium:{type:["string","null"]},campaign:{type:["string","null"]},content:{type:["string","null"]},term:{type:["string","null"]}}}}}},{name:"get_integration_guide",description:`Get code examples for integrating Sequenzy into your project.
|
|
34
34
|
|
|
35
35
|
CRITICAL - FOR SAAS/SUBSCRIPTION APPS:
|
|
36
36
|
If the app uses Stripe, Polar, Paddle, Dodo, or Creem - tell the user to connect it in Sequenzy dashboard (Settings → Integrations).
|
|
@@ -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 Nz=[{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 Ez=[{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: ${Ub}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${Ub}. 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: ${Ub}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${Ub}. 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 Tz=[{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 Rz=[{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. `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. ${Jw}`},blocks:{type:"array",description:U1,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."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},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."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},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. ${Jw}`},blocks:{type:"array",description:U1,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."},replyToName:{type:"string",description:"Display name for a newly created reply profile. Requires replyTo."},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."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},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 Sz=[{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 Cz=[{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."}},required:["name","listIds"],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 vz=[{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 _z=[{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 kz=[{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:h7},content:{type:"object",description:zb,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:zb,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:zb,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:zb,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 xz=[{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.",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."}}}},{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.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}}];var yz=[{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. Pass exactly one target: campaignId, sequenceId plus nodeId, or templateId. Without a subscriber the email renders for a sample contact and merge tags resolve to empty values. 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 a$={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."}},hz={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."}},uz=[{name:"list_sequence_goals",description:"List persisted conversion goals attached to one sequence in the dashboard.",inputSchema:{type:"object",properties:a$,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:{...a$,...hz},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:{...a$,goalId:{type:"string",description:"Sequence goal ID."},...hz},required:["sequenceId","goalId"],additionalProperties:!1}},{name:"delete_sequence_goal",description:"Delete one persisted sequence conversion goal.",inputSchema:{type:"object",properties:{...a$,goalId:{type:"string",description:"Sequence goal ID."}},required:["sequenceId","goalId"],additionalProperties:!1}}];var i9={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence with an inbound_webhook trigger."}},fz=[{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:i9,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:{...i9,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:i9,required:["sequenceId"],additionalProperties:!1}}];var cz=[{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, 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."},senderProfileId:{type:"string",description:"Existing sender profile ID. Mutually exclusive with fromEmail."},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."},replyProfileId:{type:"string",description:"Existing reply profile ID. Mutually exclusive with replyTo."},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. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value."},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:c$,stopCondition:{type:"object",description:"Optional explicit auto-stop condition. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'does_not_have_tag', value: 'trial' } when a tag is removed, { type: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { type: 'removed_from_list', value: 'list_123' } when they leave a list, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop.",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."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. 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:D0,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:X0,items:{type:"object"}},html:{type:"string",description:`HTML content for email steps. Use this for imported provider HTML. ${Jw}`},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."},...Ab,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:J0,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:Y0,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.",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 mz=[{name:"update_sequence",description:"Update an existing sequence. 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."},senderProfileId:{type:"string",description:"Set an existing sender profile. Mutually exclusive with fromEmail."},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."},replyProfileId:{type:"string",description:"Set an existing reply profile. Mutually exclusive with replyTo."},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. '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:c$,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. 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: 'removed_from_list', value: 'list_123' } to stop when they leave a list, or { type: 'none', value: null } to clear it.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"]},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition."},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:_9},elseSteps:{type:"array",description:"Optional new steps inside the else fallback path.",items:Lb},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:Lb}},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. ${Jw}`},htmlContent:{type:"string",description:`Alias for html for imported provider markup. ${Jw}`},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:A1,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."},...Ab}}},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. ${Jw}`},htmlContent:{type:"string",description:`Alias for html. ${Jw}`},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:A1,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."},...Ab}}},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:D0},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:m$.properties.nodeId,changes:I9,expectedUpdatedAt:m$.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:m$},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, 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:X0,items:{type:"object"}},html:{type:"string",description:`HTML content for an imported provider step. Provide either html or blocks, not both. ${Jw}`},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."},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:{...D0,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 URL called when a subscriber reaches this step."},method:{type:"string",enum:["POST","GET"],description:"webhook only: HTTP method. Defaults to POST."},headers:{type:"object",description:"webhook only: optional string-valued request headers. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},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:J0,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:Y0,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:_9},elseSteps:{type:"array",description:"logic_branch only: optional new steps for the else path.",items:Lb},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 DZ={type:"object",properties:{email:{type:"string",description:"Subscriber email address"},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}},required:["email"],additionalProperties:!1},gz=[{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"},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},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."}},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:DZ,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, status, attributes, or tags. 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."},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}},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,items:{type:"object",properties:{name:{type:"string",description:"Event name"},properties:{type:"object",description:"Event properties",additionalProperties:!0}},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. 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. 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 lz={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."}},iz=[{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:lz,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:lz,required:["email"],additionalProperties:!1}}];var nz=[{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:[...H0],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:[...H0],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:E9,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:{...T9,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:E9,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...T9,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 pz=[{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 oz=[{name:"list_templates",description:"List all email templates, including per-locale localization sync status",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. ${Jw}`},blocks:{type:"array",description:U1,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. ${Jw}`},blocks:{type:"array",description:U1,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\`. ${Jw}`},blocks:{type:"array",description:U1,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 dz=[{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\`. ${Jw}`},blocks:{type:"array",description:`${U1} 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\`. ${Jw}`},blocks:{type:"array",description:`${A1} Mutually exclusive with \`html\`.`,items:{type:"object"}}},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."},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 tz=[{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:[...z0]},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:[...z0]},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 rz=[...Iz,...gz,...iz,...xz,...nz,...Tz,...oz,...jz,...Rz,...yz,...Cz,...kz,...vz,...cz,...mz,...uz,...fz,...dz,...Ez,...pz,..._z,...tz,...Nz,...Sz];async function sz(w,b){let $;switch(w){case"get_account":{let W=await U("GET","/api/v1/account"),Q=B1();$={...W,selectedCompanyId:Q??W.currentCompanyId};break}case"select_company":{let W=b.companyId,Q=await U("GET","/api/v1/account"),G=Q.companies?.find((X)=>X.id===W);if(!G)throw Error(`Company not found. Available companies: ${Q.companies?.map((X)=>`${X.name} (${X.id})`).join(", ")??"none"}`);Ob(W),$={success:!0,message:`Switched to company: ${G.name}`,companyId:G.id,companyName:G.name};break}case"get_app_urls":{let W=await t$(b);$={...D1({companyId:W,campaignId:F(b,"campaignId"),landingPageId:F(b,"landingPageId"),sequenceId:F(b,"sequenceId"),emailId:F(b,"emailId")??F(b,"templateId"),transactionalId:F(b,"transactionalId"),emailSendId:F(b,"emailSendId"),domainId:F(b,"domainId"),status:F(b,"status"),settingsTab:F(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 U("POST","/api/v1/companies",{name:b.name,domain:b.domain});if(!W.success)throw Error("Failed to create company");let Q=W.company.id,G=6,X=0,Y=W.company.status;while(Y==="processing"&&X<G){await new Promise((z)=>setTimeout(z,20000)),X++;let H=await U("GET",`/api/v1/companies/${Q}`);if(H.success)Y=H.company.status}Ob(Q);let J=await U("GET",`/api/v1/companies/${Q}`);$={success:!0,company:J.company,message:Y==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${J.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let W=b.companyId;$=await U("GET",`/api/v1/companies/${W}`);break}case"update_company":{let W=await r$("update_company",b),Q=n7(b);$=await U("PATCH",`/api/v1/companies/${W}`,Q);break}case"get_sync_rules":{let W=b.companyId;$=await U("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 U("PUT","/api/v1/sync-rules",{syncRules:b.syncRules},W);break}case"get_shopify_automation_settings":{let W=b.companyId;$=await U("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 U("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 U("POST","/api/v1/api-keys",Q,W);break}case"list_api_keys":{let W=await r$(w,b);$=await U("GET","/api/v1/api-keys",void 0,W);break}case"revoke_api_key":case"delete_api_key":{let W=await r$(w,b);$=await U("DELETE",`/api/v1/api-keys/${encodeURIComponent(String(b.apiKeyId))}`,void 0,W);break}case"list_websites":{let W=b.companyId;$=await U("GET","/api/v1/websites",void 0,W);break}case"add_sending_domain":case"add_website":{let W=b.companyId;$=await U("POST","/api/v1/websites",{domain:b.domain},W);break}case"check_website":{let W=b.companyId;$=await U("GET",`/api/v1/websites/${encodeURIComponent(String(b.domain))}`,void 0,W);break}case"verify_sending_domain":{let W=b.companyId;$=await U("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 G=Q.toString();$=await U("GET",`/api/v1/integrations${G?`?${G}`:""}`,void 0,W);break}case"list_sender_profiles":{let W=b.companyId;$=await U("GET","/api/v1/sender-profiles",void 0,W);break}case"get_tracking_settings":{let W=b.companyId;$=await U("GET","/api/v1/tracking-settings",void 0,W);break}case"get_integration_guide":$=await U("POST","/api/v1/integration-guide",b);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function ez(w,b){let $;switch(w){case"generate_email":{let W=b.companyId;$=await U("POST","/api/v1/generate/email",b,W);break}case"generate_subject_lines":{let W=b.companyId;$=await U("POST","/api/v1/generate/subjects",b,W);break}case"generate_sms":{let W=b.companyId;$=await U("POST","/api/v1/generate/sms",b,W);break}case"get_sms_settings":{let W=b.companyId;$=await U("GET","/api/v1/sms/settings",void 0,W);break}case"send_test_sms":{let W=b.companyId,Q={to:P("send_test_sms",b,"to")};for(let G of["text","imageUrls","blocks"])if(b[G]!==void 0)Q[G]=b[G];$=await U("POST","/api/v1/sms/test",Q,W);break}case"submit_feedback":{let W=b.companyId,Q={message:P("submit_feedback",b,"message"),source:"mcp"};for(let G of["category","context"])if(b[G]!==void 0)Q[G]=b[G];$=await U("POST","/api/v1/feedback",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function az(w,b){let $;switch(w){case"list_transactional_emails":{let W=b.companyId,Q=new URLSearchParams,G=F(b,"search"),X=p("list_transactional_emails",b,"status",["all","active","disabled"]),Y=p("list_transactional_emails",b,"sort",["date","sends","opens","open-rate","clicks","ctr"]),J=p("list_transactional_emails",b,"order",["asc","desc"]);if(G)Q.set("search",G);if(X)Q.set("status",X);if(Y)Q.set("sort",Y);if(J)Q.set("order",J);if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let H=Q.toString();$=await U("GET",`/api/v1/transactional${H?`?${H}`:""}`,void 0,W);break}case"get_transactional_email":{let W=b.companyId;$=await U("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"]),G=Object.keys(b).filter((Y)=>!Q.has(Y));if(G.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((Y)=>`\`${Y}\``).join(", ")}.`);Yz(b);let X=Object.fromEntries(Object.entries(b).filter(([Y])=>Y!=="companyId"));$=await U("POST","/api/v1/transactional",X,W);break}case"update_transactional_email":{let W=b.companyId,Q=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),G=Object.keys(b).filter((Y)=>!Q.has(Y));if(G.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((Y)=>`\`${Y}\``).join(", ")}.`);if(vw("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 X=Object.fromEntries(Object.entries(b).filter(([Y])=>Y!=="companyId"&&Y!=="idOrSlug"));$=await U("PATCH",`/api/v1/transactional/${b.idOrSlug}`,X,W);break}case"send_email":{let W=b.companyId,Q=P("send_email",b,"to"),G=b.templateId===void 0?void 0:P("send_email",b,"templateId"),X=b.subject===void 0?void 0:P("send_email",b,"subject"),Y=b.html===void 0?void 0:P("send_email",b,"html"),J=b.emailType===void 0?void 0:P("send_email",b,"emailType"),H=b.replyTo===void 0?void 0:P("send_email",b,"replyTo");if(J!==void 0&&J!=="marketing"&&J!=="transactional")throw Error("`emailType` must be `marketing` or `transactional` when calling `send_email`.");if(G!==void 0&&(X!==void 0||Y!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(G===void 0&&(X===void 0||Y===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 L of["clickTracking","openTracking"]){let K=A[L];if(K===void 0)continue;if(typeof K!=="boolean")throw Error(`\`trackingSettings.${L}\` must be a boolean when calling \`send_email\`.`);z[L]=K}}let D=Object.fromEntries(Object.entries({to:Q,slug:G,subject:X,body:Y,variables:b.variables,subscriberExternalId:b.subscriberExternalId,emailType:J,replyTo:H,trackingSettings:z}).filter(([,A])=>A!==void 0));$=await U("POST","/api/v1/transactional/send",D,W);break}case"get_stats":{let W=b.companyId,Q=b.period??"7d",G=new URLSearchParams({period:String(Q)}),X=b.emailType===void 0?void 0:P("get_stats",b,"emailType");if(X!==void 0&&!["campaign","transactional","sequence"].includes(X))throw Error("`emailType` must be `campaign`, `transactional`, or `sequence` when calling `get_stats`.");if(X)G.set("emailType",X);if(b.includeMachineEngagement===!0)G.set("includeMachineEngagement","true");$=await U("GET",`/api/v1/metrics?${G.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 G=Q.toString();$=await U("GET",`/api/v1/metrics/campaigns/${b.campaignId}${G?`?${G}`:""}`,void 0,W);break}case"get_transactional_stats":{let W=b.companyId,Q=P("get_transactional_stats",b,"idOrSlug"),G=new URLSearchParams;for(let Y of["period","start","end"])if(typeof b[Y]==="string"&&b[Y].trim())G.set(Y,b[Y].trim());if(b.includeMachineEngagement===!0)G.set("includeMachineEngagement","true");let X=G.toString();$=await U("GET",`/api/v1/metrics/transactional/${encodeURIComponent(Q)}${X?`?${X}`:""}`,void 0,W);break}case"get_sequence_stats":{let W=b.companyId,Q=new URLSearchParams;for(let X of["period","start","end"])if(typeof b[X]==="string"&&b[X].trim())Q.set(X,b[X].trim());if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");let G=Q.toString();$=await U("GET",`/api/v1/metrics/sequences/${b.sequenceId}${G?`?${G}`:""}`,void 0,W);break}case"list_campaign_events":{let W=b.companyId,Q=P("list_campaign_events",b,"campaignId"),X=y9("list_campaign_events",b).toString();$=await U("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(Q)}/events${X?`?${X}`:""}`,void 0,W);break}case"list_sequence_events":{let W=b.companyId,Q=P("list_sequence_events",b,"sequenceId"),X=y9("list_sequence_events",b).toString();$=await U("GET",`/api/v1/metrics/sequences/${encodeURIComponent(Q)}/events${X?`?${X}`:""}`,void 0,W);break}case"get_subscriber_activity":{let W=b.companyId,Q=dw("get_subscriber_activity",b),G=await Fb(Q,W,{includeMachineEngagement:b.includeMachineEngagement===!0});$={success:G.success,email:G.subscriber.email,emailStats:G.subscriber.emailStats??null,activity:G.subscriber.activity??[],sequenceEnrollments:G.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function w5(w,b){let $;switch(w){case"list_tags":{let W=b.companyId;$=await U("GET","/api/v1/tags",void 0,W);break}case"create_tag":{let W=b.companyId,Q=P("create_tag",b,"name"),G=p("create_tag",b,"color",H0);$=await U("POST","/api/v1/tags",{name:Q,...G!==void 0&&{color:G}},W);break}case"update_tag":{let W=b.companyId,Q=P("update_tag",b,"tagId"),G=Bb("update_tag",b,"color",H0);$=await U("PATCH",`/api/v1/tags/${encodeURIComponent(Q)}`,{color:G},W);break}case"delete_tag":{let W=b.companyId,Q=P("delete_tag",b,"tagId");$=await U("DELETE",`/api/v1/tags/${encodeURIComponent(Q)}`,void 0,W);break}case"list_lists":{let W=b.companyId;$=await U("GET","/api/v1/lists",void 0,W);break}case"create_list":{let W=b.companyId;$=await U("POST","/api/v1/lists",b,W);break}case"update_list":{let W=b.companyId,Q=P("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&&F(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 U("PATCH",`/api/v1/lists/${encodeURIComponent(Q)}`,{...b.name!==void 0&&{name:F(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=P("delete_list",b,"listId");$=await U("DELETE",`/api/v1/lists/${encodeURIComponent(Q)}`,void 0,W);break}case"add_subscribers_to_list":{let W=b.companyId,Q=P("add_subscribers_to_list",b,"listId"),G=u9("add_subscribers_to_list",b),X=p("add_subscribers_to_list",b,"duplicateStrategy",["skip","merge","overwrite"])??"skip",Y=p("add_subscribers_to_list",b,"optInMode",["default","confirmed","double_opt_in"])??"default";$=await U("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers`,{emails:G,duplicateStrategy:X,enrollInSequences:b.enrollInSequences===!0,optInMode:Y},W);break}case"remove_subscribers_from_list":{let W=b.companyId,Q=P("remove_subscribers_from_list",b,"listId"),G=u9("remove_subscribers_from_list",b);$=await U("POST",`/api/v1/lists/${encodeURIComponent(Q)}/subscribers/remove`,{emails:G},W);break}case"list_segments":{let W=b.companyId;$=await U("GET","/api/v1/segments",void 0,W);break}case"create_segment":{l7(b);let W=b.companyId;$=await U("POST","/api/v1/segments",{...b,...b.filters!==void 0?{filters:g$(b.filters)}:{},...b.root!==void 0?{root:l$(b.root)}:{}},W);break}case"update_segment":{i7(b);let W=b.companyId,Q=P("update_segment",b,"segmentId"),G=F(b,"name"),X=p("update_segment",b,"filterJoinOperator",["and","or"]);$=await U("PATCH",`/api/v1/segments/${encodeURIComponent(Q)}`,{...G!==void 0&&{name:G},...X!==void 0&&{filterJoinOperator:X},...b.filters!==void 0?{filters:g$(b.filters)}:{},...b.root!==void 0?{root:l$(b.root)}:{}},W);break}case"delete_segment":{let W=b.companyId,Q=P("delete_segment",b,"segmentId");$=await U("DELETE",`/api/v1/segments/${encodeURIComponent(Q)}`,void 0,W);break}case"get_segment_count":{let W=b.companyId;$=await U("GET",`/api/v1/segments/${b.segmentId}/count`,void 0,W);break}case"list_audience_syncs":{let W=b.companyId;$=await U("GET","/api/v1/audience-syncs",void 0,W);break}case"list_ad_accounts":{let W=b.companyId;$=await U("GET","/api/v1/ad-accounts",void 0,W);break}case"create_audience_sync":{let W=b.companyId,Q=F(b,"segmentId"),G=F(b,"predefinedSegmentId");if(Q&&G)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!Q&&!G)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");$=await U("POST","/api/v1/audience-syncs",{segmentId:Q,predefinedSegmentId:G,adAccountId:P("create_audience_sync",b,"adAccountId"),audienceName:P("create_audience_sync",b,"audienceName"),...b.frequency!==void 0?{frequency:b.frequency}:{}},W);break}case"update_audience_sync":{let W=b.companyId,Q=P("update_audience_sync",b,"syncId");$=await U("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=P("delete_audience_sync",b,"syncId");$=await U("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(Q)}`,void 0,W);break}case"sync_audience_now":{let W=b.companyId,Q=P("sync_audience_now",b,"syncId");$=await U("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 b5(w,b){let $;switch(w){case"list_templates":{let W=b.companyId,Q=new URLSearchParams,G=F(b,"label");if(G)Q.set("label",G);$=await U("GET",`/api/v1/templates${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_template":{let W=b.companyId;$=await U("GET",`/api/v1/templates/${b.templateId}`,void 0,W);break}case"create_template":{let W=b.companyId;Qz(b);let Q=Object.fromEntries(Object.entries(b).filter(([G])=>G!=="companyId"));$=await U("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"]),G=Object.keys(b).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);if(vw("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 U("PUT",`/api/v1/templates/${b.templateId}`,b,W);break}case"set_template_localization":{let W=b.companyId,Q=P("set_template_localization",b,"templateId"),G=P("set_template_localization",b,"locale"),X=P("set_template_localization",b,"subject"),Y=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),J=Object.keys(b).filter((z)=>!Y.has(z));if(J.length>0)throw Error(`\`set_template_localization\` received unsupported field${J.length===1?"":"s"}: ${J.map((z)=>`\`${z}\``).join(", ")}.`);vw("set_template_localization",b,{requireContent:!0});let H={subject:X};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 U("PUT",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/${encodeURIComponent(G)}`,H,W);break}case"sync_template_localizations":{let W=b.companyId,Q=P("sync_template_localizations",b,"templateId"),G=new Set(["companyId","templateId","locales"]),X=Object.keys(b).filter((J)=>!G.has(J));if(X.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);let Y;if(b.locales!==void 0){if(!Array.isArray(b.locales)||b.locales.length===0||b.locales.some((J)=>typeof J!=="string"||J.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");Y=b.locales.map((J)=>J.trim())}$=await U("POST",`/api/v1/templates/${encodeURIComponent(Q)}/localizations/sync`,Y===void 0?{}:{locales:Y},W);break}case"delete_template":{let W=b.companyId;$=await U("DELETE",`/api/v1/templates/${b.templateId}`,void 0,W);break}case"list_ab_tests":{let W=b.companyId,Q=new URLSearchParams,G=F(b,"sequenceId");if(G)Q.set("sequenceId",G);$=await U("GET",`/api/v1/ab-tests${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_ab_test":{let W=b.companyId;$=await U("GET",`/api/v1/ab-tests/${b.abTestId}`,void 0,W);break}case"get_ab_test_stats":{let W=b.companyId,Q=new URLSearchParams,G=F(b,"period"),X=F(b,"start"),Y=F(b,"end");if(G)Q.set("period",G);if(X)Q.set("start",X);if(Y)Q.set("end",Y);if(b.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");$=await U("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"]),G=Object.keys(b).filter((H)=>!Q.has(H));if(G.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${G.length===1?"":"s"}: ${G.map((H)=>`\`${H}\``).join(", ")}.`);let X=F(b,"testType");if(X!==void 0&&X!=="subject"&&X!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let Y=b.winnerThreshold===void 0?void 0:Number(b.winnerThreshold);if(Y!==void 0&&(!Number.isInteger(Y)||Y<10||Y>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let J=b.variantCount===void 0?void 0:Number(b.variantCount);if(J!==void 0&&(!Number.isInteger(J)||J<2||J>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");$=await U("POST",`/api/v1/ab-tests/${b.abTestId}/restart`,{sourceVariantId:F(b,"sourceVariantId"),testType:X,winnerThreshold:Y,variantCount:J},W);break}case"update_ab_test_variant":{let W=b.companyId,Q=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks","confirmLiveChange"]),G=Object.keys(b).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`confirmLiveChange\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);if(vw("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 U("PATCH",`/api/v1/ab-tests/${b.abTestId}/variants/${b.variantId}`,b,W);break}case"update_ab_test":{let W=b.companyId,Q=P("update_ab_test",b,"abTestId"),G=new Set(["companyId","abTestId","name","testPercentage","testDurationMinutes","winnerCriteria","testType","winnerThreshold","confirmLiveChange"]),X=Object.keys(b).filter((L)=>!G.has(L));if(X.length>0)throw Error(`\`update_ab_test\` received unsupported field${X.length===1?"":"s"}: ${X.map((L)=>`\`${L}\``).join(", ")}.`);if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test`.");let Y=F(b,"name"),J=qw("update_ab_test",b,"testPercentage",5,50),H=qw("update_ab_test",b,"testDurationMinutes",15,1440),z=p("update_ab_test",b,"winnerCriteria",["open_rate","click_rate"]),D=p("update_ab_test",b,"testType",["subject","content"]),A=qw("update_ab_test",b,"winnerThreshold",10,1000);if(Y===void 0&&J===void 0&&H===void 0&&z===void 0&&D===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 U("PATCH",`/api/v1/ab-tests/${encodeURIComponent(Q)}`,{...Y!==void 0&&{name:Y},...J!==void 0&&{testPercentage:J},...H!==void 0&&{testDurationMinutes:H},...z!==void 0&&{winnerCriteria:z},...D!==void 0&&{testType:D},...A!==void 0&&{winnerThreshold:A},...b.confirmLiveChange===!0&&{confirmLiveChange:!0}},W);break}case"create_ab_test":{let W=b.companyId,Q=F(b,"campaignId"),G=F(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(G))throw Error("Provide exactly one of `campaignId` or `automationNodeId` when calling `create_ab_test`.");let X=F(b,"name"),Y=qw("create_ab_test",b,"testPercentage",5,50),J=qw("create_ab_test",b,"testDurationMinutes",15,1440),H=p("create_ab_test",b,"winnerCriteria",["open_rate","click_rate"]),z=p("create_ab_test",b,"testType",["subject","content"]),D=qw("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((L,K)=>{if(!k(L)||typeof L.subject!=="string"||L.subject.trim()==="")throw Error(`\`variants\` item ${K+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(L.blocks!==void 0&&!Array.isArray(L.blocks))throw Error(`\`variants\` item ${K+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}let A=Array.isArray(b.variants)?b.variants:void 0;if(G!==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 U("POST","/api/v1/ab-tests",{...Q!==void 0&&{campaignId:Q},...G!==void 0&&{automationNodeId:G},...b.confirmLiveChange===!0&&{confirmLiveChange:!0},...X!==void 0&&{name:X},...Y!==void 0&&{testPercentage:Y},...J!==void 0&&{testDurationMinutes:J},...H!==void 0&&{winnerCriteria:H},...z!==void 0&&{testType:z},...D!==void 0&&{winnerThreshold:D},...b.variants!==void 0&&{variants:b.variants}},W);break}case"add_ab_test_variant":{let W=b.companyId,Q=P("add_ab_test_variant",b,"abTestId"),G=P("add_ab_test_variant",b,"subject"),X=F(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 U("POST",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants`,{subject:G,...X!==void 0&&{previewText:X},...b.blocks!==void 0&&{blocks:b.blocks},...b.confirmLiveChange===!0&&{confirmLiveChange:!0}},W);break}case"delete_ab_test_variant":{let W=b.companyId,Q=P("delete_ab_test_variant",b,"abTestId"),G=P("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 U("DELETE",`/api/v1/ab-tests/${encodeURIComponent(Q)}/variants/${encodeURIComponent(G)}${b.confirmLiveChange===!0?"?confirmLiveChange=true":""}`,void 0,W);break}case"delete_ab_test":{let W=b.companyId,Q=P("delete_ab_test",b,"abTestId");$=await U("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 G=F(b,"label");if(G)Q.set("label",G);for(let X of["limit","offset"])if(b[X]!==void 0)Q.set(X,String(b[X]));$=await U("GET",`/api/v1/campaigns?${Q}`,void 0,W);break}case"get_campaign":{let W=b.companyId;$=await U("GET",`/api/v1/campaigns/${b.campaignId}`,void 0,W);break}case"get_campaign_audience":{let W=b.companyId;$=await U("GET",`/api/v1/campaigns/${encodeURIComponent(String(b.campaignId))}/audience`,void 0,W);break}case"get_email_send":{let W=b.companyId;$=await U("GET",`/api/v1/email-sends/${encodeURIComponent(String(b.emailSendId))}`,void 0,W);break}case"list_email_sends":{let W=b.companyId,Q=new URLSearchParams,G=["search","subject","recipient","campaignId","transactionalEmailId","automationId"];for(let j of G){let V=F(b,j);if(V)Q.set(j,V)}let X=p("list_email_sends",b,"status",["pending","sent","delivered","opened","clicked","bounced","complained","failed","suppressed"]),Y=p("list_email_sends",b,"emailType",["campaign","transactional","sequence"]),J=p("list_email_sends",b,"bounceType",["Permanent","Transient"]),H=p("list_email_sends",b,"sortField",["recipientEmail","subject","status","eventAt","sentAt","createdAt"]),z=p("list_email_sends",b,"sortOrder",["asc","desc"]),D=qw("list_email_sends",b,"days",1,14),A=qw("list_email_sends",b,"page",1,Number.MAX_SAFE_INTEGER),L=qw("list_email_sends",b,"limit",1,100),K=[["status",X],["emailType",Y],["bounceType",J],["sortField",H],["sortOrder",z],["days",D],["page",A],["limit",L]];for(let[j,V]of K)if(V!==void 0)Q.set(j,String(V));let M=Q.toString();$=await U("GET",`/api/v1/email-sends${M?`?${M}`:""}`,void 0,W);break}case"create_campaign":{let W=b.companyId;if(Wz(b),b.fromEmail!==void 0&&b.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_campaign`, not both.");if(b.replyTo!==void 0&&b.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_campaign`, not both.");if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_campaign`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_campaign`.");let Q=Object.fromEntries(Object.entries(b).filter(([G])=>G!=="companyId"));$=await U("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"]),G=Object.keys(b).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, audience, and label update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);if(vw("update_campaign",b),L1("update_campaign",b),b.replyTo!==void 0&&b.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `update_campaign`, not both.");if(b.fromEmail!==void 0&&b.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `update_campaign`, not both.");if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `update_campaign`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `update_campaign`.");if(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 U("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"]),G=Object.keys(b).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);Gz(b),$=await U("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 U("POST",`/api/v1/campaigns/${b.campaignId}/test`,{to:b.to},W);break}case"cancel_campaign":{let W=b.companyId,Q=P("cancel_campaign",b,"campaignId");$=await U("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/cancel`,void 0,W);break}case"unschedule_campaign":{let W=b.companyId,Q=P("unschedule_campaign",b,"campaignId");$=await U("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/unschedule`,void 0,W);break}case"pause_campaign":{let W=b.companyId,Q=P("pause_campaign",b,"campaignId");$=await U("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/pause`,void 0,W);break}case"resume_campaign":{let W=b.companyId,Q=P("resume_campaign",b,"campaignId"),G=qw("resume_campaign",b,"spreadOverHours",1,72);$=await U("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/resume`,{...G!==void 0&&{spreadOverHours:G}},W);break}case"delete_campaign":{let W=b.companyId,Q=P("delete_campaign",b,"campaignId");$=await U("DELETE",`/api/v1/campaigns/${encodeURIComponent(Q)}`,void 0,W);break}case"duplicate_campaign":{let W=b.companyId,Q=P("duplicate_campaign",b,"campaignId"),G=p("duplicate_campaign",b,"mode",["campaign","ab_test","variant"]),X=F(b,"variantId");if(G==="variant"&&X===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");$=await U("POST",`/api/v1/campaigns/${encodeURIComponent(Q)}/duplicate`,{...G!==void 0&&{mode:G},...X!==void 0&&{variantId:X}},W);break}case"resend_campaign_to_non_openers":{let W=b.companyId,Q=P("resend_campaign_to_non_openers",b,"campaignId");$=await U("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 $5(w,b){let $;switch(w){case"list_forms":{let W=b.companyId;$=await U("GET","/api/v1/forms",void 0,W);break}case"create_form":{let W=b.companyId,Q=P("create_form",b,"name"),G=Array.isArray(b.listIds)?b.listIds.filter((J)=>typeof J==="string").map((J)=>J.trim()).filter(Boolean):[];if(G.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let X=p("create_form",b,"duplicateStrategy",["skip","merge","overwrite"]),Y={name:Q,listIds:G};for(let J of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName"])if(b[J]!==void 0)Y[J]=b[J];if(X!==void 0)Y.duplicateStrategy=X;$=await U("POST","/api/v1/forms",Y,W);break}case"get_form_embed":{let W=b.companyId,Q=P("get_form_embed",b,"formId");$=await U("GET",`/api/v1/forms/embed/${encodeURIComponent(Q)}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function w4(w,b,$,W,Q){let G=w[b];if(G===void 0)return;if(typeof G!=="number"||!Number.isFinite(G)||G<$||G>W||Q&&!Number.isInteger(G))throw Error(`\`${b}\` must be a ${Q?"integer":"number"} between ${$} and ${W} when calling \`upload_image_asset\`.`);return G}async function W5(w,b){if(w!=="upload_image_asset")return{handled:!1,result:void 0};let $=F(b,"filePath"),W=F(b,"imageBase64");if($===void 0===(W===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let Q=F(b,"filename");if(W!==void 0&&Q===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let G=w4(b,"sourceWidth",1,20000,!0),X=w4(b,"sourceHeight",1,20000,!0);if(G===void 0!==(X===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let Y=w4(b,"displayWidthPercent",1,100,!1)??100,J=w4(b,"cropHeight",1,2000,!0),H=F(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&&J===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let z=F(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 D=typeof b.altText==="string"?b.altText.trim():void 0;if(D!==void 0&&D.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let A=await Oz({companyId:F(b,"companyId"),filePath:$,imageBase64:W,filename:Q,contentType:F(b,"contentType"),altText:D,sourceWidth:G,sourceHeight:X}),L={type:"image",src:A.url,alt:A.altText??"",width:Y,widthType:"percent",...J!==void 0&&{height:J,objectFit:H??"cover"},...z!==void 0&&{align:z}};return{handled:!0,result:{success:!0,asset:A,imageBlock:L,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}async function Q5(w,b){let $;switch(w){case"list_landing_pages":{let W=b.companyId;$=await U("GET","/api/v1/landing-pages",void 0,W);break}case"get_landing_page":{let W=b.companyId;$=await U("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"]),G=Object.keys(b).filter((X)=>!Q.has(X));if(G.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${G.length===1?"":"s"}: ${G.map((X)=>`\`${X}\``).join(", ")}.`);$=await U("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=o$("update_landing_page",b,{requireUpdate:!0});$=await U("PUT",`/api/v1/landing-pages/${b.landingPageId}`,Q,W);break}case"publish_landing_page":{let W=b.companyId,Q=o$("publish_landing_page",b,{requireUpdate:!1});$=await U("POST",`/api/v1/landing-pages/${b.landingPageId}/publish`,Q,W);break}case"unpublish_landing_page":{let W=b.companyId,Q=o$("unpublish_landing_page",b,{requireUpdate:!1});$=await U("POST",`/api/v1/landing-pages/${b.landingPageId}/unpublish`,Q,W);break}case"duplicate_landing_page":{let W=b.companyId;$=await U("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 U("DELETE",`/api/v1/landing-pages/${b.landingPageId}`,void 0,W);break}case"connect_landing_page_domain":{let W=b.companyId;$=await U("POST","/api/v1/landing-pages/domain",{domain:b.domain},W);break}case"update_landing_page_domain_settings":{let W=b.companyId,Q=Xz(b);$=await U("PUT","/api/v1/landing-pages/domain",Q,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function G5(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 G=Q.size>0?`?${Q.toString()}`:"";$=await U("GET",`/api/v1/products${G}`,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 U("POST","/api/v1/products",{products:b.products},W);break}case"delete_product":{let W=b.companyId,Q=P("delete_product",b,"productId");$=await U("DELETE",`/api/v1/products/${encodeURIComponent(Q)}`,void 0,W);break}case"attach_product_file":{let W=b.companyId,Q=P("attach_product_file",b,"productId"),G=F(b,"url"),X=F(b,"filePath");if(G===void 0===(X===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let Y;if(X!==void 0){let J=await Uz(X,W);Y={url:J.url,source:"upload",fileName:F(b,"fileName")??J.fileName,fileSizeBytes:J.fileSizeBytes,mimeType:J.mimeType}}else{Y={url:G};let J=F(b,"fileName");if(J)Y.fileName=J}$=await U("PUT",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,Y,W);break}case"remove_product_file":{let W=b.companyId,Q=P("remove_product_file",b,"productId");$=await U("DELETE",`/api/v1/products/${encodeURIComponent(Q)}/delivery`,void 0,W);break}case"sync_products":{let W=b.companyId;$=await U("POST","/api/v1/products/sync",void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function UZ(w){let b=F(w,"campaignId"),$=F(w,"sequenceId"),W=F(w,"templateId"),Q=[b,$,W].filter((G)=>G!==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 G=P("render_email",w,"nodeId");return`/api/v1/sequences/${encodeURIComponent($)}/nodes/${encodeURIComponent(G)}/render`}return`/api/v1/templates/${encodeURIComponent(W)}/render`}var AZ=["subscriberId","subscriber","variables","locale","variantId","tracking"];async function X5(w,b){if(w!=="render_email")return{handled:!1,result:void 0};let $=UZ(b),W={};for(let G of AZ)if(b[G]!==void 0)W[G]=b[G];return{handled:!0,result:await U("POST",$,W,F(b,"companyId"))}}var Y5=80,J5=10;function LZ(w){if(!Array.isArray(w.recipients))throw Error("`recipients` must be an array when calling `send_sequence_test_email`.");if(w.recipients.length>J5)throw Error(`\`recipients\` must include no more than ${J5} 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 FZ(w){let b=w.trim().replace(/\s+/g," ");if(b.length<=Y5)return b;return`${b.slice(0,Y5-3).trimEnd()}...`}async function n9(w,b){let $;switch(w){case"generate_sequence":{let W=P("generate_sequence",b,"goal"),Q=typeof b.name==="string"&&b.name.trim().length>0?b.name.trim():void 0,X=(await n9("create_sequence",{...b,goal:W,name:Q??FZ(W),trigger:"contact_added",durationDays:b.durationDays??14})).result;return{handled:!0,result:typeof X==="object"&&X!==null?{...X,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:X}}case"list_sequences":{let W=b.companyId,Q=new URLSearchParams;for(let X of["status","search","limit","offset"])if(b[X]!==void 0)Q.set(X,String(b[X]));if(Array.isArray(b.labels)&&b.labels.length>0)Q.set("labels",b.labels.join(","));let G=Q.size>0?`?${Q.toString()}`:"";$=await U("GET",`/api/v1/sequences${G}`,void 0,W);break}case"get_sequence":{let W=b.companyId;$=await U("GET",`/api/v1/sequences/${b.sequenceId}`,void 0,W);break}case"list_sequence_enrollments":{let W=b.companyId,Q=P(w,b,"sequenceId"),G=new URLSearchParams;for(let Y of["currentNodeId","status","subscriberId"]){let J=b[Y];if(Array.isArray(J)){if(J.length>0)G.set(Y,J.join(","))}else if(J!==void 0)G.set(Y,String(J))}for(let Y of["email","sort","limit","offset"])if(b[Y]!==void 0)G.set(Y,String(b[Y]));let X=G.size>0?`?${G.toString()}`:"";$=await U("GET",`/api/v1/sequences/${encodeURIComponent(Q)}/enrollments${X}`,void 0,W);break}case"send_sequence_test_email":{let W=b.companyId,Q=P(w,b,"sequenceId"),G=P(w,b,"nodeId"),X=LZ(b);$=await U("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/nodes/${encodeURIComponent(G)}/test`,{recipients:X},W);break}case"create_sequence":{let W=b.companyId;if(L1("create_sequence",b),b.fromEmail!==void 0&&b.senderProfileId!==void 0)throw Error("Provide either `fromEmail` or `senderProfileId` when calling `create_sequence`, not both.");if(b.replyTo!==void 0&&b.replyProfileId!==void 0)throw Error("Provide either `replyTo` or `replyProfileId` when calling `create_sequence`, not both.");if(b.fromName!==void 0&&b.fromEmail===void 0)throw Error("`fromName` requires `fromEmail` when calling `create_sequence`.");if(b.replyToName!==void 0&&b.replyTo===void 0)throw Error("`replyToName` requires `replyTo` when calling `create_sequence`.");let Q=Array.isArray(b.steps),G=b.goal===void 0&&b.steps===void 0,X=await U("POST","/api/v1/sequences",b,W);if(!X.success){$=X;break}let Y=X.sequence.id;if(Q||G){let A=await U("GET",`/api/v1/sequences/${Y}`,void 0,W);if(A.success)$={...X,success:!0,sequence:A.sequence,message:`Sequence "${A.sequence.name}" created ${G?"as a blank draft":"with explicit steps"}. Review it before enabling.${X.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=A;break}let J=7,H=0,z="pending";while(z!=="complete"&&H<J){let A=await U("GET",`/api/v1/sequences/${Y}`,void 0,W);if(A.success)z=A.sequence.enrichmentStatus;if(H++,z!=="complete"&&H<J)await new Promise((L)=>setTimeout(L,20000))}let D=await U("GET",`/api/v1/sequences/${Y}`,void 0,W);if(D.success)$={...X,success:!0,sequence:D.sequence,message:D.sequence.enrichmentStatus==="complete"?`Sequence "${D.sequence.name}" created with ${D.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${X.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${D.sequence.name}" created. Email enrichment is still in progress (${D.sequence.enrichedCount}/${D.sequence.emailCount} emails generated). You can check status with get_sequence.${X.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=D;break}case"update_sequence":{let W=b.companyId,Q=o7(b);$=await U("PUT",`/api/v1/sequences/${b.sequenceId}`,Q,W);break}case"update_sequence_node":{let W=b.companyId,Q=P("update_sequence_node",b,"sequenceId"),G=e7(b);$=await U("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"update_sequence_nodes":{let W=b.companyId,Q=P("update_sequence_nodes",b,"sequenceId"),G=a7(b);$=await U("PUT",`/api/v1/sequences/${Q}`,G,W);break}case"edit_sequence_graph":{let W=b.companyId,Q=wz(b);$=await U("PUT",`/api/v1/sequences/${b.sequenceId}`,Q,W);break}case"insert_sequence_step":{let W=b.companyId,Q=bz(b),G=await U("PUT",`/api/v1/sequences/${b.sequenceId}`,Q,W);if(typeof G==="object"&&G!==null){let X=G,Y=X.sequence;if(typeof Y==="object"&&Y!==null){let J=Y;$={...X,...J.insertedNodeIds!==void 0?{insertedNodeIds:J.insertedNodeIds}:{},...J.insertedEmailIds!==void 0?{insertedEmailIds:J.insertedEmailIds}:{},...J.insertedEmailCount!==void 0?{insertedEmailCount:J.insertedEmailCount}:{},...J.addedBranchNodeId!==void 0?{addedBranchNodeId:J.addedBranchNodeId}:{},...J.addedBranchPathNodeIds!==void 0?{addedBranchPathNodeIds:J.addedBranchPathNodeIds}:{}};break}}$=G;break}case"enable_sequence":{let W=b.companyId;$=await U("POST",`/api/v1/sequences/${b.sequenceId}/enable`,void 0,W);break}case"disable_sequence":{let W=b.companyId;$=await U("POST",`/api/v1/sequences/${b.sequenceId}/disable`,void 0,W);break}case"duplicate_sequence":{let W=b.companyId,Q=P("duplicate_sequence",b,"sequenceId"),G=F(b,"name");$=await U("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/duplicate`,G===void 0?void 0:{name:G},W);break}case"archive_sequence":case"unarchive_sequence":{let W=b.companyId,Q=P(w,b,"sequenceId"),G=w==="archive_sequence"?"archive":"unarchive";$=await U("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/${G}`,void 0,W);break}case"list_sequence_goals":{let W=b.companyId,Q=P(w,b,"sequenceId");$=await U("GET",`/api/v1/sequences/${encodeURIComponent(Q)}/goals`,void 0,W);break}case"create_sequence_goal":case"update_sequence_goal":{let W=b.companyId,Q=P(w,b,"sequenceId");if(w==="create_sequence_goal")P(w,b,"name"),d7(b);else t7(b);let G=w==="update_sequence_goal"?P(w,b,"goalId"):void 0,X={...b};delete X.companyId,delete X.sequenceId,delete X.goalId,$=await U(w==="create_sequence_goal"?"POST":"PATCH",`/api/v1/sequences/${encodeURIComponent(Q)}/goals${G?`/${encodeURIComponent(G)}`:""}`,X,W);break}case"delete_sequence_goal":{let W=b.companyId,Q=P(w,b,"sequenceId"),G=P(w,b,"goalId");$=await U("DELETE",`/api/v1/sequences/${encodeURIComponent(Q)}/goals/${encodeURIComponent(G)}`,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=P(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 G=w==="configure_sequence_inbound_webhook",X=w==="rotate_sequence_inbound_webhook_secret",Y=G?{...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 U(X?"POST":G?"PUT":"GET",`/api/v1/sequences/${encodeURIComponent(Q)}/inbound-webhook${X?"/rotate-secret":""}`,Y,W);break}case"pause_sequence_enrollments":{let W=b.companyId;$=await U("POST",`/api/v1/sequences/${b.sequenceId}/pause-enrollments`,void 0,W);break}case"resume_sequence_enrollments":{let W=b.companyId;$=await U("POST",`/api/v1/sequences/${b.sequenceId}/resume-enrollments`,void 0,W);break}case"enroll_subscribers_in_sequence":{let W=b.companyId,Q=P("enroll_subscribers_in_sequence",b,"sequenceId"),G=Dz(b);$=await U("POST",`/api/v1/sequences/${encodeURIComponent(Q)}/enroll`,G,W);break}case"cancel_sequence_enrollments":{let W=b.companyId,Q=$z(b);$=await U("POST",`/api/v1/sequences/${b.sequenceId}/enrollments/cancel`,Q,W);break}case"delete_sequence":{let W=b.companyId;$=await U("DELETE",`/api/v1/sequences/${b.sequenceId}`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function b4(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((G)=>typeof G==="string").map((G)=>G.trim()).filter((G)=>G.length>0);if(Q.length!==W.length)throw Error(`\`${$}\` must contain only non-empty strings when calling \`${w}\`.`);return Q}function BZ(w,b){let $=b4(w,b,"tags");if($===void 0||$.length===0)throw Error(`\`tags\` must contain at least one tag when calling \`${w}\`.`);let W=b4(w,b,"emails"),Q=b4(w,b,"externalIds"),G=b4(w,b,"subscriberIds");if((W?.length??0)+(Q?.length??0)+(G?.length??0)===0)throw Error(`Provide \`emails\`, \`externalIds\`, or \`subscriberIds\` when calling \`${w}\`.`);return{tags:$,...W?.length?{emails:W}:{},...Q?.length?{externalIds:Q}:{},...G?.length?{subscriberIds:G}:{},...w==="bulk_add_subscriber_tags"&&typeof b.triggerAutomations==="boolean"?{triggerAutomations:b.triggerAutomations}:{}}}async function H5(w,b){let $;switch(w){case"add_subscriber":{let W=b.companyId,Q=dw("add_subscriber",b),G=p("add_subscriber",b,"status",["active","unsubscribed","bounced"]),X=p("add_subscriber",b,"optInMode",["default","confirmed","double_opt_in"]);if($=await U("POST","/api/v1/subscribers",{...Q,...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},...X!==void 0&&{optInMode:X}},W),G!==void 0&&k($)&&k($.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 X=0;X<b.subscribers.length;X+=1){let Y=b.subscribers[X];if(!k(Y)||typeof Y.email!=="string"||Y.email.trim()==="")throw Error(`Subscriber record ${X} must include a non-empty email string.`)}let Q=p("create_subscriber_import",b,"duplicateStrategy",["skip","merge","overwrite"]),G=p("create_subscriber_import",b,"optInMode",["default","confirmed","double_opt_in"]);$=await U("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},...G!==void 0&&{optInMode:G}},W);break}case"get_subscriber_import":{let W=b.companyId,Q=P("get_subscriber_import",b,"importId");$=await U("GET",`/api/v1/subscribers/imports/${encodeURIComponent(Q)}`,void 0,W);break}case"update_subscriber":{let W=b.companyId,Q=dw("update_subscriber",b),G=p("update_subscriber",b,"status",["active","unsubscribed","bounced"]),Y=k(b.attributes)||b.addTags!==void 0||b.removeTags!==void 0?await Fb(Q,W):null,J=Array.isArray(Y?.subscriber.tags)?Y.subscriber.tags.filter((L)=>typeof L==="string"):[],H=Array.isArray(b.addTags)?b.addTags.filter((L)=>typeof L==="string"&&L.trim()!=="").map(k9):[],z=new Set(Array.isArray(b.removeTags)?b.removeTags.filter((L)=>typeof L==="string"&&L.trim()!=="").map(k9):[]),D=J.filter((L)=>!z.has(L));for(let L of H)if(!D.includes(L))D.push(L);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(G!==void 0)A.status=G;if(k(b.attributes))A.customAttributes={...k(Y?.subscriber.customAttributes)?Y.subscriber.customAttributes:{},...b.attributes};if(b.addTags||b.removeTags)A.tags=D;$=await U("PATCH",d$(Q),A,W);break}case"remove_subscriber":{let W=b.companyId,Q=dw("remove_subscriber",b),G=d$(Q);if(b.hardDelete===!0)$=await U("DELETE",G,void 0,W);else $=await U("PATCH",G,{status:"unsubscribed"},W);break}case"get_subscriber":{let W=b.companyId,Q=dw("get_subscriber",b);$=await Fb(Q,W,{includeMachineEngagement:b.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let W=b.companyId,Q=dw("list_subscriber_notes",b);$=await U("GET",x9(Q),void 0,W);break}case"add_subscriber_note":{let W=b.companyId,Q=dw("add_subscriber_note",b),G=typeof b.body==="string"?b.body.trim():void 0;if(!G)throw Error("`body` is required when calling `add_subscriber_note`.");if(G.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");$=await U("POST",x9(Q),{body:G},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 U("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(Q)}`,void 0,W);break}case"trigger_subscriber_event":{let W=b.companyId,Q=dw("trigger_subscriber_event",b),G=P("trigger_subscriber_event",b,"event");if(b.properties!==void 0&&!k(b.properties))throw Error("`properties` must be an object when calling `trigger_subscriber_event`.");$=await U("POST","/api/v1/subscribers/events",{...Q,event:G,...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}},W);break}case"trigger_subscriber_events":{let W=b.companyId,Q=dw("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`.");for(let G=0;G<b.events.length;G+=1){let X=b.events[G];if(!k(X)||typeof X.name!=="string"||X.name.trim()==="")throw Error(`Event ${G} must include a non-empty \`name\` string.`)}$=await U("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=BZ(w,b);$=await U("POST",`/api/v1/subscribers/bulk/tags/${w==="bulk_add_subscriber_tags"?"add":"remove"}`,Q,W);break}case"search_subscribers":{let W=b.companyId;$=await zz(b,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function z5(w,b){if(w!=="get_recipient_suppression"&&w!=="remove_recipient_suppression")return{handled:!1,result:void 0};let $=F(b,"companyId"),W=P(w,b,"email"),Q=F(b,"region"),G=new URLSearchParams;if(Q)G.set("region",Q);let X=`/api/v1/suppressions/${encodeURIComponent(W)}${G.size>0?`?${G}`:""}`;return{handled:!0,result:await U(w==="get_recipient_suppression"?"GET":"DELETE",X,void 0,$)}}async function D5(w,b){let $;switch(w){case"list_team_members":{let W=b.companyId;$=await U("GET","/api/v1/team",void 0,W);break}case"invite_team_member":{let W=b.companyId,Q=P("invite_team_member",b,"email"),G=Bb("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 U("POST","/api/v1/team/invitations",{email:Q,role:G,...b.canManageBilling!==void 0&&{canManageBilling:b.canManageBilling}},W);break}case"cancel_team_invitation":{let W=b.companyId,Q=P("cancel_team_invitation",b,"invitationId");$=await U("DELETE",`/api/v1/team/invitations/${encodeURIComponent(Q)}`,void 0,W);break}case"list_conversations":{let W=b.companyId,Q=new URLSearchParams,G=p("list_conversations",b,"status",["open","closed","all"]);if(G)Q.set("status",G);let X=F(b,"search");if(X)Q.set("search",X);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 Y=qw("list_conversations",b,"limit",1,100);if(Y!==void 0)Q.set("limit",String(Y));$=await U("GET",`/api/v1/conversations${Q.size>0?`?${Q}`:""}`,void 0,W);break}case"get_conversation":{let W=b.companyId,Q=P("get_conversation",b,"conversationId");$=await U("GET",`/api/v1/conversations/${encodeURIComponent(Q)}`,void 0,W);break}case"reply_to_conversation":{let W=b.companyId,Q=P("reply_to_conversation",b,"conversationId"),G=p("reply_to_conversation",b,"type",["outbound","note"])??"outbound",X=F(b,"subject"),Y=F(b,"bodyText"),J=F(b,"bodyHtml");if(G==="outbound"&&Y===void 0&&J===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");$=await U("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/messages`,{type:G,...X!==void 0&&{subject:X},...Y!==void 0&&{bodyText:Y},...J!==void 0&&{bodyHtml:J}},W);break}case"update_conversation_status":{let W=b.companyId,Q=P("update_conversation_status",b,"conversationId"),G=Bb("update_conversation_status",b,"status",["open","closed"]);$=await U("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/status`,{status:G},W);break}case"mark_conversation_read":{let W=b.companyId,Q=P("mark_conversation_read",b,"conversationId");$=await U("POST",`/api/v1/conversations/${encodeURIComponent(Q)}/read`,void 0,W);break}case"list_webhooks":{let W=b.companyId;$=await U("GET","/api/v1/webhooks",void 0,W);break}case"create_webhook":{let W=b.companyId,Q=P("create_webhook",b,"name"),G=P("create_webhook",b,"url"),X=h9("create_webhook",b);$=await U("POST","/api/v1/webhooks",{name:Q,url:G,...X!==void 0&&{events:X}},W);break}case"update_webhook":{let W=b.companyId,Q=P("update_webhook",b,"webhookId"),G=F(b,"name"),X=F(b,"url"),Y=h9("update_webhook",b),J=p("update_webhook",b,"status",["enabled","disabled"]);if(G===void 0&&X===void 0&&Y===void 0&&J===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");$=await U("PATCH",`/api/v1/webhooks/${encodeURIComponent(Q)}`,{...G!==void 0&&{name:G},...X!==void 0&&{url:X},...Y!==void 0&&{events:Y},...J!==void 0&&{status:J}},W);break}case"delete_webhook":{let W=b.companyId,Q=P("delete_webhook",b,"webhookId");$=await U("DELETE",`/api/v1/webhooks/${encodeURIComponent(Q)}`,void 0,W);break}case"test_webhook":{let W=b.companyId,Q=P("test_webhook",b,"webhookId");$=await U("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/test`,void 0,W);break}case"list_webhook_deliveries":{let W=b.companyId,Q=P("list_webhook_deliveries",b,"webhookId"),G=qw("list_webhook_deliveries",b,"limit",1,100),X=new URLSearchParams;if(G!==void 0)X.set("limit",String(G));$=await U("GET",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries${X.size>0?`?${X}`:""}`,void 0,W);break}case"replay_webhook_delivery":{let W=b.companyId,Q=P("replay_webhook_delivery",b,"webhookId"),G=P("replay_webhook_delivery",b,"deliveryId");$=await U("POST",`/api/v1/webhooks/${encodeURIComponent(Q)}/deliveries/${encodeURIComponent(G)}/replay`,void 0,W);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var U5=[sz,H5,z5,G5,w5,b5,X5,$5,Q5,W5,n9,az,D5,ez];var KZ=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 A5(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}function p9(w){if(Array.isArray(w))return w.some(p9);if(!A5(w))return!1;for(let[b,$]of Object.entries(w)){if((b==="html"||b==="htmlContent")&&typeof $==="string"&&$.trim().length>0)return!0;if(p9($))return!0}return!1}function L5(w,b,$){if(!KZ.has(w)||!p9(b)||!A5($))return $;let W=Array.isArray($.warnings)?$.warnings.filter((Q)=>typeof Q==="string"):[];return{...$,warnings:[...new Set([...W,Jw])]}}var F5=rz.map(Zz).map(u7);async function B5(w,b){try{let $,W=!1;for(let G of U5){let X=await G(w,b);if(X.handled){$=X.result,W=!0;break}}if(!W)throw Error(`Unknown tool: ${w}`);let Q=Jz($);if(Q)throw Q;return $=L5(w,b,$),$=await Lz(w,b,$),{structuredContent:Vz($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:F1($)}]}}}async function K5(w,b,$){let W=b.getRequestContext?.(w)??{};try{return await X4(W,$)}finally{await b.onRequestContextUpdated?.(W,w)}}function o9(w={}){let b=new O9({name:"sequenzy",version:v7.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(
|
|
53
|
-
`);if(w===-1)return null;let b=this._buffer.toString("utf8",0,w).replace(/\r$/,"");return this._buffer=this._buffer.subarray(w+1),
|
|
54
|
-
`}class
|
|
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 yz=[{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 uz=[{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: ${Lb}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${Lb}. 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: ${Lb}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${Lb}. 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 fz=[{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 cz=[{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. `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. ${Jw}`},blocks:{type:"array",description:U1,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. ${Jw}`},blocks:{type:"array",description:U1,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 mz=[{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 gz=[{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."}},required:["name","listIds"],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 lz=[{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 iz=[{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 nz=[{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:oH},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 pz=[{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.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}}];var oz=[{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 Q4={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."}},dz={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."}},tz=[{name:"list_sequence_goals",description:"List persisted conversion goals attached to one sequence in the dashboard.",inputSchema:{type:"object",properties:Q4,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:{...Q4,...dz},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:{...Q4,goalId:{type:"string",description:"Sequence goal ID."},...dz},required:["sequenceId","goalId"],additionalProperties:!1}},{name:"delete_sequence_goal",description:"Delete one persisted sequence conversion goal.",inputSchema:{type:"object",properties:{...Q4,goalId:{type:"string",description:"Sequence goal ID."}},required:["sequenceId","goalId"],additionalProperties:!1}}];var wQ={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence with an inbound_webhook trigger."}},rz=[{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:wQ,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:{...wQ,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:wQ,required:["sequenceId"],additionalProperties:!1}}];var sz=[{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:l$,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:A0,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:G0,items:{type:"object"}},html:{type:"string",description:`HTML content for email steps. Use this for imported provider HTML. ${Jw}`},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."},...Fb,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:H0,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:J0,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.${g$}`,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 ez=[{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:l$,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:l9},elseSteps:{type:"array",description:"Optional new steps inside the else fallback path.",items:Bb},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:Bb}},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. ${Jw}`},htmlContent:{type:"string",description:`Alias for html for imported provider markup. ${Jw}`},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:A1,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."},...Fb}}},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. ${Jw}`},htmlContent:{type:"string",description:`Alias for html. ${Jw}`},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:A1,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."},...Fb}}},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:A0},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:i$.properties.nodeId,changes:S9,expectedUpdatedAt:i$.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:i$},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:G0,items:{type:"object"}},html:{type:"string",description:`HTML content for an imported provider step. Provide either html or blocks, not both. ${Jw}`},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:{...A0,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 URL called when a subscriber reaches this step."},method:{type:"string",enum:["POST","GET"],description:"webhook only: HTTP method. Defaults to POST."},headers:{type:"object",description:"webhook only: optional string-valued request headers. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},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:H0,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:J0,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:l9},elseSteps:{type:"array",description:"logic_branch only: optional new steps for the else path.",items:Bb},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 ZP={type:"object",properties:{email:{type:"string",description:"Subscriber email address"},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}},required:["email"],additionalProperties:!1},az=[{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"},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},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."}},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:ZP,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, status, attributes, or tags. 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."},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}},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,items:{type:"object",properties:{name:{type:"string",description:"Event name"},properties:{type:"object",description:"Event properties",additionalProperties:!0}},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. 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. 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 w5={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."}},b5=[{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:w5,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:w5,required:["email"],additionalProperties:!1}}];var $5=[{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:[...z0],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:[...z0],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:v9,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:{..._9,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:v9,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{..._9,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 Q5=[{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 W5=[{name:"list_templates",description:"List all email templates, including per-locale localization sync status",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. ${Jw}`},blocks:{type:"array",description:U1,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. ${Jw}`},blocks:{type:"array",description:U1,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\`. ${Jw}`},blocks:{type:"array",description:U1,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 X5=[{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\`. ${Jw}`},blocks:{type:"array",description:`${U1} 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\`. ${Jw}`},blocks:{type:"array",description:`${A1}${c1} Mutually exclusive with \`html\`.`,items:{type:"object"}}},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 Y5=[{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:[...D0]},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:[...D0]},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 G5=[...hz,...az,...b5,...pz,...$5,...fz,...W5,...xz,...cz,...oz,...gz,...nz,...lz,...sz,...ez,...tz,...rz,...X5,...uz,...Q5,...iz,...Y5,...yz,...mz];async function J5(w,b){let $;switch(w){case"get_account":{let Q=await U("GET","/api/v1/account"),W=B1();$={...Q,selectedCompanyId:W??Q.currentCompanyId};break}case"select_company":{let Q=b.companyId,W=await U("GET","/api/v1/account"),X=W.companies?.find((Y)=>Y.id===Q);if(!X)throw Error(`Company not found. Available companies: ${W.companies?.map((Y)=>`${Y.name} (${Y.id})`).join(", ")??"none"}`);qb(Q),$={success:!0,message:`Switched to company: ${X.name}`,companyId:X.id,companyName:X.name};break}case"get_app_urls":{let Q=await e$(b);$={...D1({companyId:Q,campaignId:F(b,"campaignId"),landingPageId:F(b,"landingPageId"),sequenceId:F(b,"sequenceId"),emailId:F(b,"emailId")??F(b,"templateId"),transactionalId:F(b,"transactionalId"),emailSendId:F(b,"emailSendId"),domainId:F(b,"domainId"),status:F(b,"status"),settingsTab:F(b,"settingsTab")}),...Q===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 Q=await U("POST","/api/v1/companies",{name:b.name,domain:b.domain});if(!Q.success)throw Error("Failed to create company");let W=Q.company.id,X=6,Y=0,G=Q.company.status;while(G==="processing"&&Y<X){await new Promise((z)=>setTimeout(z,20000)),Y++;let H=await U("GET",`/api/v1/companies/${W}`);if(H.success)G=H.company.status}qb(W);let J=await U("GET",`/api/v1/companies/${W}`);$={success:!0,company:J.company,message:G==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${J.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let Q=b.companyId;$=await U("GET",`/api/v1/companies/${Q}`);break}case"update_company":{let Q=await a$("update_company",b),W=bz(b);$=await U("PATCH",`/api/v1/companies/${Q}`,W);break}case"get_sync_rules":{let Q=b.companyId;$=await U("GET","/api/v1/sync-rules",void 0,Q);break}case"update_sync_rules":{let Q=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 U("PUT","/api/v1/sync-rules",{syncRules:b.syncRules},Q);break}case"get_shopify_automation_settings":{let Q=b.companyId;$=await U("GET","/api/v1/shopify/automation-settings",void 0,Q);break}case"update_shopify_automation_settings":{let Q=b.companyId,W={};if(b.browseAbandonment!==void 0)W.browseAbandonment=b.browseAbandonment;if(b.cartAbandonment!==void 0)W.cartAbandonment=b.cartAbandonment;if(b.priceDrop!==void 0)W.priceDrop=b.priceDrop;if(Object.keys(W).length===0)throw Error("Provide `browseAbandonment`, `cartAbandonment`, and/or `priceDrop` when calling `update_shopify_automation_settings`.");$=await U("PUT","/api/v1/shopify/automation-settings",W,Q);break}case"create_api_key":{let Q=b.companyId,W={};if(typeof b.name==="string")W.name=b.name;if(typeof b.preset==="string")W.preset=b.preset;if(Array.isArray(b.scopes))W.scopes=b.scopes;$=await U("POST","/api/v1/api-keys",W,Q);break}case"list_api_keys":{let Q=await a$(w,b);$=await U("GET","/api/v1/api-keys",void 0,Q);break}case"revoke_api_key":case"delete_api_key":{let Q=await a$(w,b);$=await U("DELETE",`/api/v1/api-keys/${encodeURIComponent(String(b.apiKeyId))}`,void 0,Q);break}case"list_websites":{let Q=b.companyId;$=await U("GET","/api/v1/websites",void 0,Q);break}case"add_sending_domain":case"add_website":{let Q=b.companyId;$=await U("POST","/api/v1/websites",{domain:b.domain},Q);break}case"check_website":{let Q=b.companyId;$=await U("GET",`/api/v1/websites/${encodeURIComponent(String(b.domain))}`,void 0,Q);break}case"verify_sending_domain":{let Q=b.companyId;$=await U("POST",`/api/v1/websites/${encodeURIComponent(String(b.domain))}/verify`,void 0,Q);break}case"list_integrations":{let Q=b.companyId,W=new URLSearchParams;if(b.includeInactive===!0)W.set("includeInactive","true");let X=W.toString();$=await U("GET",`/api/v1/integrations${X?`?${X}`:""}`,void 0,Q);break}case"list_sender_profiles":{let Q=b.companyId;$=await U("GET","/api/v1/sender-profiles",void 0,Q);break}case"get_tracking_settings":{let Q=b.companyId;$=await U("GET","/api/v1/tracking-settings",void 0,Q);break}case"update_tracking_settings":{let Q=b.companyId,W=$z(b);$=await U("PATCH","/api/v1/tracking-settings",W,Q);break}case"get_integration_guide":$=await U("POST","/api/v1/integration-guide",b);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function H5(w,b){let $;switch(w){case"generate_email":{let Q=b.companyId;$=await U("POST","/api/v1/generate/email",b,Q);break}case"generate_subject_lines":{let Q=b.companyId;$=await U("POST","/api/v1/generate/subjects",b,Q);break}case"generate_sms":{let Q=b.companyId;$=await U("POST","/api/v1/generate/sms",b,Q);break}case"get_sms_settings":{let Q=b.companyId;$=await U("GET","/api/v1/sms/settings",void 0,Q);break}case"send_test_sms":{let Q=b.companyId,W={to:Z("send_test_sms",b,"to")};for(let X of["text","imageUrls","blocks"])if(b[X]!==void 0)W[X]=b[X];$=await U("POST","/api/v1/sms/test",W,Q);break}case"submit_feedback":{let Q=b.companyId,W={message:Z("submit_feedback",b,"message"),source:"mcp"};for(let X of["category","context"])if(b[X]!==void 0)W[X]=b[X];$=await U("POST","/api/v1/feedback",W,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function z5(w,b){let $;switch(w){case"list_transactional_emails":{let Q=b.companyId,W=new URLSearchParams,X=F(b,"search"),Y=p("list_transactional_emails",b,"status",["all","active","disabled"]),G=p("list_transactional_emails",b,"sort",["date","sends","opens","open-rate","clicks","ctr"]),J=p("list_transactional_emails",b,"order",["asc","desc"]);if(X)W.set("search",X);if(Y)W.set("status",Y);if(G)W.set("sort",G);if(J)W.set("order",J);if(b.includeMachineEngagement===!0)W.set("includeMachineEngagement","true");let H=W.toString();$=await U("GET",`/api/v1/transactional${H?`?${H}`:""}`,void 0,Q);break}case"get_transactional_email":{let Q=b.companyId;$=await U("GET",`/api/v1/transactional/${b.idOrSlug}`,void 0,Q);break}case"create_transactional_email":{let Q=b.companyId,W=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),X=Object.keys(b).filter((G)=>!W.has(G));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((G)=>`\`${G}\``).join(", ")}.`);Mz(b);let Y=Object.fromEntries(Object.entries(b).filter(([G])=>G!=="companyId"));$=await U("POST","/api/v1/transactional",Y,Q);break}case"update_transactional_email":{let Q=b.companyId,W=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),X=Object.keys(b).filter((G)=>!W.has(G));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((G)=>`\`${G}\``).join(", ")}.`);if(vw("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 Y=Object.fromEntries(Object.entries(b).filter(([G])=>G!=="companyId"&&G!=="idOrSlug"));$=await U("PATCH",`/api/v1/transactional/${b.idOrSlug}`,Y,Q);break}case"send_email":{let Q=b.companyId,W=Z("send_email",b,"to"),X=b.templateId===void 0?void 0:Z("send_email",b,"templateId"),Y=b.subject===void 0?void 0:Z("send_email",b,"subject"),G=b.html===void 0?void 0:Z("send_email",b,"html"),J=b.emailType===void 0?void 0:Z("send_email",b,"emailType"),H=b.replyTo===void 0?void 0:Z("send_email",b,"replyTo");if(J!==void 0&&J!=="marketing"&&J!=="transactional")throw Error("`emailType` must be `marketing` or `transactional` when calling `send_email`.");if(X!==void 0&&(Y!==void 0||G!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(X===void 0&&(Y===void 0||G===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 L of["clickTracking","openTracking"]){let O=A[L];if(O===void 0)continue;if(typeof O!=="boolean")throw Error(`\`trackingSettings.${L}\` must be a boolean when calling \`send_email\`.`);z[L]=O}}let D=Object.fromEntries(Object.entries({to:W,slug:X,subject:Y,body:G,variables:b.variables,subscriberExternalId:b.subscriberExternalId,emailType:J,replyTo:H,trackingSettings:z}).filter(([,A])=>A!==void 0));$=await U("POST","/api/v1/transactional/send",D,Q);break}case"get_stats":{let Q=b.companyId,W=b.period??"7d",X=new URLSearchParams({period:String(W)}),Y=b.emailType===void 0?void 0:Z("get_stats",b,"emailType");if(Y!==void 0&&!["campaign","transactional","sequence"].includes(Y))throw Error("`emailType` must be `campaign`, `transactional`, or `sequence` when calling `get_stats`.");if(Y)X.set("emailType",Y);if(b.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");$=await U("GET",`/api/v1/metrics?${X.toString()}`,void 0,Q);break}case"get_campaign_stats":{let Q=b.companyId,W=new URLSearchParams;if(typeof b.period==="string")W.set("period",b.period);if(typeof b.start==="string")W.set("start",b.start);if(typeof b.end==="string")W.set("end",b.end);if(b.includeMachineEngagement===!0)W.set("includeMachineEngagement","true");let X=W.toString();$=await U("GET",`/api/v1/metrics/campaigns/${b.campaignId}${X?`?${X}`:""}`,void 0,Q);break}case"get_transactional_stats":{let Q=b.companyId,W=Z("get_transactional_stats",b,"idOrSlug"),X=new URLSearchParams;for(let G of["period","start","end"])if(typeof b[G]==="string"&&b[G].trim())X.set(G,b[G].trim());if(b.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");let Y=X.toString();$=await U("GET",`/api/v1/metrics/transactional/${encodeURIComponent(W)}${Y?`?${Y}`:""}`,void 0,Q);break}case"get_sequence_stats":{let Q=b.companyId,W=new URLSearchParams;for(let Y of["period","start","end"])if(typeof b[Y]==="string"&&b[Y].trim())W.set(Y,b[Y].trim());if(b.includeMachineEngagement===!0)W.set("includeMachineEngagement","true");let X=W.toString();$=await U("GET",`/api/v1/metrics/sequences/${b.sequenceId}${X?`?${X}`:""}`,void 0,Q);break}case"list_campaign_events":{let Q=b.companyId,W=Z("list_campaign_events",b,"campaignId"),Y=p9("list_campaign_events",b).toString();$=await U("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(W)}/events${Y?`?${Y}`:""}`,void 0,Q);break}case"list_sequence_events":{let Q=b.companyId,W=Z("list_sequence_events",b,"sequenceId"),Y=p9("list_sequence_events",b).toString();$=await U("GET",`/api/v1/metrics/sequences/${encodeURIComponent(W)}/events${Y?`?${Y}`:""}`,void 0,Q);break}case"get_subscriber_activity":{let Q=b.companyId,W=dw("get_subscriber_activity",b),X=await Ob(W,Q,{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 D5(w,b){let $;switch(w){case"list_tags":{let Q=b.companyId;$=await U("GET","/api/v1/tags",void 0,Q);break}case"create_tag":{let Q=b.companyId,W=Z("create_tag",b,"name"),X=p("create_tag",b,"color",z0);$=await U("POST","/api/v1/tags",{name:W,...X!==void 0&&{color:X}},Q);break}case"update_tag":{let Q=b.companyId,W=Z("update_tag",b,"tagId"),X=Mb("update_tag",b,"color",z0);$=await U("PATCH",`/api/v1/tags/${encodeURIComponent(W)}`,{color:X},Q);break}case"delete_tag":{let Q=b.companyId,W=Z("delete_tag",b,"tagId");$=await U("DELETE",`/api/v1/tags/${encodeURIComponent(W)}`,void 0,Q);break}case"list_lists":{let Q=b.companyId;$=await U("GET","/api/v1/lists",void 0,Q);break}case"create_list":{let Q=b.companyId;$=await U("POST","/api/v1/lists",b,Q);break}case"update_list":{let Q=b.companyId,W=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&&F(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 U("PATCH",`/api/v1/lists/${encodeURIComponent(W)}`,{...b.name!==void 0&&{name:F(b,"name")},...b.description!==void 0&&{description:b.description},...b.isPrivate!==void 0&&{isPrivate:b.isPrivate}},Q);break}case"delete_list":{let Q=b.companyId,W=Z("delete_list",b,"listId");$=await U("DELETE",`/api/v1/lists/${encodeURIComponent(W)}`,void 0,Q);break}case"add_subscribers_to_list":{let Q=b.companyId,W=Z("add_subscribers_to_list",b,"listId"),X=d9("add_subscribers_to_list",b),Y=p("add_subscribers_to_list",b,"duplicateStrategy",["skip","merge","overwrite"])??"skip",G=p("add_subscribers_to_list",b,"optInMode",["default","confirmed","double_opt_in"])??"default";$=await U("POST",`/api/v1/lists/${encodeURIComponent(W)}/subscribers`,{emails:X,duplicateStrategy:Y,enrollInSequences:b.enrollInSequences===!0,optInMode:G},Q);break}case"remove_subscribers_from_list":{let Q=b.companyId,W=Z("remove_subscribers_from_list",b,"listId"),X=d9("remove_subscribers_from_list",b);$=await U("POST",`/api/v1/lists/${encodeURIComponent(W)}/subscribers/remove`,{emails:X},Q);break}case"list_segments":{let Q=b.companyId;$=await U("GET","/api/v1/segments",void 0,Q);break}case"create_segment":{aH(b);let Q=b.companyId;$=await U("POST","/api/v1/segments",{...b,...b.filters!==void 0?{filters:n$(b.filters)}:{},...b.root!==void 0?{root:p$(b.root)}:{}},Q);break}case"update_segment":{wz(b);let Q=b.companyId,W=Z("update_segment",b,"segmentId"),X=F(b,"name"),Y=p("update_segment",b,"filterJoinOperator",["and","or"]);$=await U("PATCH",`/api/v1/segments/${encodeURIComponent(W)}`,{...X!==void 0&&{name:X},...Y!==void 0&&{filterJoinOperator:Y},...b.filters!==void 0?{filters:n$(b.filters)}:{},...b.root!==void 0?{root:p$(b.root)}:{}},Q);break}case"delete_segment":{let Q=b.companyId,W=Z("delete_segment",b,"segmentId");$=await U("DELETE",`/api/v1/segments/${encodeURIComponent(W)}`,void 0,Q);break}case"get_segment_count":{let Q=b.companyId;$=await U("GET",`/api/v1/segments/${b.segmentId}/count`,void 0,Q);break}case"list_audience_syncs":{let Q=b.companyId;$=await U("GET","/api/v1/audience-syncs",void 0,Q);break}case"list_ad_accounts":{let Q=b.companyId;$=await U("GET","/api/v1/ad-accounts",void 0,Q);break}case"create_audience_sync":{let Q=b.companyId,W=F(b,"segmentId"),X=F(b,"predefinedSegmentId");if(W&&X)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!W&&!X)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");$=await U("POST","/api/v1/audience-syncs",{segmentId:W,predefinedSegmentId:X,adAccountId:Z("create_audience_sync",b,"adAccountId"),audienceName:Z("create_audience_sync",b,"audienceName"),...b.frequency!==void 0?{frequency:b.frequency}:{}},Q);break}case"update_audience_sync":{let Q=b.companyId,W=Z("update_audience_sync",b,"syncId");$=await U("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(W)}`,{...b.frequency!==void 0?{frequency:b.frequency}:{},...b.isActive!==void 0?{isActive:b.isActive}:{}},Q);break}case"delete_audience_sync":{let Q=b.companyId,W=Z("delete_audience_sync",b,"syncId");$=await U("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(W)}`,void 0,Q);break}case"sync_audience_now":{let Q=b.companyId,W=Z("sync_audience_now",b,"syncId");$=await U("POST",`/api/v1/audience-syncs/${encodeURIComponent(W)}/sync`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function U5(w,b){let $;switch(w){case"list_templates":{let Q=b.companyId,W=new URLSearchParams,X=F(b,"label");if(X)W.set("label",X);$=await U("GET",`/api/v1/templates${W.size>0?`?${W}`:""}`,void 0,Q);break}case"get_template":{let Q=b.companyId;$=await U("GET",`/api/v1/templates/${b.templateId}`,void 0,Q);break}case"create_template":{let Q=b.companyId;Fz(b);let W=Object.fromEntries(Object.entries(b).filter(([X])=>X!=="companyId"));$=await U("POST","/api/v1/templates",W,Q);break}case"update_template":{let Q=b.companyId,W=new Set(["companyId","templateId","name","subject","previewText","html","blocks","labels"]),X=Object.keys(b).filter((Y)=>!W.has(Y));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((Y)=>`\`${Y}\``).join(", ")}.`);if(vw("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 U("PUT",`/api/v1/templates/${b.templateId}`,b,Q);break}case"set_template_localization":{let Q=b.companyId,W=Z("set_template_localization",b,"templateId"),X=Z("set_template_localization",b,"locale"),Y=Z("set_template_localization",b,"subject"),G=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),J=Object.keys(b).filter((z)=>!G.has(z));if(J.length>0)throw Error(`\`set_template_localization\` received unsupported field${J.length===1?"":"s"}: ${J.map((z)=>`\`${z}\``).join(", ")}.`);vw("set_template_localization",b,{requireContent:!0});let H={subject:Y};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 U("PUT",`/api/v1/templates/${encodeURIComponent(W)}/localizations/${encodeURIComponent(X)}`,H,Q);break}case"sync_template_localizations":{let Q=b.companyId,W=Z("sync_template_localizations",b,"templateId"),X=new Set(["companyId","templateId","locales"]),Y=Object.keys(b).filter((J)=>!X.has(J));if(Y.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${Y.length===1?"":"s"}: ${Y.map((J)=>`\`${J}\``).join(", ")}.`);let G;if(b.locales!==void 0){if(!Array.isArray(b.locales)||b.locales.length===0||b.locales.some((J)=>typeof J!=="string"||J.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");G=b.locales.map((J)=>J.trim())}$=await U("POST",`/api/v1/templates/${encodeURIComponent(W)}/localizations/sync`,G===void 0?{}:{locales:G},Q);break}case"delete_template":{let Q=b.companyId;$=await U("DELETE",`/api/v1/templates/${b.templateId}`,void 0,Q);break}case"list_ab_tests":{let Q=b.companyId,W=new URLSearchParams,X=F(b,"sequenceId");if(X)W.set("sequenceId",X);$=await U("GET",`/api/v1/ab-tests${W.size>0?`?${W}`:""}`,void 0,Q);break}case"get_ab_test":{let Q=b.companyId;$=await U("GET",`/api/v1/ab-tests/${b.abTestId}`,void 0,Q);break}case"get_ab_test_stats":{let Q=b.companyId,W=new URLSearchParams,X=F(b,"period"),Y=F(b,"start"),G=F(b,"end");if(X)W.set("period",X);if(Y)W.set("start",Y);if(G)W.set("end",G);if(b.includeMachineEngagement===!0)W.set("includeMachineEngagement","true");$=await U("GET",`/api/v1/ab-tests/${b.abTestId}/stats${W.size>0?`?${W}`:""}`,void 0,Q);break}case"restart_ab_test":{let Q=b.companyId,W=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),X=Object.keys(b).filter((H)=>!W.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 Y=F(b,"testType");if(Y!==void 0&&Y!=="subject"&&Y!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let G=b.winnerThreshold===void 0?void 0:Number(b.winnerThreshold);if(G!==void 0&&(!Number.isInteger(G)||G<10||G>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let J=b.variantCount===void 0?void 0:Number(b.variantCount);if(J!==void 0&&(!Number.isInteger(J)||J<2||J>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");$=await U("POST",`/api/v1/ab-tests/${b.abTestId}/restart`,{sourceVariantId:F(b,"sourceVariantId"),testType:Y,winnerThreshold:G,variantCount:J},Q);break}case"update_ab_test_variant":{let Q=b.companyId,W=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks","confirmLiveChange"]),X=Object.keys(b).filter((Y)=>!W.has(Y));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((Y)=>`\`${Y}\``).join(", ")}.`);if(vw("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 U("PATCH",`/api/v1/ab-tests/${b.abTestId}/variants/${b.variantId}`,b,Q);break}case"update_ab_test":{let Q=b.companyId,W=Z("update_ab_test",b,"abTestId"),X=new Set(["companyId","abTestId","name","testPercentage","testDurationMinutes","winnerCriteria","testType","winnerThreshold","confirmLiveChange"]),Y=Object.keys(b).filter((L)=>!X.has(L));if(Y.length>0)throw Error(`\`update_ab_test\` received unsupported field${Y.length===1?"":"s"}: ${Y.map((L)=>`\`${L}\``).join(", ")}.`);if(b.confirmLiveChange!==void 0&&typeof b.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test`.");let G=F(b,"name"),J=Uw("update_ab_test",b,"testPercentage",5,50),H=Uw("update_ab_test",b,"testDurationMinutes",15,1440),z=p("update_ab_test",b,"winnerCriteria",["open_rate","click_rate"]),D=p("update_ab_test",b,"testType",["subject","content"]),A=Uw("update_ab_test",b,"winnerThreshold",10,1000);if(G===void 0&&J===void 0&&H===void 0&&z===void 0&&D===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 U("PATCH",`/api/v1/ab-tests/${encodeURIComponent(W)}`,{...G!==void 0&&{name:G},...J!==void 0&&{testPercentage:J},...H!==void 0&&{testDurationMinutes:H},...z!==void 0&&{winnerCriteria:z},...D!==void 0&&{testType:D},...A!==void 0&&{winnerThreshold:A},...b.confirmLiveChange===!0&&{confirmLiveChange:!0}},Q);break}case"create_ab_test":{let Q=b.companyId,W=F(b,"campaignId"),X=F(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(W)===Boolean(X))throw Error("Provide exactly one of `campaignId` or `automationNodeId` when calling `create_ab_test`.");let Y=F(b,"name"),G=Uw("create_ab_test",b,"testPercentage",5,50),J=Uw("create_ab_test",b,"testDurationMinutes",15,1440),H=p("create_ab_test",b,"winnerCriteria",["open_rate","click_rate"]),z=p("create_ab_test",b,"testType",["subject","content"]),D=Uw("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((L,O)=>{if(!v(L)||typeof L.subject!=="string"||L.subject.trim()==="")throw Error(`\`variants\` item ${O+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(L.blocks!==void 0&&!Array.isArray(L.blocks))throw Error(`\`variants\` item ${O+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 U("POST","/api/v1/ab-tests",{...W!==void 0&&{campaignId:W},...X!==void 0&&{automationNodeId:X},...b.confirmLiveChange===!0&&{confirmLiveChange:!0},...Y!==void 0&&{name:Y},...G!==void 0&&{testPercentage:G},...J!==void 0&&{testDurationMinutes:J},...H!==void 0&&{winnerCriteria:H},...z!==void 0&&{testType:z},...D!==void 0&&{winnerThreshold:D},...b.variants!==void 0&&{variants:b.variants}},Q);break}case"add_ab_test_variant":{let Q=b.companyId,W=Z("add_ab_test_variant",b,"abTestId"),X=Z("add_ab_test_variant",b,"subject"),Y=F(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 U("POST",`/api/v1/ab-tests/${encodeURIComponent(W)}/variants`,{subject:X,...Y!==void 0&&{previewText:Y},...b.blocks!==void 0&&{blocks:b.blocks},...b.confirmLiveChange===!0&&{confirmLiveChange:!0}},Q);break}case"delete_ab_test_variant":{let Q=b.companyId,W=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 U("DELETE",`/api/v1/ab-tests/${encodeURIComponent(W)}/variants/${encodeURIComponent(X)}${b.confirmLiveChange===!0?"?confirmLiveChange=true":""}`,void 0,Q);break}case"delete_ab_test":{let Q=b.companyId,W=Z("delete_ab_test",b,"abTestId");$=await U("DELETE",`/api/v1/ab-tests/${encodeURIComponent(W)}`,void 0,Q);break}case"list_campaigns":{let Q=b.companyId,W=new URLSearchParams;if(b.status)W.set("status",String(b.status));let X=F(b,"label");if(X)W.set("label",X);for(let Y of["limit","offset"])if(b[Y]!==void 0)W.set(Y,String(b[Y]));$=await U("GET",`/api/v1/campaigns?${W}`,void 0,Q);break}case"get_campaign":{let Q=b.companyId;$=await U("GET",`/api/v1/campaigns/${b.campaignId}`,void 0,Q);break}case"get_campaign_audience":{let Q=b.companyId;$=await U("GET",`/api/v1/campaigns/${encodeURIComponent(String(b.campaignId))}/audience`,void 0,Q);break}case"get_email_send":{let Q=b.companyId;$=await U("GET",`/api/v1/email-sends/${encodeURIComponent(String(b.emailSendId))}`,void 0,Q);break}case"list_email_sends":{let Q=b.companyId,W=new URLSearchParams,X=["search","subject","recipient","campaignId","transactionalEmailId","automationId"];for(let j of X){let V=F(b,j);if(V)W.set(j,V)}let Y=p("list_email_sends",b,"status",["pending","sent","delivered","opened","clicked","bounced","complained","failed","suppressed"]),G=p("list_email_sends",b,"emailType",["campaign","transactional","sequence"]),J=p("list_email_sends",b,"bounceType",["Permanent","Transient"]),H=p("list_email_sends",b,"sortField",["recipientEmail","subject","status","eventAt","sentAt","createdAt"]),z=p("list_email_sends",b,"sortOrder",["asc","desc"]),D=Uw("list_email_sends",b,"days",1,14),A=Uw("list_email_sends",b,"page",1,Number.MAX_SAFE_INTEGER),L=Uw("list_email_sends",b,"limit",1,100),O=[["status",Y],["emailType",G],["bounceType",J],["sortField",H],["sortOrder",z],["days",D],["page",A],["limit",L]];for(let[j,V]of O)if(V!==void 0)W.set(j,String(V));let K=W.toString();$=await U("GET",`/api/v1/email-sends${K?`?${K}`:""}`,void 0,Q);break}case"create_campaign":{let Q=b.companyId;Lz(b),U0("create_campaign",b);let W=Object.fromEntries(Object.entries(b).filter(([X])=>X!=="companyId"));$=await U("POST","/api/v1/campaigns",W,Q);break}case"update_campaign":{let Q=b.companyId,W=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((Y)=>!W.has(Y));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((Y)=>`\`${Y}\``).join(", ")}.`);if(vw("update_campaign",b),L1("update_campaign",b),U0("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 U("PUT",`/api/v1/campaigns/${b.campaignId}`,b,Q);break}case"schedule_campaign":{let Q=b.companyId,W=new Set(["companyId","campaignId","scheduledAt","targetLists","sendTimeOptimization","spreadOverHours","recurringInterval"]),X=Object.keys(b).filter((Y)=>!W.has(Y));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((Y)=>`\`${Y}\``).join(", ")}.`);Bz(b),$=await U("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}},Q);break}case"send_test_email":{let Q=b.companyId;$=await U("POST",`/api/v1/campaigns/${b.campaignId}/test`,{to:b.to},Q);break}case"cancel_campaign":{let Q=b.companyId,W=Z("cancel_campaign",b,"campaignId");$=await U("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/cancel`,void 0,Q);break}case"unschedule_campaign":{let Q=b.companyId,W=Z("unschedule_campaign",b,"campaignId");$=await U("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/unschedule`,void 0,Q);break}case"pause_campaign":{let Q=b.companyId,W=Z("pause_campaign",b,"campaignId");$=await U("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/pause`,void 0,Q);break}case"resume_campaign":{let Q=b.companyId,W=Z("resume_campaign",b,"campaignId"),X=Uw("resume_campaign",b,"spreadOverHours",1,72);$=await U("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/resume`,{...X!==void 0&&{spreadOverHours:X}},Q);break}case"delete_campaign":{let Q=b.companyId,W=Z("delete_campaign",b,"campaignId");$=await U("DELETE",`/api/v1/campaigns/${encodeURIComponent(W)}`,void 0,Q);break}case"duplicate_campaign":{let Q=b.companyId,W=Z("duplicate_campaign",b,"campaignId"),X=p("duplicate_campaign",b,"mode",["campaign","ab_test","variant"]),Y=F(b,"variantId");if(X==="variant"&&Y===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");$=await U("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/duplicate`,{...X!==void 0&&{mode:X},...Y!==void 0&&{variantId:Y}},Q);break}case"resend_campaign_to_non_openers":{let Q=b.companyId,W=Z("resend_campaign_to_non_openers",b,"campaignId");$=await U("POST",`/api/v1/campaigns/${encodeURIComponent(W)}/resend-to-non-openers`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function A5(w,b){let $;switch(w){case"list_forms":{let Q=b.companyId;$=await U("GET","/api/v1/forms",void 0,Q);break}case"create_form":{let Q=b.companyId,W=Z("create_form",b,"name"),X=Array.isArray(b.listIds)?b.listIds.filter((J)=>typeof J==="string").map((J)=>J.trim()).filter(Boolean):[];if(X.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let Y=p("create_form",b,"duplicateStrategy",["skip","merge","overwrite"]),G={name:W,listIds:X};for(let J of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName"])if(b[J]!==void 0)G[J]=b[J];if(Y!==void 0)G.duplicateStrategy=Y;$=await U("POST","/api/v1/forms",G,Q);break}case"get_form_embed":{let Q=b.companyId,W=Z("get_form_embed",b,"formId");$=await U("GET",`/api/v1/forms/embed/${encodeURIComponent(W)}`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function W4(w,b,$,Q,W){let X=w[b];if(X===void 0)return;if(typeof X!=="number"||!Number.isFinite(X)||X<$||X>Q||W&&!Number.isInteger(X))throw Error(`\`${b}\` must be a ${W?"integer":"number"} between ${$} and ${Q} when calling \`upload_image_asset\`.`);return X}async function L5(w,b){if(w!=="upload_image_asset")return{handled:!1,result:void 0};let $=F(b,"filePath"),Q=F(b,"imageBase64");if($===void 0===(Q===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let W=F(b,"filename");if(Q!==void 0&&W===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let X=W4(b,"sourceWidth",1,20000,!0),Y=W4(b,"sourceHeight",1,20000,!0);if(X===void 0!==(Y===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let G=W4(b,"displayWidthPercent",1,100,!1)??100,J=W4(b,"cropHeight",1,2000,!0),H=F(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&&J===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let z=F(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 D=typeof b.altText==="string"?b.altText.trim():void 0;if(D!==void 0&&D.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let A=await Rz({companyId:F(b,"companyId"),filePath:$,imageBase64:Q,filename:W,contentType:F(b,"contentType"),altText:D,sourceWidth:X,sourceHeight:Y}),L={type:"image",src:A.url,alt:A.altText??"",width:G,widthType:"percent",...J!==void 0&&{height:J,objectFit:H??"cover"},...z!==void 0&&{align:z}};return{handled:!0,result:{success:!0,asset:A,imageBlock:L,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}async function F5(w,b){let $;switch(w){case"list_landing_pages":{let Q=b.companyId;$=await U("GET","/api/v1/landing-pages",void 0,Q);break}case"get_landing_page":{let Q=b.companyId;$=await U("GET",`/api/v1/landing-pages/${b.landingPageId}`,void 0,Q);break}case"create_landing_page":{let Q=b.companyId,W=new Set(["companyId","name","slug","template","content"]),X=Object.keys(b).filter((Y)=>!W.has(Y));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((Y)=>`\`${Y}\``).join(", ")}.`);$=await U("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}},Q);break}case"update_landing_page":{let Q=b.companyId,W=r$("update_landing_page",b,{requireUpdate:!0});$=await U("PUT",`/api/v1/landing-pages/${b.landingPageId}`,W,Q);break}case"publish_landing_page":{let Q=b.companyId,W=r$("publish_landing_page",b,{requireUpdate:!1});$=await U("POST",`/api/v1/landing-pages/${b.landingPageId}/publish`,W,Q);break}case"unpublish_landing_page":{let Q=b.companyId,W=r$("unpublish_landing_page",b,{requireUpdate:!1});$=await U("POST",`/api/v1/landing-pages/${b.landingPageId}/unpublish`,W,Q);break}case"duplicate_landing_page":{let Q=b.companyId;$=await U("POST",`/api/v1/landing-pages/${b.landingPageId}/duplicate`,{...b.name!==void 0&&{name:b.name},...b.slug!==void 0&&{slug:b.slug}},Q);break}case"delete_landing_page":{let Q=b.companyId;$=await U("DELETE",`/api/v1/landing-pages/${b.landingPageId}`,void 0,Q);break}case"connect_landing_page_domain":{let Q=b.companyId;$=await U("POST","/api/v1/landing-pages/domain",{domain:b.domain},Q);break}case"update_landing_page_domain_settings":{let Q=b.companyId,W=Oz(b);$=await U("PUT","/api/v1/landing-pages/domain",W,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function B5(w,b){let $;switch(w){case"list_products":{let Q=b.companyId,W=new URLSearchParams;if(typeof b.provider==="string"&&b.provider.trim())W.set("provider",b.provider.trim());if(typeof b.search==="string"&&b.search.trim())W.set("search",b.search.trim());let X=Uw("list_products",b,"limit",1,100);if(X!==void 0)W.set("limit",String(X));let Y=Uw("list_products",b,"offset",0,Number.MAX_SAFE_INTEGER);if(Y!==void 0)W.set("offset",String(Y));let G=W.size>0?`?${W.toString()}`:"";$=await U("GET",`/api/v1/products${G}`,void 0,Q);break}case"upsert_products":{let Q=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 U("POST","/api/v1/products",{products:b.products},Q);break}case"delete_product":{let Q=b.companyId,W=Z("delete_product",b,"productId");$=await U("DELETE",`/api/v1/products/${encodeURIComponent(W)}`,void 0,Q);break}case"attach_product_file":{let Q=b.companyId,W=Z("attach_product_file",b,"productId"),X=F(b,"url"),Y=F(b,"filePath");if(X===void 0===(Y===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let G;if(Y!==void 0){let J=await Vz(Y,Q);G={url:J.url,source:"upload",fileName:F(b,"fileName")??J.fileName,fileSizeBytes:J.fileSizeBytes,mimeType:J.mimeType}}else{G={url:X};let J=F(b,"fileName");if(J)G.fileName=J}$=await U("PUT",`/api/v1/products/${encodeURIComponent(W)}/delivery`,G,Q);break}case"remove_product_file":{let Q=b.companyId,W=Z("remove_product_file",b,"productId");$=await U("DELETE",`/api/v1/products/${encodeURIComponent(W)}/delivery`,void 0,Q);break}case"sync_products":{let Q=b.companyId;$=await U("POST","/api/v1/products/sync",void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function PP(w){let b=F(w,"campaignId"),$=F(w,"sequenceId"),Q=F(w,"templateId"),W=[b,$,Q].filter((X)=>X!==void 0);if(W.length===0)throw Error("render_email requires one of campaignId, sequenceId plus nodeId, or templateId.");if(W.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(Q)}/render`}var VP=["subscriberId","subscriber","variables","locale","variantId","tracking"];async function O5(w,b){if(w!=="render_email")return{handled:!1,result:void 0};let $=PP(b),Q={};for(let X of VP)if(b[X]!==void 0)Q[X]=b[X];return{handled:!0,result:await U("POST",$,Q,F(b,"companyId"))}}var M5=80,K5=10;function jP(w){if(!Array.isArray(w.recipients))throw Error("`recipients` must be an array when calling `send_sequence_test_email`.");if(w.recipients.length>K5)throw Error(`\`recipients\` must include no more than ${K5} email addresses when calling \`send_sequence_test_email\`.`);if(w.recipients.find((W)=>typeof W!=="string"||W.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((W)=>typeof W==="string"?W.trim().toLowerCase():""))).filter(Boolean);if($.length===0)throw Error("`recipients` must include at least one email address when calling `send_sequence_test_email`.");let Q=$.find((W)=>!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(W));if(Q)throw Error(`Invalid test recipient email address: \`${Q}\`.`);return $}function IP(w){let b=w.trim().replace(/\s+/g," ");if(b.length<=M5)return b;return`${b.slice(0,M5-3).trimEnd()}...`}async function bQ(w,b){let $;switch(w){case"generate_sequence":{let Q=Z("generate_sequence",b,"goal"),W=typeof b.name==="string"&&b.name.trim().length>0?b.name.trim():void 0,Y=(await bQ("create_sequence",{...b,goal:Q,name:W??IP(Q),trigger:"contact_added",durationDays:b.durationDays??14})).result;return{handled:!0,result:typeof Y==="object"&&Y!==null?{...Y,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:Y}}case"list_sequences":{let Q=b.companyId,W=new URLSearchParams;for(let Y of["status","search","limit","offset"])if(b[Y]!==void 0)W.set(Y,String(b[Y]));if(Array.isArray(b.labels)&&b.labels.length>0)W.set("labels",b.labels.join(","));let X=W.size>0?`?${W.toString()}`:"";$=await U("GET",`/api/v1/sequences${X}`,void 0,Q);break}case"get_sequence":{let Q=b.companyId;$=await U("GET",`/api/v1/sequences/${b.sequenceId}`,void 0,Q);break}case"list_sequence_enrollments":{let Q=b.companyId,W=Z(w,b,"sequenceId"),X=new URLSearchParams;for(let G of["currentNodeId","status","subscriberId"]){let J=b[G];if(Array.isArray(J)){if(J.length>0)X.set(G,J.join(","))}else if(J!==void 0)X.set(G,String(J))}for(let G of["email","sort","limit","offset"])if(b[G]!==void 0)X.set(G,String(b[G]));let Y=X.size>0?`?${X.toString()}`:"";$=await U("GET",`/api/v1/sequences/${encodeURIComponent(W)}/enrollments${Y}`,void 0,Q);break}case"send_sequence_test_email":{let Q=b.companyId,W=Z(w,b,"sequenceId"),X=Z(w,b,"nodeId"),Y=jP(b);$=await U("POST",`/api/v1/sequences/${encodeURIComponent(W)}/nodes/${encodeURIComponent(X)}/test`,{recipients:Y},Q);break}case"create_sequence":{let Q=b.companyId;L1("create_sequence",b),U0("create_sequence",b);let W=Array.isArray(b.steps),X=b.goal===void 0&&b.steps===void 0,Y=await U("POST","/api/v1/sequences",b,Q);if(!Y.success){$=Y;break}let G=Y.sequence.id;if(W||X){let A=await U("GET",`/api/v1/sequences/${G}`,void 0,Q);if(A.success)$={...Y,success:!0,sequence:A.sequence,message:`Sequence "${A.sequence.name}" created ${X?"as a blank draft":"with explicit steps"}. Review it before enabling.${Y.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=A;break}let J=7,H=0,z="pending";while(z!=="complete"&&H<J){let A=await U("GET",`/api/v1/sequences/${G}`,void 0,Q);if(A.success)z=A.sequence.enrichmentStatus;if(H++,z!=="complete"&&H<J)await new Promise((L)=>setTimeout(L,20000))}let D=await U("GET",`/api/v1/sequences/${G}`,void 0,Q);if(D.success)$={...Y,success:!0,sequence:D.sequence,message:D.sequence.enrichmentStatus==="complete"?`Sequence "${D.sequence.name}" created with ${D.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${Y.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${D.sequence.name}" created. Email enrichment is still in progress (${D.sequence.enrichedCount}/${D.sequence.emailCount} emails generated). You can check status with get_sequence.${Y.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else $=D;break}case"update_sequence":{let Q=b.companyId,W=Wz(b);$=await U("PUT",`/api/v1/sequences/${b.sequenceId}`,W,Q);break}case"update_sequence_node":{let Q=b.companyId,W=Z("update_sequence_node",b,"sequenceId"),X=Hz(b);$=await U("PUT",`/api/v1/sequences/${W}`,X,Q);break}case"update_sequence_nodes":{let Q=b.companyId,W=Z("update_sequence_nodes",b,"sequenceId"),X=zz(b);$=await U("PUT",`/api/v1/sequences/${W}`,X,Q);break}case"edit_sequence_graph":{let Q=b.companyId,W=Dz(b);$=await U("PUT",`/api/v1/sequences/${b.sequenceId}`,W,Q);break}case"insert_sequence_step":{let Q=b.companyId,W=Uz(b),X=await U("PUT",`/api/v1/sequences/${b.sequenceId}`,W,Q);if(typeof X==="object"&&X!==null){let Y=X,G=Y.sequence;if(typeof G==="object"&&G!==null){let J=G;$={...Y,...J.insertedNodeIds!==void 0?{insertedNodeIds:J.insertedNodeIds}:{},...J.insertedEmailIds!==void 0?{insertedEmailIds:J.insertedEmailIds}:{},...J.insertedEmailCount!==void 0?{insertedEmailCount:J.insertedEmailCount}:{},...J.addedBranchNodeId!==void 0?{addedBranchNodeId:J.addedBranchNodeId}:{},...J.addedBranchPathNodeIds!==void 0?{addedBranchPathNodeIds:J.addedBranchPathNodeIds}:{}};break}}$=X;break}case"enable_sequence":{let Q=b.companyId;$=await U("POST",`/api/v1/sequences/${b.sequenceId}/enable`,void 0,Q);break}case"disable_sequence":{let Q=b.companyId;$=await U("POST",`/api/v1/sequences/${b.sequenceId}/disable`,void 0,Q);break}case"duplicate_sequence":{let Q=b.companyId,W=Z("duplicate_sequence",b,"sequenceId"),X=F(b,"name");$=await U("POST",`/api/v1/sequences/${encodeURIComponent(W)}/duplicate`,X===void 0?void 0:{name:X},Q);break}case"archive_sequence":case"unarchive_sequence":{let Q=b.companyId,W=Z(w,b,"sequenceId"),X=w==="archive_sequence"?"archive":"unarchive";$=await U("POST",`/api/v1/sequences/${encodeURIComponent(W)}/${X}`,void 0,Q);break}case"list_sequence_goals":{let Q=b.companyId,W=Z(w,b,"sequenceId");$=await U("GET",`/api/v1/sequences/${encodeURIComponent(W)}/goals`,void 0,Q);break}case"create_sequence_goal":case"update_sequence_goal":{let Q=b.companyId,W=Z(w,b,"sequenceId");if(w==="create_sequence_goal")Z(w,b,"name"),Xz(b);else Yz(b);let X=w==="update_sequence_goal"?Z(w,b,"goalId"):void 0,Y={...b};delete Y.companyId,delete Y.sequenceId,delete Y.goalId,$=await U(w==="create_sequence_goal"?"POST":"PATCH",`/api/v1/sequences/${encodeURIComponent(W)}/goals${X?`/${encodeURIComponent(X)}`:""}`,Y,Q);break}case"delete_sequence_goal":{let Q=b.companyId,W=Z(w,b,"sequenceId"),X=Z(w,b,"goalId");$=await U("DELETE",`/api/v1/sequences/${encodeURIComponent(W)}/goals/${encodeURIComponent(X)}`,void 0,Q);break}case"get_sequence_inbound_webhook":case"configure_sequence_inbound_webhook":case"rotate_sequence_inbound_webhook_secret":{let Q=b.companyId,W=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",Y=w==="rotate_sequence_inbound_webhook_secret",G=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 U(Y?"POST":X?"PUT":"GET",`/api/v1/sequences/${encodeURIComponent(W)}/inbound-webhook${Y?"/rotate-secret":""}`,G,Q);break}case"pause_sequence_enrollments":{let Q=b.companyId;$=await U("POST",`/api/v1/sequences/${b.sequenceId}/pause-enrollments`,void 0,Q);break}case"resume_sequence_enrollments":{let Q=b.companyId;$=await U("POST",`/api/v1/sequences/${b.sequenceId}/resume-enrollments`,void 0,Q);break}case"enroll_subscribers_in_sequence":{let Q=b.companyId,W=Z("enroll_subscribers_in_sequence",b,"sequenceId"),X=Pz(b);$=await U("POST",`/api/v1/sequences/${encodeURIComponent(W)}/enroll`,X,Q);break}case"cancel_sequence_enrollments":{let Q=b.companyId,W=Az(b);$=await U("POST",`/api/v1/sequences/${b.sequenceId}/enrollments/cancel`,W,Q);break}case"delete_sequence":{let Q=b.companyId;$=await U("DELETE",`/api/v1/sequences/${b.sequenceId}`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}function X4(w,b,$){let Q=b[$];if(Q===void 0)return;if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array of strings when calling \`${w}\`.`);let W=Q.filter((X)=>typeof X==="string").map((X)=>X.trim()).filter((X)=>X.length>0);if(W.length!==Q.length)throw Error(`\`${$}\` must contain only non-empty strings when calling \`${w}\`.`);return W}function NP(w,b){let $=X4(w,b,"tags");if($===void 0||$.length===0)throw Error(`\`tags\` must contain at least one tag when calling \`${w}\`.`);let Q=X4(w,b,"emails"),W=X4(w,b,"externalIds"),X=X4(w,b,"subscriberIds");if((Q?.length??0)+(W?.length??0)+(X?.length??0)===0)throw Error(`Provide \`emails\`, \`externalIds\`, or \`subscriberIds\` when calling \`${w}\`.`);return{tags:$,...Q?.length?{emails:Q}:{},...W?.length?{externalIds:W}:{},...X?.length?{subscriberIds:X}:{},...w==="bulk_add_subscriber_tags"&&typeof b.triggerAutomations==="boolean"?{triggerAutomations:b.triggerAutomations}:{}}}async function q5(w,b){let $;switch(w){case"add_subscriber":{let Q=b.companyId,W=dw("add_subscriber",b),X=p("add_subscriber",b,"status",["active","unsubscribed","bounced"]),Y=p("add_subscriber",b,"optInMode",["default","confirmed","double_opt_in"]);if($=await U("POST","/api/v1/subscribers",{...W,...b.firstName!==void 0&&{firstName:b.firstName},...b.lastName!==void 0&&{lastName:b.lastName},customAttributes:b.attributes,tags:b.tags,lists:b.listIds,...X!==void 0&&{status:X},...Y!==void 0&&{optInMode:Y}},Q),X!==void 0&&v($)&&v($.subscriber)&&$.subscriber.skipped===!0&&$.subscriber.status!==X)throw Error(`Existing subscriber was not changed to status '${X}'. Use update_subscriber to change an existing contact's status.`);break}case"create_subscriber_import":{let Q=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 Y=0;Y<b.subscribers.length;Y+=1){let G=b.subscribers[Y];if(!v(G)||typeof G.email!=="string"||G.email.trim()==="")throw Error(`Subscriber record ${Y} must include a non-empty email string.`)}let W=p("create_subscriber_import",b,"duplicateStrategy",["skip","merge","overwrite"]),X=p("create_subscriber_import",b,"optInMode",["default","confirmed","double_opt_in"]);$=await U("POST","/api/v1/subscribers/imports",{subscribers:b.subscribers,...W!==void 0&&{duplicateStrategy:W},...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}},Q);break}case"get_subscriber_import":{let Q=b.companyId,W=Z("get_subscriber_import",b,"importId");$=await U("GET",`/api/v1/subscribers/imports/${encodeURIComponent(W)}`,void 0,Q);break}case"update_subscriber":{let Q=b.companyId,W=dw("update_subscriber",b),X=p("update_subscriber",b,"status",["active","unsubscribed","bounced"]),G=v(b.attributes)||b.addTags!==void 0||b.removeTags!==void 0?await Ob(W,Q):null,J=Array.isArray(G?.subscriber.tags)?G.subscriber.tags.filter((L)=>typeof L==="string"):[],H=Array.isArray(b.addTags)?b.addTags.filter((L)=>typeof L==="string"&&L.trim()!=="").map(i9):[],z=new Set(Array.isArray(b.removeTags)?b.removeTags.filter((L)=>typeof L==="string"&&L.trim()!=="").map(i9):[]),D=J.filter((L)=>!z.has(L));for(let L of H)if(!D.includes(L))D.push(L);let A={};if(W.email&&W.externalId)A.externalId=W.externalId;if(b.firstName!==void 0)A.firstName=b.firstName;if(b.lastName!==void 0)A.lastName=b.lastName;if(X!==void 0)A.status=X;if(v(b.attributes))A.customAttributes={...v(G?.subscriber.customAttributes)?G.subscriber.customAttributes:{},...b.attributes};if(b.addTags||b.removeTags)A.tags=D;$=await U("PATCH",s$(W),A,Q);break}case"remove_subscriber":{let Q=b.companyId,W=dw("remove_subscriber",b),X=s$(W);if(b.hardDelete===!0)$=await U("DELETE",X,void 0,Q);else $=await U("PATCH",X,{status:"unsubscribed"},Q);break}case"get_subscriber":{let Q=b.companyId,W=dw("get_subscriber",b);$=await Ob(W,Q,{includeMachineEngagement:b.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let Q=b.companyId,W=dw("list_subscriber_notes",b);$=await U("GET",n9(W),void 0,Q);break}case"add_subscriber_note":{let Q=b.companyId,W=dw("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 U("POST",n9(W),{body:X},Q);break}case"delete_subscriber_note":{let Q=b.companyId,W=typeof b.noteId==="string"?b.noteId.trim():"";if(!W)throw Error("`noteId` is required when calling `delete_subscriber_note`.");$=await U("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(W)}`,void 0,Q);break}case"trigger_subscriber_event":{let Q=b.companyId,W=dw("trigger_subscriber_event",b),X=Z("trigger_subscriber_event",b,"event");if(b.properties!==void 0&&!v(b.properties))throw Error("`properties` must be an object when calling `trigger_subscriber_event`.");$=await U("POST","/api/v1/subscribers/events",{...W,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}},Q);break}case"trigger_subscriber_events":{let Q=b.companyId,W=dw("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`.");for(let X=0;X<b.events.length;X+=1){let Y=b.events[X];if(!v(Y)||typeof Y.name!=="string"||Y.name.trim()==="")throw Error(`Event ${X} must include a non-empty \`name\` string.`)}$=await U("POST","/api/v1/subscribers/events/bulk",{...W,events:b.events,...b.firstName!==void 0&&{firstName:b.firstName},...b.lastName!==void 0&&{lastName:b.lastName},...b.attributes!==void 0&&{customAttributes:b.attributes}},Q);break}case"bulk_add_subscriber_tags":case"bulk_remove_subscriber_tags":{let Q=b.companyId,W=NP(w,b);$=await U("POST",`/api/v1/subscribers/bulk/tags/${w==="bulk_add_subscriber_tags"?"add":"remove"}`,W,Q);break}case"search_subscribers":{let Q=b.companyId;$=await Zz(b,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}async function Z5(w,b){if(w!=="get_recipient_suppression"&&w!=="remove_recipient_suppression")return{handled:!1,result:void 0};let $=F(b,"companyId"),Q=Z(w,b,"email"),W=F(b,"region"),X=new URLSearchParams;if(W)X.set("region",W);let Y=`/api/v1/suppressions/${encodeURIComponent(Q)}${X.size>0?`?${X}`:""}`;return{handled:!0,result:await U(w==="get_recipient_suppression"?"GET":"DELETE",Y,void 0,$)}}async function P5(w,b){let $;switch(w){case"list_team_members":{let Q=b.companyId;$=await U("GET","/api/v1/team",void 0,Q);break}case"invite_team_member":{let Q=b.companyId,W=Z("invite_team_member",b,"email"),X=Mb("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 U("POST","/api/v1/team/invitations",{email:W,role:X,...b.canManageBilling!==void 0&&{canManageBilling:b.canManageBilling}},Q);break}case"cancel_team_invitation":{let Q=b.companyId,W=Z("cancel_team_invitation",b,"invitationId");$=await U("DELETE",`/api/v1/team/invitations/${encodeURIComponent(W)}`,void 0,Q);break}case"list_conversations":{let Q=b.companyId,W=new URLSearchParams,X=p("list_conversations",b,"status",["open","closed","all"]);if(X)W.set("status",X);let Y=F(b,"search");if(Y)W.set("search",Y);if(b.unread!==void 0){if(typeof b.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(b.unread)W.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`.");W.set("page",String(b.page))}let G=Uw("list_conversations",b,"limit",1,100);if(G!==void 0)W.set("limit",String(G));$=await U("GET",`/api/v1/conversations${W.size>0?`?${W}`:""}`,void 0,Q);break}case"get_conversation":{let Q=b.companyId,W=Z("get_conversation",b,"conversationId");$=await U("GET",`/api/v1/conversations/${encodeURIComponent(W)}`,void 0,Q);break}case"reply_to_conversation":{let Q=b.companyId,W=Z("reply_to_conversation",b,"conversationId"),X=p("reply_to_conversation",b,"type",["outbound","note"])??"outbound",Y=F(b,"subject"),G=F(b,"bodyText"),J=F(b,"bodyHtml");if(X==="outbound"&&G===void 0&&J===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");$=await U("POST",`/api/v1/conversations/${encodeURIComponent(W)}/messages`,{type:X,...Y!==void 0&&{subject:Y},...G!==void 0&&{bodyText:G},...J!==void 0&&{bodyHtml:J}},Q);break}case"update_conversation_status":{let Q=b.companyId,W=Z("update_conversation_status",b,"conversationId"),X=Mb("update_conversation_status",b,"status",["open","closed"]);$=await U("POST",`/api/v1/conversations/${encodeURIComponent(W)}/status`,{status:X},Q);break}case"mark_conversation_read":{let Q=b.companyId,W=Z("mark_conversation_read",b,"conversationId");$=await U("POST",`/api/v1/conversations/${encodeURIComponent(W)}/read`,void 0,Q);break}case"list_webhooks":{let Q=b.companyId;$=await U("GET","/api/v1/webhooks",void 0,Q);break}case"create_webhook":{let Q=b.companyId,W=Z("create_webhook",b,"name"),X=Z("create_webhook",b,"url"),Y=o9("create_webhook",b);$=await U("POST","/api/v1/webhooks",{name:W,url:X,...Y!==void 0&&{events:Y}},Q);break}case"update_webhook":{let Q=b.companyId,W=Z("update_webhook",b,"webhookId"),X=F(b,"name"),Y=F(b,"url"),G=o9("update_webhook",b),J=p("update_webhook",b,"status",["enabled","disabled"]);if(X===void 0&&Y===void 0&&G===void 0&&J===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");$=await U("PATCH",`/api/v1/webhooks/${encodeURIComponent(W)}`,{...X!==void 0&&{name:X},...Y!==void 0&&{url:Y},...G!==void 0&&{events:G},...J!==void 0&&{status:J}},Q);break}case"delete_webhook":{let Q=b.companyId,W=Z("delete_webhook",b,"webhookId");$=await U("DELETE",`/api/v1/webhooks/${encodeURIComponent(W)}`,void 0,Q);break}case"test_webhook":{let Q=b.companyId,W=Z("test_webhook",b,"webhookId");$=await U("POST",`/api/v1/webhooks/${encodeURIComponent(W)}/test`,void 0,Q);break}case"list_webhook_deliveries":{let Q=b.companyId,W=Z("list_webhook_deliveries",b,"webhookId"),X=Uw("list_webhook_deliveries",b,"limit",1,100),Y=new URLSearchParams;if(X!==void 0)Y.set("limit",String(X));$=await U("GET",`/api/v1/webhooks/${encodeURIComponent(W)}/deliveries${Y.size>0?`?${Y}`:""}`,void 0,Q);break}case"replay_webhook_delivery":{let Q=b.companyId,W=Z("replay_webhook_delivery",b,"webhookId"),X=Z("replay_webhook_delivery",b,"deliveryId");$=await U("POST",`/api/v1/webhooks/${encodeURIComponent(W)}/deliveries/${encodeURIComponent(X)}/replay`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:$}}var V5=[J5,q5,Z5,B5,D5,U5,O5,A5,F5,L5,bQ,z5,P5,H5];var EP=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 j5(w){return typeof w==="object"&&w!==null&&!Array.isArray(w)}function $Q(w){if(Array.isArray(w))return w.some($Q);if(!j5(w))return!1;for(let[b,$]of Object.entries(w)){if((b==="html"||b==="htmlContent")&&typeof $==="string"&&$.trim().length>0)return!0;if($Q($))return!0}return!1}function I5(w,b,$){if(!EP.has(w)||!$Q(b)||!j5($))return $;let Q=Array.isArray($.warnings)?$.warnings.filter((W)=>typeof W==="string"):[];return{...$,warnings:[...new Set([...Q,Jw])]}}var N5=G5.map(_z).map(dH);async function E5(w,b){try{let $,Q=!1;for(let X of V5){let Y=await X(w,b);if(Y.handled){$=Y.result,Q=!0;break}}if(!Q)throw Error(`Unknown tool: ${w}`);let W=Kz($);if(W)throw W;return $=I5(w,b,$),$=await Iz(w,b,$),{structuredContent:kz($),content:[{type:"text",text:JSON.stringify($,null,2)}]}}catch($){return{isError:!0,content:[{type:"text",text:F1($)}]}}}async function T5(w,b,$){let Q=b.getRequestContext?.(w)??{};try{return await z4(Q,$)}finally{await b.onRequestContextUpdated?.(Q,w)}}function QQ(w={}){let b=new P9({name:"sequenzy",version:gH.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(H6,async()=>{return{tools:N5}}),b.setRequestHandler(c0,async($,Q)=>{let{name:W,arguments:X}=$.params;return T5(Q,w,()=>E5(W,X??{}))}),b.setRequestHandler($6,async()=>{return{resources:nH}}),b.setRequestHandler(W6,async($,Q)=>{let{uri:W}=$.params;return T5(Q,w,()=>pH(W))}),b}import S5 from"node:process";class WQ{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),TP(b)}clear(){this._buffer=void 0}}function TP(w){return sX.parse(JSON.parse(w))}function R5(w){return JSON.stringify(w)+`
|
|
54
|
+
`}class XQ{constructor(w=S5.stdin,b=S5.stdout){this._stdin=w,this._stdout=b,this._readBuffer=new WQ,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 $=R5(w);if(this._stdout.write($))b();else this._stdout.once("drain",b)})}}async function RP(){BQ(),DQ();let w=QQ(),b=new XQ;await w.connect(b),console.error("Sequenzy MCP server running on stdio")}RP().catch((w)=>{console.error(F1(w)),process.exit(1)});export{z4 as withMcpRequestContext,qb as setSelectedCompanyId,B1 as getSelectedCompanyId,QQ as createSequenzyMcpServer,U as apiRequest};
|